OSDN Git Service

PR c++/48535
[pf3gnuchains/gcc-fork.git] / gcc / cp / semantics.c
1 /* Perform the semantic phase of parsing, i.e., the process of
2    building tree structure, checking semantic consistency, and
3    building RTL.  These routines are used both during actual parsing
4    and during the instantiation of template functions.
5
6    Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
7                  2008, 2009, 2010, 2011 Free Software Foundation, Inc.
8    Written by Mark Mitchell (mmitchell@usa.net) based on code found
9    formerly in parse.y and pt.c.
10
11    This file is part of GCC.
12
13    GCC is free software; you can redistribute it and/or modify it
14    under the terms of the GNU General Public License as published by
15    the Free Software Foundation; either version 3, or (at your option)
16    any later version.
17
18    GCC is distributed in the hope that it will be useful, but
19    WITHOUT ANY WARRANTY; without even the implied warranty of
20    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21    General Public License for more details.
22
23 You should have received a copy of the GNU General Public License
24 along with GCC; see the file COPYING3.  If not see
25 <http://www.gnu.org/licenses/>.  */
26
27 #include "config.h"
28 #include "system.h"
29 #include "coretypes.h"
30 #include "tm.h"
31 #include "tree.h"
32 #include "cp-tree.h"
33 #include "c-family/c-common.h"
34 #include "c-family/c-objc.h"
35 #include "tree-inline.h"
36 #include "tree-mudflap.h"
37 #include "toplev.h"
38 #include "flags.h"
39 #include "output.h"
40 #include "timevar.h"
41 #include "diagnostic.h"
42 #include "cgraph.h"
43 #include "tree-iterator.h"
44 #include "vec.h"
45 #include "target.h"
46 #include "gimple.h"
47 #include "bitmap.h"
48
49 /* There routines provide a modular interface to perform many parsing
50    operations.  They may therefore be used during actual parsing, or
51    during template instantiation, which may be regarded as a
52    degenerate form of parsing.  */
53
54 static tree maybe_convert_cond (tree);
55 static tree finalize_nrv_r (tree *, int *, void *);
56 static tree capture_decltype (tree);
57 static tree thisify_lambda_field (tree);
58
59
60 /* Deferred Access Checking Overview
61    ---------------------------------
62
63    Most C++ expressions and declarations require access checking
64    to be performed during parsing.  However, in several cases,
65    this has to be treated differently.
66
67    For member declarations, access checking has to be deferred
68    until more information about the declaration is known.  For
69    example:
70
71      class A {
72          typedef int X;
73        public:
74          X f();
75      };
76
77      A::X A::f();
78      A::X g();
79
80    When we are parsing the function return type `A::X', we don't
81    really know if this is allowed until we parse the function name.
82
83    Furthermore, some contexts require that access checking is
84    never performed at all.  These include class heads, and template
85    instantiations.
86
87    Typical use of access checking functions is described here:
88
89    1. When we enter a context that requires certain access checking
90       mode, the function `push_deferring_access_checks' is called with
91       DEFERRING argument specifying the desired mode.  Access checking
92       may be performed immediately (dk_no_deferred), deferred
93       (dk_deferred), or not performed (dk_no_check).
94
95    2. When a declaration such as a type, or a variable, is encountered,
96       the function `perform_or_defer_access_check' is called.  It
97       maintains a VEC of all deferred checks.
98
99    3. The global `current_class_type' or `current_function_decl' is then
100       setup by the parser.  `enforce_access' relies on these information
101       to check access.
102
103    4. Upon exiting the context mentioned in step 1,
104       `perform_deferred_access_checks' is called to check all declaration
105       stored in the VEC. `pop_deferring_access_checks' is then
106       called to restore the previous access checking mode.
107
108       In case of parsing error, we simply call `pop_deferring_access_checks'
109       without `perform_deferred_access_checks'.  */
110
111 typedef struct GTY(()) deferred_access {
112   /* A VEC representing name-lookups for which we have deferred
113      checking access controls.  We cannot check the accessibility of
114      names used in a decl-specifier-seq until we know what is being
115      declared because code like:
116
117        class A {
118          class B {};
119          B* f();
120        }
121
122        A::B* A::f() { return 0; }
123
124      is valid, even though `A::B' is not generally accessible.  */
125   VEC (deferred_access_check,gc)* GTY(()) deferred_access_checks;
126
127   /* The current mode of access checks.  */
128   enum deferring_kind deferring_access_checks_kind;
129
130 } deferred_access;
131 DEF_VEC_O (deferred_access);
132 DEF_VEC_ALLOC_O (deferred_access,gc);
133
134 /* Data for deferred access checking.  */
135 static GTY(()) VEC(deferred_access,gc) *deferred_access_stack;
136 static GTY(()) unsigned deferred_access_no_check;
137
138 /* Save the current deferred access states and start deferred
139    access checking iff DEFER_P is true.  */
140
141 void
142 push_deferring_access_checks (deferring_kind deferring)
143 {
144   /* For context like template instantiation, access checking
145      disabling applies to all nested context.  */
146   if (deferred_access_no_check || deferring == dk_no_check)
147     deferred_access_no_check++;
148   else
149     {
150       deferred_access *ptr;
151
152       ptr = VEC_safe_push (deferred_access, gc, deferred_access_stack, NULL);
153       ptr->deferred_access_checks = NULL;
154       ptr->deferring_access_checks_kind = deferring;
155     }
156 }
157
158 /* Resume deferring access checks again after we stopped doing
159    this previously.  */
160
161 void
162 resume_deferring_access_checks (void)
163 {
164   if (!deferred_access_no_check)
165     VEC_last (deferred_access, deferred_access_stack)
166       ->deferring_access_checks_kind = dk_deferred;
167 }
168
169 /* Stop deferring access checks.  */
170
171 void
172 stop_deferring_access_checks (void)
173 {
174   if (!deferred_access_no_check)
175     VEC_last (deferred_access, deferred_access_stack)
176       ->deferring_access_checks_kind = dk_no_deferred;
177 }
178
179 /* Discard the current deferred access checks and restore the
180    previous states.  */
181
182 void
183 pop_deferring_access_checks (void)
184 {
185   if (deferred_access_no_check)
186     deferred_access_no_check--;
187   else
188     VEC_pop (deferred_access, deferred_access_stack);
189 }
190
191 /* Returns a TREE_LIST representing the deferred checks.
192    The TREE_PURPOSE of each node is the type through which the
193    access occurred; the TREE_VALUE is the declaration named.
194    */
195
196 VEC (deferred_access_check,gc)*
197 get_deferred_access_checks (void)
198 {
199   if (deferred_access_no_check)
200     return NULL;
201   else
202     return (VEC_last (deferred_access, deferred_access_stack)
203             ->deferred_access_checks);
204 }
205
206 /* Take current deferred checks and combine with the
207    previous states if we also defer checks previously.
208    Otherwise perform checks now.  */
209
210 void
211 pop_to_parent_deferring_access_checks (void)
212 {
213   if (deferred_access_no_check)
214     deferred_access_no_check--;
215   else
216     {
217       VEC (deferred_access_check,gc) *checks;
218       deferred_access *ptr;
219
220       checks = (VEC_last (deferred_access, deferred_access_stack)
221                 ->deferred_access_checks);
222
223       VEC_pop (deferred_access, deferred_access_stack);
224       ptr = VEC_last (deferred_access, deferred_access_stack);
225       if (ptr->deferring_access_checks_kind == dk_no_deferred)
226         {
227           /* Check access.  */
228           perform_access_checks (checks);
229         }
230       else
231         {
232           /* Merge with parent.  */
233           int i, j;
234           deferred_access_check *chk, *probe;
235
236           FOR_EACH_VEC_ELT (deferred_access_check, checks, i, chk)
237             {
238               FOR_EACH_VEC_ELT (deferred_access_check,
239                                 ptr->deferred_access_checks, j, probe)
240                 {
241                   if (probe->binfo == chk->binfo &&
242                       probe->decl == chk->decl &&
243                       probe->diag_decl == chk->diag_decl)
244                     goto found;
245                 }
246               /* Insert into parent's checks.  */
247               VEC_safe_push (deferred_access_check, gc,
248                              ptr->deferred_access_checks, chk);
249             found:;
250             }
251         }
252     }
253 }
254
255 /* Perform the access checks in CHECKS.  The TREE_PURPOSE of each node
256    is the BINFO indicating the qualifying scope used to access the
257    DECL node stored in the TREE_VALUE of the node.  */
258
259 void
260 perform_access_checks (VEC (deferred_access_check,gc)* checks)
261 {
262   int i;
263   deferred_access_check *chk;
264
265   if (!checks)
266     return;
267
268   FOR_EACH_VEC_ELT (deferred_access_check, checks, i, chk)
269     enforce_access (chk->binfo, chk->decl, chk->diag_decl);
270 }
271
272 /* Perform the deferred access checks.
273
274    After performing the checks, we still have to keep the list
275    `deferred_access_stack->deferred_access_checks' since we may want
276    to check access for them again later in a different context.
277    For example:
278
279      class A {
280        typedef int X;
281        static X a;
282      };
283      A::X A::a, x;      // No error for `A::a', error for `x'
284
285    We have to perform deferred access of `A::X', first with `A::a',
286    next with `x'.  */
287
288 void
289 perform_deferred_access_checks (void)
290 {
291   perform_access_checks (get_deferred_access_checks ());
292 }
293
294 /* Defer checking the accessibility of DECL, when looked up in
295    BINFO. DIAG_DECL is the declaration to use to print diagnostics.  */
296
297 void
298 perform_or_defer_access_check (tree binfo, tree decl, tree diag_decl)
299 {
300   int i;
301   deferred_access *ptr;
302   deferred_access_check *chk;
303   deferred_access_check *new_access;
304
305
306   /* Exit if we are in a context that no access checking is performed.
307      */
308   if (deferred_access_no_check)
309     return;
310
311   gcc_assert (TREE_CODE (binfo) == TREE_BINFO);
312
313   ptr = VEC_last (deferred_access, deferred_access_stack);
314
315   /* If we are not supposed to defer access checks, just check now.  */
316   if (ptr->deferring_access_checks_kind == dk_no_deferred)
317     {
318       enforce_access (binfo, decl, diag_decl);
319       return;
320     }
321
322   /* See if we are already going to perform this check.  */
323   FOR_EACH_VEC_ELT  (deferred_access_check,
324                      ptr->deferred_access_checks, i, chk)
325     {
326       if (chk->decl == decl && chk->binfo == binfo &&
327           chk->diag_decl == diag_decl)
328         {
329           return;
330         }
331     }
332   /* If not, record the check.  */
333   new_access =
334     VEC_safe_push (deferred_access_check, gc,
335                    ptr->deferred_access_checks, 0);
336   new_access->binfo = binfo;
337   new_access->decl = decl;
338   new_access->diag_decl = diag_decl;
339 }
340
341 /* Used by build_over_call in LOOKUP_SPECULATIVE mode: return whether DECL
342    is accessible in BINFO, and possibly complain if not.  If we're not
343    checking access, everything is accessible.  */
344
345 bool
346 speculative_access_check (tree binfo, tree decl, tree diag_decl,
347                           bool complain)
348 {
349   if (deferred_access_no_check)
350     return true;
351
352   /* If we're checking for implicit delete, we don't want access
353      control errors.  */
354   if (!accessible_p (binfo, decl, true))
355     {
356       /* Unless we're under maybe_explain_implicit_delete.  */
357       if (complain)
358         enforce_access (binfo, decl, diag_decl);
359       return false;
360     }
361
362   return true;
363 }
364
365 /* Returns nonzero if the current statement is a full expression,
366    i.e. temporaries created during that statement should be destroyed
367    at the end of the statement.  */
368
369 int
370 stmts_are_full_exprs_p (void)
371 {
372   return current_stmt_tree ()->stmts_are_full_exprs_p;
373 }
374
375 /* T is a statement.  Add it to the statement-tree.  This is the C++
376    version.  The C/ObjC frontends have a slightly different version of
377    this function.  */
378
379 tree
380 add_stmt (tree t)
381 {
382   enum tree_code code = TREE_CODE (t);
383
384   if (EXPR_P (t) && code != LABEL_EXPR)
385     {
386       if (!EXPR_HAS_LOCATION (t))
387         SET_EXPR_LOCATION (t, input_location);
388
389       /* When we expand a statement-tree, we must know whether or not the
390          statements are full-expressions.  We record that fact here.  */
391       STMT_IS_FULL_EXPR_P (t) = stmts_are_full_exprs_p ();
392     }
393
394   /* Add T to the statement-tree.  Non-side-effect statements need to be
395      recorded during statement expressions.  */
396   append_to_statement_list_force (t, &cur_stmt_list);
397
398   return t;
399 }
400
401 /* Returns the stmt_tree to which statements are currently being added.  */
402
403 stmt_tree
404 current_stmt_tree (void)
405 {
406   return (cfun
407           ? &cfun->language->base.x_stmt_tree
408           : &scope_chain->x_stmt_tree);
409 }
410
411 /* If statements are full expressions, wrap STMT in a CLEANUP_POINT_EXPR.  */
412
413 static tree
414 maybe_cleanup_point_expr (tree expr)
415 {
416   if (!processing_template_decl && stmts_are_full_exprs_p ())
417     expr = fold_build_cleanup_point_expr (TREE_TYPE (expr), expr);
418   return expr;
419 }
420
421 /* Like maybe_cleanup_point_expr except have the type of the new expression be
422    void so we don't need to create a temporary variable to hold the inner
423    expression.  The reason why we do this is because the original type might be
424    an aggregate and we cannot create a temporary variable for that type.  */
425
426 static tree
427 maybe_cleanup_point_expr_void (tree expr)
428 {
429   if (!processing_template_decl && stmts_are_full_exprs_p ())
430     expr = fold_build_cleanup_point_expr (void_type_node, expr);
431   return expr;
432 }
433
434
435
436 /* Create a declaration statement for the declaration given by the DECL.  */
437
438 void
439 add_decl_expr (tree decl)
440 {
441   tree r = build_stmt (input_location, DECL_EXPR, decl);
442   if (DECL_INITIAL (decl)
443       || (DECL_SIZE (decl) && TREE_SIDE_EFFECTS (DECL_SIZE (decl))))
444     r = maybe_cleanup_point_expr_void (r);
445   add_stmt (r);
446 }
447
448 /* Finish a scope.  */
449
450 tree
451 do_poplevel (tree stmt_list)
452 {
453   tree block = NULL;
454
455   if (stmts_are_full_exprs_p ())
456     block = poplevel (kept_level_p (), 1, 0);
457
458   stmt_list = pop_stmt_list (stmt_list);
459
460   if (!processing_template_decl)
461     {
462       stmt_list = c_build_bind_expr (input_location, block, stmt_list);
463       /* ??? See c_end_compound_stmt re statement expressions.  */
464     }
465
466   return stmt_list;
467 }
468
469 /* Begin a new scope.  */
470
471 static tree
472 do_pushlevel (scope_kind sk)
473 {
474   tree ret = push_stmt_list ();
475   if (stmts_are_full_exprs_p ())
476     begin_scope (sk, NULL);
477   return ret;
478 }
479
480 /* Queue a cleanup.  CLEANUP is an expression/statement to be executed
481    when the current scope is exited.  EH_ONLY is true when this is not
482    meant to apply to normal control flow transfer.  */
483
484 void
485 push_cleanup (tree decl, tree cleanup, bool eh_only)
486 {
487   tree stmt = build_stmt (input_location, CLEANUP_STMT, NULL, cleanup, decl);
488   CLEANUP_EH_ONLY (stmt) = eh_only;
489   add_stmt (stmt);
490   CLEANUP_BODY (stmt) = push_stmt_list ();
491 }
492
493 /* Begin a conditional that might contain a declaration.  When generating
494    normal code, we want the declaration to appear before the statement
495    containing the conditional.  When generating template code, we want the
496    conditional to be rendered as the raw DECL_EXPR.  */
497
498 static void
499 begin_cond (tree *cond_p)
500 {
501   if (processing_template_decl)
502     *cond_p = push_stmt_list ();
503 }
504
505 /* Finish such a conditional.  */
506
507 static void
508 finish_cond (tree *cond_p, tree expr)
509 {
510   if (processing_template_decl)
511     {
512       tree cond = pop_stmt_list (*cond_p);
513       if (TREE_CODE (cond) == DECL_EXPR)
514         expr = cond;
515
516       if (check_for_bare_parameter_packs (expr))
517         *cond_p = error_mark_node;
518     }
519   *cond_p = expr;
520 }
521
522 /* If *COND_P specifies a conditional with a declaration, transform the
523    loop such that
524             while (A x = 42) { }
525             for (; A x = 42;) { }
526    becomes
527             while (true) { A x = 42; if (!x) break; }
528             for (;;) { A x = 42; if (!x) break; }
529    The statement list for BODY will be empty if the conditional did
530    not declare anything.  */
531
532 static void
533 simplify_loop_decl_cond (tree *cond_p, tree body)
534 {
535   tree cond, if_stmt;
536
537   if (!TREE_SIDE_EFFECTS (body))
538     return;
539
540   cond = *cond_p;
541   *cond_p = boolean_true_node;
542
543   if_stmt = begin_if_stmt ();
544   cond = cp_build_unary_op (TRUTH_NOT_EXPR, cond, 0, tf_warning_or_error);
545   finish_if_stmt_cond (cond, if_stmt);
546   finish_break_stmt ();
547   finish_then_clause (if_stmt);
548   finish_if_stmt (if_stmt);
549 }
550
551 /* Finish a goto-statement.  */
552
553 tree
554 finish_goto_stmt (tree destination)
555 {
556   if (TREE_CODE (destination) == IDENTIFIER_NODE)
557     destination = lookup_label (destination);
558
559   /* We warn about unused labels with -Wunused.  That means we have to
560      mark the used labels as used.  */
561   if (TREE_CODE (destination) == LABEL_DECL)
562     TREE_USED (destination) = 1;
563   else
564     {
565       destination = mark_rvalue_use (destination);
566       if (!processing_template_decl)
567         {
568           destination = cp_convert (ptr_type_node, destination);
569           if (error_operand_p (destination))
570             return NULL_TREE;
571         }
572       /* We don't inline calls to functions with computed gotos.
573          Those functions are typically up to some funny business,
574          and may be depending on the labels being at particular
575          addresses, or some such.  */
576       DECL_UNINLINABLE (current_function_decl) = 1;
577     }
578
579   check_goto (destination);
580
581   return add_stmt (build_stmt (input_location, GOTO_EXPR, destination));
582 }
583
584 /* COND is the condition-expression for an if, while, etc.,
585    statement.  Convert it to a boolean value, if appropriate.
586    In addition, verify sequence points if -Wsequence-point is enabled.  */
587
588 static tree
589 maybe_convert_cond (tree cond)
590 {
591   /* Empty conditions remain empty.  */
592   if (!cond)
593     return NULL_TREE;
594
595   /* Wait until we instantiate templates before doing conversion.  */
596   if (processing_template_decl)
597     return cond;
598
599   if (warn_sequence_point)
600     verify_sequence_points (cond);
601
602   /* Do the conversion.  */
603   cond = convert_from_reference (cond);
604
605   if (TREE_CODE (cond) == MODIFY_EXPR
606       && !TREE_NO_WARNING (cond)
607       && warn_parentheses)
608     {
609       warning (OPT_Wparentheses,
610                "suggest parentheses around assignment used as truth value");
611       TREE_NO_WARNING (cond) = 1;
612     }
613
614   return condition_conversion (cond);
615 }
616
617 /* Finish an expression-statement, whose EXPRESSION is as indicated.  */
618
619 tree
620 finish_expr_stmt (tree expr)
621 {
622   tree r = NULL_TREE;
623
624   if (expr != NULL_TREE)
625     {
626       if (!processing_template_decl)
627         {
628           if (warn_sequence_point)
629             verify_sequence_points (expr);
630           expr = convert_to_void (expr, ICV_STATEMENT, tf_warning_or_error);
631         }
632       else if (!type_dependent_expression_p (expr))
633         convert_to_void (build_non_dependent_expr (expr), ICV_STATEMENT, 
634                          tf_warning_or_error);
635
636       if (check_for_bare_parameter_packs (expr))
637         expr = error_mark_node;
638
639       /* Simplification of inner statement expressions, compound exprs,
640          etc can result in us already having an EXPR_STMT.  */
641       if (TREE_CODE (expr) != CLEANUP_POINT_EXPR)
642         {
643           if (TREE_CODE (expr) != EXPR_STMT)
644             expr = build_stmt (input_location, EXPR_STMT, expr);
645           expr = maybe_cleanup_point_expr_void (expr);
646         }
647
648       r = add_stmt (expr);
649     }
650
651   finish_stmt ();
652
653   return r;
654 }
655
656
657 /* Begin an if-statement.  Returns a newly created IF_STMT if
658    appropriate.  */
659
660 tree
661 begin_if_stmt (void)
662 {
663   tree r, scope;
664   scope = do_pushlevel (sk_block);
665   r = build_stmt (input_location, IF_STMT, NULL_TREE, NULL_TREE, NULL_TREE);
666   TREE_CHAIN (r) = scope;
667   begin_cond (&IF_COND (r));
668   return r;
669 }
670
671 /* Process the COND of an if-statement, which may be given by
672    IF_STMT.  */
673
674 void
675 finish_if_stmt_cond (tree cond, tree if_stmt)
676 {
677   finish_cond (&IF_COND (if_stmt), maybe_convert_cond (cond));
678   add_stmt (if_stmt);
679   THEN_CLAUSE (if_stmt) = push_stmt_list ();
680 }
681
682 /* Finish the then-clause of an if-statement, which may be given by
683    IF_STMT.  */
684
685 tree
686 finish_then_clause (tree if_stmt)
687 {
688   THEN_CLAUSE (if_stmt) = pop_stmt_list (THEN_CLAUSE (if_stmt));
689   return if_stmt;
690 }
691
692 /* Begin the else-clause of an if-statement.  */
693
694 void
695 begin_else_clause (tree if_stmt)
696 {
697   ELSE_CLAUSE (if_stmt) = push_stmt_list ();
698 }
699
700 /* Finish the else-clause of an if-statement, which may be given by
701    IF_STMT.  */
702
703 void
704 finish_else_clause (tree if_stmt)
705 {
706   ELSE_CLAUSE (if_stmt) = pop_stmt_list (ELSE_CLAUSE (if_stmt));
707 }
708
709 /* Finish an if-statement.  */
710
711 void
712 finish_if_stmt (tree if_stmt)
713 {
714   tree scope = TREE_CHAIN (if_stmt);
715   TREE_CHAIN (if_stmt) = NULL;
716   add_stmt (do_poplevel (scope));
717   finish_stmt ();
718 }
719
720 /* Begin a while-statement.  Returns a newly created WHILE_STMT if
721    appropriate.  */
722
723 tree
724 begin_while_stmt (void)
725 {
726   tree r;
727   r = build_stmt (input_location, WHILE_STMT, NULL_TREE, NULL_TREE);
728   add_stmt (r);
729   WHILE_BODY (r) = do_pushlevel (sk_block);
730   begin_cond (&WHILE_COND (r));
731   return r;
732 }
733
734 /* Process the COND of a while-statement, which may be given by
735    WHILE_STMT.  */
736
737 void
738 finish_while_stmt_cond (tree cond, tree while_stmt)
739 {
740   finish_cond (&WHILE_COND (while_stmt), maybe_convert_cond (cond));
741   simplify_loop_decl_cond (&WHILE_COND (while_stmt), WHILE_BODY (while_stmt));
742 }
743
744 /* Finish a while-statement, which may be given by WHILE_STMT.  */
745
746 void
747 finish_while_stmt (tree while_stmt)
748 {
749   WHILE_BODY (while_stmt) = do_poplevel (WHILE_BODY (while_stmt));
750   finish_stmt ();
751 }
752
753 /* Begin a do-statement.  Returns a newly created DO_STMT if
754    appropriate.  */
755
756 tree
757 begin_do_stmt (void)
758 {
759   tree r = build_stmt (input_location, DO_STMT, NULL_TREE, NULL_TREE);
760   add_stmt (r);
761   DO_BODY (r) = push_stmt_list ();
762   return r;
763 }
764
765 /* Finish the body of a do-statement, which may be given by DO_STMT.  */
766
767 void
768 finish_do_body (tree do_stmt)
769 {
770   tree body = DO_BODY (do_stmt) = pop_stmt_list (DO_BODY (do_stmt));
771
772   if (TREE_CODE (body) == STATEMENT_LIST && STATEMENT_LIST_TAIL (body))
773     body = STATEMENT_LIST_TAIL (body)->stmt;
774
775   if (IS_EMPTY_STMT (body))
776     warning (OPT_Wempty_body,
777             "suggest explicit braces around empty body in %<do%> statement");
778 }
779
780 /* Finish a do-statement, which may be given by DO_STMT, and whose
781    COND is as indicated.  */
782
783 void
784 finish_do_stmt (tree cond, tree do_stmt)
785 {
786   cond = maybe_convert_cond (cond);
787   DO_COND (do_stmt) = cond;
788   finish_stmt ();
789 }
790
791 /* Finish a return-statement.  The EXPRESSION returned, if any, is as
792    indicated.  */
793
794 tree
795 finish_return_stmt (tree expr)
796 {
797   tree r;
798   bool no_warning;
799
800   expr = check_return_expr (expr, &no_warning);
801
802   if (flag_openmp && !check_omp_return ())
803     return error_mark_node;
804   if (!processing_template_decl)
805     {
806       if (warn_sequence_point)
807         verify_sequence_points (expr);
808       
809       if (DECL_DESTRUCTOR_P (current_function_decl)
810           || (DECL_CONSTRUCTOR_P (current_function_decl)
811               && targetm.cxx.cdtor_returns_this ()))
812         {
813           /* Similarly, all destructors must run destructors for
814              base-classes before returning.  So, all returns in a
815              destructor get sent to the DTOR_LABEL; finish_function emits
816              code to return a value there.  */
817           return finish_goto_stmt (cdtor_label);
818         }
819     }
820
821   r = build_stmt (input_location, RETURN_EXPR, expr);
822   TREE_NO_WARNING (r) |= no_warning;
823   r = maybe_cleanup_point_expr_void (r);
824   r = add_stmt (r);
825   finish_stmt ();
826
827   return r;
828 }
829
830 /* Begin the scope of a for-statement or a range-for-statement.
831    Both the returned trees are to be used in a call to
832    begin_for_stmt or begin_range_for_stmt.  */
833
834 tree
835 begin_for_scope (tree *init)
836 {
837   tree scope = NULL_TREE;
838   if (flag_new_for_scope > 0)
839     scope = do_pushlevel (sk_for);
840
841   if (processing_template_decl)
842     *init = push_stmt_list ();
843   else
844     *init = NULL_TREE;
845
846   return scope;
847 }
848
849 /* Begin a for-statement.  Returns a new FOR_STMT.
850    SCOPE and INIT should be the return of begin_for_scope,
851    or both NULL_TREE  */
852
853 tree
854 begin_for_stmt (tree scope, tree init)
855 {
856   tree r;
857
858   r = build_stmt (input_location, FOR_STMT, NULL_TREE, NULL_TREE,
859                   NULL_TREE, NULL_TREE);
860
861   if (scope == NULL_TREE)
862     {
863       gcc_assert (!init || !(flag_new_for_scope > 0));
864       if (!init)
865         scope = begin_for_scope (&init);
866     }
867   FOR_INIT_STMT (r) = init;
868   TREE_CHAIN (r) = scope;
869
870   return r;
871 }
872
873 /* Finish the for-init-statement of a for-statement, which may be
874    given by FOR_STMT.  */
875
876 void
877 finish_for_init_stmt (tree for_stmt)
878 {
879   if (processing_template_decl)
880     FOR_INIT_STMT (for_stmt) = pop_stmt_list (FOR_INIT_STMT (for_stmt));
881   add_stmt (for_stmt);
882   FOR_BODY (for_stmt) = do_pushlevel (sk_block);
883   begin_cond (&FOR_COND (for_stmt));
884 }
885
886 /* Finish the COND of a for-statement, which may be given by
887    FOR_STMT.  */
888
889 void
890 finish_for_cond (tree cond, tree for_stmt)
891 {
892   finish_cond (&FOR_COND (for_stmt), maybe_convert_cond (cond));
893   simplify_loop_decl_cond (&FOR_COND (for_stmt), FOR_BODY (for_stmt));
894 }
895
896 /* Finish the increment-EXPRESSION in a for-statement, which may be
897    given by FOR_STMT.  */
898
899 void
900 finish_for_expr (tree expr, tree for_stmt)
901 {
902   if (!expr)
903     return;
904   /* If EXPR is an overloaded function, issue an error; there is no
905      context available to use to perform overload resolution.  */
906   if (type_unknown_p (expr))
907     {
908       cxx_incomplete_type_error (expr, TREE_TYPE (expr));
909       expr = error_mark_node;
910     }
911   if (!processing_template_decl)
912     {
913       if (warn_sequence_point)
914         verify_sequence_points (expr);
915       expr = convert_to_void (expr, ICV_THIRD_IN_FOR,
916                               tf_warning_or_error);
917     }
918   else if (!type_dependent_expression_p (expr))
919     convert_to_void (build_non_dependent_expr (expr), ICV_THIRD_IN_FOR,
920                      tf_warning_or_error);
921   expr = maybe_cleanup_point_expr_void (expr);
922   if (check_for_bare_parameter_packs (expr))
923     expr = error_mark_node;
924   FOR_EXPR (for_stmt) = expr;
925 }
926
927 /* Finish the body of a for-statement, which may be given by
928    FOR_STMT.  The increment-EXPR for the loop must be
929    provided.
930    It can also finish RANGE_FOR_STMT. */
931
932 void
933 finish_for_stmt (tree for_stmt)
934 {
935   if (TREE_CODE (for_stmt) == RANGE_FOR_STMT)
936     RANGE_FOR_BODY (for_stmt) = do_poplevel (RANGE_FOR_BODY (for_stmt));
937   else
938     FOR_BODY (for_stmt) = do_poplevel (FOR_BODY (for_stmt));
939
940   /* Pop the scope for the body of the loop.  */
941   if (flag_new_for_scope > 0)
942     {
943       tree scope = TREE_CHAIN (for_stmt);
944       TREE_CHAIN (for_stmt) = NULL;
945       add_stmt (do_poplevel (scope));
946     }
947
948   finish_stmt ();
949 }
950
951 /* Begin a range-for-statement.  Returns a new RANGE_FOR_STMT.
952    SCOPE and INIT should be the return of begin_for_scope,
953    or both NULL_TREE  .
954    To finish it call finish_for_stmt(). */
955
956 tree
957 begin_range_for_stmt (tree scope, tree init)
958 {
959   tree r;
960
961   r = build_stmt (input_location, RANGE_FOR_STMT,
962                   NULL_TREE, NULL_TREE, NULL_TREE);
963
964   if (scope == NULL_TREE)
965     {
966       gcc_assert (!init || !(flag_new_for_scope > 0));
967       if (!init)
968         scope = begin_for_scope (&init);
969     }
970
971   /* RANGE_FOR_STMTs do not use nor save the init tree, so we
972      pop it now.  */
973   if (init)
974     pop_stmt_list (init);
975   TREE_CHAIN (r) = scope;
976
977   return r;
978 }
979
980 /* Finish the head of a range-based for statement, which may
981    be given by RANGE_FOR_STMT. DECL must be the declaration
982    and EXPR must be the loop expression. */
983
984 void
985 finish_range_for_decl (tree range_for_stmt, tree decl, tree expr)
986 {
987   RANGE_FOR_DECL (range_for_stmt) = decl;
988   RANGE_FOR_EXPR (range_for_stmt) = expr;
989   add_stmt (range_for_stmt);
990   RANGE_FOR_BODY (range_for_stmt) = do_pushlevel (sk_block);
991 }
992
993 /* Finish a break-statement.  */
994
995 tree
996 finish_break_stmt (void)
997 {
998   return add_stmt (build_stmt (input_location, BREAK_STMT));
999 }
1000
1001 /* Finish a continue-statement.  */
1002
1003 tree
1004 finish_continue_stmt (void)
1005 {
1006   return add_stmt (build_stmt (input_location, CONTINUE_STMT));
1007 }
1008
1009 /* Begin a switch-statement.  Returns a new SWITCH_STMT if
1010    appropriate.  */
1011
1012 tree
1013 begin_switch_stmt (void)
1014 {
1015   tree r, scope;
1016
1017   r = build_stmt (input_location, SWITCH_STMT, NULL_TREE, NULL_TREE, NULL_TREE);
1018
1019   scope = do_pushlevel (sk_block);
1020   TREE_CHAIN (r) = scope;
1021   begin_cond (&SWITCH_STMT_COND (r));
1022
1023   return r;
1024 }
1025
1026 /* Finish the cond of a switch-statement.  */
1027
1028 void
1029 finish_switch_cond (tree cond, tree switch_stmt)
1030 {
1031   tree orig_type = NULL;
1032   if (!processing_template_decl)
1033     {
1034       /* Convert the condition to an integer or enumeration type.  */
1035       cond = build_expr_type_conversion (WANT_INT | WANT_ENUM, cond, true);
1036       if (cond == NULL_TREE)
1037         {
1038           error ("switch quantity not an integer");
1039           cond = error_mark_node;
1040         }
1041       orig_type = TREE_TYPE (cond);
1042       if (cond != error_mark_node)
1043         {
1044           /* [stmt.switch]
1045
1046              Integral promotions are performed.  */
1047           cond = perform_integral_promotions (cond);
1048           cond = maybe_cleanup_point_expr (cond);
1049         }
1050     }
1051   if (check_for_bare_parameter_packs (cond))
1052     cond = error_mark_node;
1053   else if (!processing_template_decl && warn_sequence_point)
1054     verify_sequence_points (cond);
1055
1056   finish_cond (&SWITCH_STMT_COND (switch_stmt), cond);
1057   SWITCH_STMT_TYPE (switch_stmt) = orig_type;
1058   add_stmt (switch_stmt);
1059   push_switch (switch_stmt);
1060   SWITCH_STMT_BODY (switch_stmt) = push_stmt_list ();
1061 }
1062
1063 /* Finish the body of a switch-statement, which may be given by
1064    SWITCH_STMT.  The COND to switch on is indicated.  */
1065
1066 void
1067 finish_switch_stmt (tree switch_stmt)
1068 {
1069   tree scope;
1070
1071   SWITCH_STMT_BODY (switch_stmt) =
1072     pop_stmt_list (SWITCH_STMT_BODY (switch_stmt));
1073   pop_switch ();
1074   finish_stmt ();
1075
1076   scope = TREE_CHAIN (switch_stmt);
1077   TREE_CHAIN (switch_stmt) = NULL;
1078   add_stmt (do_poplevel (scope));
1079 }
1080
1081 /* Begin a try-block.  Returns a newly-created TRY_BLOCK if
1082    appropriate.  */
1083
1084 tree
1085 begin_try_block (void)
1086 {
1087   tree r = build_stmt (input_location, TRY_BLOCK, NULL_TREE, NULL_TREE);
1088   add_stmt (r);
1089   TRY_STMTS (r) = push_stmt_list ();
1090   return r;
1091 }
1092
1093 /* Likewise, for a function-try-block.  The block returned in
1094    *COMPOUND_STMT is an artificial outer scope, containing the
1095    function-try-block.  */
1096
1097 tree
1098 begin_function_try_block (tree *compound_stmt)
1099 {
1100   tree r;
1101   /* This outer scope does not exist in the C++ standard, but we need
1102      a place to put __FUNCTION__ and similar variables.  */
1103   *compound_stmt = begin_compound_stmt (0);
1104   r = begin_try_block ();
1105   FN_TRY_BLOCK_P (r) = 1;
1106   return r;
1107 }
1108
1109 /* Finish a try-block, which may be given by TRY_BLOCK.  */
1110
1111 void
1112 finish_try_block (tree try_block)
1113 {
1114   TRY_STMTS (try_block) = pop_stmt_list (TRY_STMTS (try_block));
1115   TRY_HANDLERS (try_block) = push_stmt_list ();
1116 }
1117
1118 /* Finish the body of a cleanup try-block, which may be given by
1119    TRY_BLOCK.  */
1120
1121 void
1122 finish_cleanup_try_block (tree try_block)
1123 {
1124   TRY_STMTS (try_block) = pop_stmt_list (TRY_STMTS (try_block));
1125 }
1126
1127 /* Finish an implicitly generated try-block, with a cleanup is given
1128    by CLEANUP.  */
1129
1130 void
1131 finish_cleanup (tree cleanup, tree try_block)
1132 {
1133   TRY_HANDLERS (try_block) = cleanup;
1134   CLEANUP_P (try_block) = 1;
1135 }
1136
1137 /* Likewise, for a function-try-block.  */
1138
1139 void
1140 finish_function_try_block (tree try_block)
1141 {
1142   finish_try_block (try_block);
1143   /* FIXME : something queer about CTOR_INITIALIZER somehow following
1144      the try block, but moving it inside.  */
1145   in_function_try_handler = 1;
1146 }
1147
1148 /* Finish a handler-sequence for a try-block, which may be given by
1149    TRY_BLOCK.  */
1150
1151 void
1152 finish_handler_sequence (tree try_block)
1153 {
1154   TRY_HANDLERS (try_block) = pop_stmt_list (TRY_HANDLERS (try_block));
1155   check_handlers (TRY_HANDLERS (try_block));
1156 }
1157
1158 /* Finish the handler-seq for a function-try-block, given by
1159    TRY_BLOCK.  COMPOUND_STMT is the outer block created by
1160    begin_function_try_block.  */
1161
1162 void
1163 finish_function_handler_sequence (tree try_block, tree compound_stmt)
1164 {
1165   in_function_try_handler = 0;
1166   finish_handler_sequence (try_block);
1167   finish_compound_stmt (compound_stmt);
1168 }
1169
1170 /* Begin a handler.  Returns a HANDLER if appropriate.  */
1171
1172 tree
1173 begin_handler (void)
1174 {
1175   tree r;
1176
1177   r = build_stmt (input_location, HANDLER, NULL_TREE, NULL_TREE);
1178   add_stmt (r);
1179
1180   /* Create a binding level for the eh_info and the exception object
1181      cleanup.  */
1182   HANDLER_BODY (r) = do_pushlevel (sk_catch);
1183
1184   return r;
1185 }
1186
1187 /* Finish the handler-parameters for a handler, which may be given by
1188    HANDLER.  DECL is the declaration for the catch parameter, or NULL
1189    if this is a `catch (...)' clause.  */
1190
1191 void
1192 finish_handler_parms (tree decl, tree handler)
1193 {
1194   tree type = NULL_TREE;
1195   if (processing_template_decl)
1196     {
1197       if (decl)
1198         {
1199           decl = pushdecl (decl);
1200           decl = push_template_decl (decl);
1201           HANDLER_PARMS (handler) = decl;
1202           type = TREE_TYPE (decl);
1203         }
1204     }
1205   else
1206     type = expand_start_catch_block (decl);
1207   HANDLER_TYPE (handler) = type;
1208   if (!processing_template_decl && type)
1209     mark_used (eh_type_info (type));
1210 }
1211
1212 /* Finish a handler, which may be given by HANDLER.  The BLOCKs are
1213    the return value from the matching call to finish_handler_parms.  */
1214
1215 void
1216 finish_handler (tree handler)
1217 {
1218   if (!processing_template_decl)
1219     expand_end_catch_block ();
1220   HANDLER_BODY (handler) = do_poplevel (HANDLER_BODY (handler));
1221 }
1222
1223 /* Begin a compound statement.  FLAGS contains some bits that control the
1224    behavior and context.  If BCS_NO_SCOPE is set, the compound statement
1225    does not define a scope.  If BCS_FN_BODY is set, this is the outermost
1226    block of a function.  If BCS_TRY_BLOCK is set, this is the block
1227    created on behalf of a TRY statement.  Returns a token to be passed to
1228    finish_compound_stmt.  */
1229
1230 tree
1231 begin_compound_stmt (unsigned int flags)
1232 {
1233   tree r;
1234
1235   if (flags & BCS_NO_SCOPE)
1236     {
1237       r = push_stmt_list ();
1238       STATEMENT_LIST_NO_SCOPE (r) = 1;
1239
1240       /* Normally, we try hard to keep the BLOCK for a statement-expression.
1241          But, if it's a statement-expression with a scopeless block, there's
1242          nothing to keep, and we don't want to accidentally keep a block
1243          *inside* the scopeless block.  */
1244       keep_next_level (false);
1245     }
1246   else
1247     r = do_pushlevel (flags & BCS_TRY_BLOCK ? sk_try : sk_block);
1248
1249   /* When processing a template, we need to remember where the braces were,
1250      so that we can set up identical scopes when instantiating the template
1251      later.  BIND_EXPR is a handy candidate for this.
1252      Note that do_poplevel won't create a BIND_EXPR itself here (and thus
1253      result in nested BIND_EXPRs), since we don't build BLOCK nodes when
1254      processing templates.  */
1255   if (processing_template_decl)
1256     {
1257       r = build3 (BIND_EXPR, NULL, NULL, r, NULL);
1258       BIND_EXPR_TRY_BLOCK (r) = (flags & BCS_TRY_BLOCK) != 0;
1259       BIND_EXPR_BODY_BLOCK (r) = (flags & BCS_FN_BODY) != 0;
1260       TREE_SIDE_EFFECTS (r) = 1;
1261     }
1262
1263   return r;
1264 }
1265
1266 /* Finish a compound-statement, which is given by STMT.  */
1267
1268 void
1269 finish_compound_stmt (tree stmt)
1270 {
1271   if (TREE_CODE (stmt) == BIND_EXPR)
1272     {
1273       tree body = do_poplevel (BIND_EXPR_BODY (stmt));
1274       /* If the STATEMENT_LIST is empty and this BIND_EXPR isn't special,
1275          discard the BIND_EXPR so it can be merged with the containing
1276          STATEMENT_LIST.  */
1277       if (TREE_CODE (body) == STATEMENT_LIST
1278           && STATEMENT_LIST_HEAD (body) == NULL
1279           && !BIND_EXPR_BODY_BLOCK (stmt)
1280           && !BIND_EXPR_TRY_BLOCK (stmt))
1281         stmt = body;
1282       else
1283         BIND_EXPR_BODY (stmt) = body;
1284     }
1285   else if (STATEMENT_LIST_NO_SCOPE (stmt))
1286     stmt = pop_stmt_list (stmt);
1287   else
1288     {
1289       /* Destroy any ObjC "super" receivers that may have been
1290          created.  */
1291       objc_clear_super_receiver ();
1292
1293       stmt = do_poplevel (stmt);
1294     }
1295
1296   /* ??? See c_end_compound_stmt wrt statement expressions.  */
1297   add_stmt (stmt);
1298   finish_stmt ();
1299 }
1300
1301 /* Finish an asm-statement, whose components are a STRING, some
1302    OUTPUT_OPERANDS, some INPUT_OPERANDS, some CLOBBERS and some
1303    LABELS.  Also note whether the asm-statement should be
1304    considered volatile.  */
1305
1306 tree
1307 finish_asm_stmt (int volatile_p, tree string, tree output_operands,
1308                  tree input_operands, tree clobbers, tree labels)
1309 {
1310   tree r;
1311   tree t;
1312   int ninputs = list_length (input_operands);
1313   int noutputs = list_length (output_operands);
1314
1315   if (!processing_template_decl)
1316     {
1317       const char *constraint;
1318       const char **oconstraints;
1319       bool allows_mem, allows_reg, is_inout;
1320       tree operand;
1321       int i;
1322
1323       oconstraints = XALLOCAVEC (const char *, noutputs);
1324
1325       string = resolve_asm_operand_names (string, output_operands,
1326                                           input_operands, labels);
1327
1328       for (i = 0, t = output_operands; t; t = TREE_CHAIN (t), ++i)
1329         {
1330           operand = TREE_VALUE (t);
1331
1332           /* ??? Really, this should not be here.  Users should be using a
1333              proper lvalue, dammit.  But there's a long history of using
1334              casts in the output operands.  In cases like longlong.h, this
1335              becomes a primitive form of typechecking -- if the cast can be
1336              removed, then the output operand had a type of the proper width;
1337              otherwise we'll get an error.  Gross, but ...  */
1338           STRIP_NOPS (operand);
1339
1340           operand = mark_lvalue_use (operand);
1341
1342           if (!lvalue_or_else (operand, lv_asm, tf_warning_or_error))
1343             operand = error_mark_node;
1344
1345           if (operand != error_mark_node
1346               && (TREE_READONLY (operand)
1347                   || CP_TYPE_CONST_P (TREE_TYPE (operand))
1348                   /* Functions are not modifiable, even though they are
1349                      lvalues.  */
1350                   || TREE_CODE (TREE_TYPE (operand)) == FUNCTION_TYPE
1351                   || TREE_CODE (TREE_TYPE (operand)) == METHOD_TYPE
1352                   /* If it's an aggregate and any field is const, then it is
1353                      effectively const.  */
1354                   || (CLASS_TYPE_P (TREE_TYPE (operand))
1355                       && C_TYPE_FIELDS_READONLY (TREE_TYPE (operand)))))
1356             cxx_readonly_error (operand, lv_asm);
1357
1358           constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (t)));
1359           oconstraints[i] = constraint;
1360
1361           if (parse_output_constraint (&constraint, i, ninputs, noutputs,
1362                                        &allows_mem, &allows_reg, &is_inout))
1363             {
1364               /* If the operand is going to end up in memory,
1365                  mark it addressable.  */
1366               if (!allows_reg && !cxx_mark_addressable (operand))
1367                 operand = error_mark_node;
1368             }
1369           else
1370             operand = error_mark_node;
1371
1372           TREE_VALUE (t) = operand;
1373         }
1374
1375       for (i = 0, t = input_operands; t; ++i, t = TREE_CHAIN (t))
1376         {
1377           constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (t)));
1378           operand = decay_conversion (TREE_VALUE (t));
1379
1380           /* If the type of the operand hasn't been determined (e.g.,
1381              because it involves an overloaded function), then issue
1382              an error message.  There's no context available to
1383              resolve the overloading.  */
1384           if (TREE_TYPE (operand) == unknown_type_node)
1385             {
1386               error ("type of asm operand %qE could not be determined",
1387                      TREE_VALUE (t));
1388               operand = error_mark_node;
1389             }
1390
1391           if (parse_input_constraint (&constraint, i, ninputs, noutputs, 0,
1392                                       oconstraints, &allows_mem, &allows_reg))
1393             {
1394               /* If the operand is going to end up in memory,
1395                  mark it addressable.  */
1396               if (!allows_reg && allows_mem)
1397                 {
1398                   /* Strip the nops as we allow this case.  FIXME, this really
1399                      should be rejected or made deprecated.  */
1400                   STRIP_NOPS (operand);
1401                   if (!cxx_mark_addressable (operand))
1402                     operand = error_mark_node;
1403                 }
1404             }
1405           else
1406             operand = error_mark_node;
1407
1408           TREE_VALUE (t) = operand;
1409         }
1410     }
1411
1412   r = build_stmt (input_location, ASM_EXPR, string,
1413                   output_operands, input_operands,
1414                   clobbers, labels);
1415   ASM_VOLATILE_P (r) = volatile_p || noutputs == 0;
1416   r = maybe_cleanup_point_expr_void (r);
1417   return add_stmt (r);
1418 }
1419
1420 /* Finish a label with the indicated NAME.  Returns the new label.  */
1421
1422 tree
1423 finish_label_stmt (tree name)
1424 {
1425   tree decl = define_label (input_location, name);
1426
1427   if (decl == error_mark_node)
1428     return error_mark_node;
1429
1430   add_stmt (build_stmt (input_location, LABEL_EXPR, decl));
1431
1432   return decl;
1433 }
1434
1435 /* Finish a series of declarations for local labels.  G++ allows users
1436    to declare "local" labels, i.e., labels with scope.  This extension
1437    is useful when writing code involving statement-expressions.  */
1438
1439 void
1440 finish_label_decl (tree name)
1441 {
1442   if (!at_function_scope_p ())
1443     {
1444       error ("__label__ declarations are only allowed in function scopes");
1445       return;
1446     }
1447
1448   add_decl_expr (declare_local_label (name));
1449 }
1450
1451 /* When DECL goes out of scope, make sure that CLEANUP is executed.  */
1452
1453 void
1454 finish_decl_cleanup (tree decl, tree cleanup)
1455 {
1456   push_cleanup (decl, cleanup, false);
1457 }
1458
1459 /* If the current scope exits with an exception, run CLEANUP.  */
1460
1461 void
1462 finish_eh_cleanup (tree cleanup)
1463 {
1464   push_cleanup (NULL, cleanup, true);
1465 }
1466
1467 /* The MEM_INITS is a list of mem-initializers, in reverse of the
1468    order they were written by the user.  Each node is as for
1469    emit_mem_initializers.  */
1470
1471 void
1472 finish_mem_initializers (tree mem_inits)
1473 {
1474   /* Reorder the MEM_INITS so that they are in the order they appeared
1475      in the source program.  */
1476   mem_inits = nreverse (mem_inits);
1477
1478   if (processing_template_decl)
1479     {
1480       tree mem;
1481
1482       for (mem = mem_inits; mem; mem = TREE_CHAIN (mem))
1483         {
1484           /* If the TREE_PURPOSE is a TYPE_PACK_EXPANSION, skip the
1485              check for bare parameter packs in the TREE_VALUE, because
1486              any parameter packs in the TREE_VALUE have already been
1487              bound as part of the TREE_PURPOSE.  See
1488              make_pack_expansion for more information.  */
1489           if (TREE_CODE (TREE_PURPOSE (mem)) != TYPE_PACK_EXPANSION
1490               && check_for_bare_parameter_packs (TREE_VALUE (mem)))
1491             TREE_VALUE (mem) = error_mark_node;
1492         }
1493
1494       add_stmt (build_min_nt (CTOR_INITIALIZER, mem_inits));
1495     }
1496   else
1497     emit_mem_initializers (mem_inits);
1498 }
1499
1500 /* Finish a parenthesized expression EXPR.  */
1501
1502 tree
1503 finish_parenthesized_expr (tree expr)
1504 {
1505   if (EXPR_P (expr))
1506     /* This inhibits warnings in c_common_truthvalue_conversion.  */
1507     TREE_NO_WARNING (expr) = 1;
1508
1509   if (TREE_CODE (expr) == OFFSET_REF)
1510     /* [expr.unary.op]/3 The qualified id of a pointer-to-member must not be
1511        enclosed in parentheses.  */
1512     PTRMEM_OK_P (expr) = 0;
1513
1514   if (TREE_CODE (expr) == STRING_CST)
1515     PAREN_STRING_LITERAL_P (expr) = 1;
1516
1517   return expr;
1518 }
1519
1520 /* Finish a reference to a non-static data member (DECL) that is not
1521    preceded by `.' or `->'.  */
1522
1523 tree
1524 finish_non_static_data_member (tree decl, tree object, tree qualifying_scope)
1525 {
1526   gcc_assert (TREE_CODE (decl) == FIELD_DECL);
1527
1528   if (!object)
1529     {
1530       tree scope = qualifying_scope;
1531       if (scope == NULL_TREE)
1532         scope = context_for_name_lookup (decl);
1533       object = maybe_dummy_object (scope, NULL);
1534     }
1535
1536   if (object == error_mark_node)
1537     return error_mark_node;
1538
1539   /* DR 613: Can use non-static data members without an associated
1540      object in sizeof/decltype/alignof.  */
1541   if (is_dummy_object (object) && cp_unevaluated_operand == 0
1542       && (!processing_template_decl || !current_class_ref))
1543     {
1544       if (current_function_decl
1545           && DECL_STATIC_FUNCTION_P (current_function_decl))
1546         error ("invalid use of member %q+D in static member function", decl);
1547       else
1548         error ("invalid use of non-static data member %q+D", decl);
1549       error ("from this location");
1550
1551       return error_mark_node;
1552     }
1553
1554   if (current_class_ptr)
1555     TREE_USED (current_class_ptr) = 1;
1556   if (processing_template_decl && !qualifying_scope)
1557     {
1558       tree type = TREE_TYPE (decl);
1559
1560       if (TREE_CODE (type) == REFERENCE_TYPE)
1561         type = TREE_TYPE (type);
1562       else
1563         {
1564           /* Set the cv qualifiers.  */
1565           int quals = (current_class_ref
1566                        ? cp_type_quals (TREE_TYPE (current_class_ref))
1567                        : TYPE_UNQUALIFIED);
1568
1569           if (DECL_MUTABLE_P (decl))
1570             quals &= ~TYPE_QUAL_CONST;
1571
1572           quals |= cp_type_quals (TREE_TYPE (decl));
1573           type = cp_build_qualified_type (type, quals);
1574         }
1575
1576       return build_min (COMPONENT_REF, type, object, decl, NULL_TREE);
1577     }
1578   /* If PROCESSING_TEMPLATE_DECL is nonzero here, then
1579      QUALIFYING_SCOPE is also non-null.  Wrap this in a SCOPE_REF
1580      for now.  */
1581   else if (processing_template_decl)
1582     return build_qualified_name (TREE_TYPE (decl),
1583                                  qualifying_scope,
1584                                  DECL_NAME (decl),
1585                                  /*template_p=*/false);
1586   else
1587     {
1588       tree access_type = TREE_TYPE (object);
1589
1590       perform_or_defer_access_check (TYPE_BINFO (access_type), decl,
1591                                      decl);
1592
1593       /* If the data member was named `C::M', convert `*this' to `C'
1594          first.  */
1595       if (qualifying_scope)
1596         {
1597           tree binfo = NULL_TREE;
1598           object = build_scoped_ref (object, qualifying_scope,
1599                                      &binfo);
1600         }
1601
1602       return build_class_member_access_expr (object, decl,
1603                                              /*access_path=*/NULL_TREE,
1604                                              /*preserve_reference=*/false,
1605                                              tf_warning_or_error);
1606     }
1607 }
1608
1609 /* If we are currently parsing a template and we encountered a typedef
1610    TYPEDEF_DECL that is being accessed though CONTEXT, this function
1611    adds the typedef to a list tied to the current template.
1612    At tempate instantiatin time, that list is walked and access check
1613    performed for each typedef.
1614    LOCATION is the location of the usage point of TYPEDEF_DECL.  */
1615
1616 void
1617 add_typedef_to_current_template_for_access_check (tree typedef_decl,
1618                                                   tree context,
1619                                                   location_t location)
1620 {
1621     tree template_info = NULL;
1622     tree cs = current_scope ();
1623
1624     if (!is_typedef_decl (typedef_decl)
1625         || !context
1626         || !CLASS_TYPE_P (context)
1627         || !cs)
1628       return;
1629
1630     if (CLASS_TYPE_P (cs) || TREE_CODE (cs) == FUNCTION_DECL)
1631       template_info = get_template_info (cs);
1632
1633     if (template_info
1634         && TI_TEMPLATE (template_info)
1635         && !currently_open_class (context))
1636       append_type_to_template_for_access_check (cs, typedef_decl,
1637                                                 context, location);
1638 }
1639
1640 /* DECL was the declaration to which a qualified-id resolved.  Issue
1641    an error message if it is not accessible.  If OBJECT_TYPE is
1642    non-NULL, we have just seen `x->' or `x.' and OBJECT_TYPE is the
1643    type of `*x', or `x', respectively.  If the DECL was named as
1644    `A::B' then NESTED_NAME_SPECIFIER is `A'.  */
1645
1646 void
1647 check_accessibility_of_qualified_id (tree decl,
1648                                      tree object_type,
1649                                      tree nested_name_specifier)
1650 {
1651   tree scope;
1652   tree qualifying_type = NULL_TREE;
1653
1654   /* If we are parsing a template declaration and if decl is a typedef,
1655      add it to a list tied to the template.
1656      At template instantiation time, that list will be walked and
1657      access check performed.  */
1658   add_typedef_to_current_template_for_access_check (decl,
1659                                                     nested_name_specifier
1660                                                     ? nested_name_specifier
1661                                                     : DECL_CONTEXT (decl),
1662                                                     input_location);
1663
1664   /* If we're not checking, return immediately.  */
1665   if (deferred_access_no_check)
1666     return;
1667
1668   /* Determine the SCOPE of DECL.  */
1669   scope = context_for_name_lookup (decl);
1670   /* If the SCOPE is not a type, then DECL is not a member.  */
1671   if (!TYPE_P (scope))
1672     return;
1673   /* Compute the scope through which DECL is being accessed.  */
1674   if (object_type
1675       /* OBJECT_TYPE might not be a class type; consider:
1676
1677            class A { typedef int I; };
1678            I *p;
1679            p->A::I::~I();
1680
1681          In this case, we will have "A::I" as the DECL, but "I" as the
1682          OBJECT_TYPE.  */
1683       && CLASS_TYPE_P (object_type)
1684       && DERIVED_FROM_P (scope, object_type))
1685     /* If we are processing a `->' or `.' expression, use the type of the
1686        left-hand side.  */
1687     qualifying_type = object_type;
1688   else if (nested_name_specifier)
1689     {
1690       /* If the reference is to a non-static member of the
1691          current class, treat it as if it were referenced through
1692          `this'.  */
1693       if (DECL_NONSTATIC_MEMBER_P (decl)
1694           && current_class_ptr
1695           && DERIVED_FROM_P (scope, current_class_type))
1696         qualifying_type = current_class_type;
1697       /* Otherwise, use the type indicated by the
1698          nested-name-specifier.  */
1699       else
1700         qualifying_type = nested_name_specifier;
1701     }
1702   else
1703     /* Otherwise, the name must be from the current class or one of
1704        its bases.  */
1705     qualifying_type = currently_open_derived_class (scope);
1706
1707   if (qualifying_type 
1708       /* It is possible for qualifying type to be a TEMPLATE_TYPE_PARM
1709          or similar in a default argument value.  */
1710       && CLASS_TYPE_P (qualifying_type)
1711       && !dependent_type_p (qualifying_type))
1712     perform_or_defer_access_check (TYPE_BINFO (qualifying_type), decl,
1713                                    decl);
1714 }
1715
1716 /* EXPR is the result of a qualified-id.  The QUALIFYING_CLASS was the
1717    class named to the left of the "::" operator.  DONE is true if this
1718    expression is a complete postfix-expression; it is false if this
1719    expression is followed by '->', '[', '(', etc.  ADDRESS_P is true
1720    iff this expression is the operand of '&'.  TEMPLATE_P is true iff
1721    the qualified-id was of the form "A::template B".  TEMPLATE_ARG_P
1722    is true iff this qualified name appears as a template argument.  */
1723
1724 tree
1725 finish_qualified_id_expr (tree qualifying_class,
1726                           tree expr,
1727                           bool done,
1728                           bool address_p,
1729                           bool template_p,
1730                           bool template_arg_p)
1731 {
1732   gcc_assert (TYPE_P (qualifying_class));
1733
1734   if (error_operand_p (expr))
1735     return error_mark_node;
1736
1737   if (DECL_P (expr) || BASELINK_P (expr))
1738     mark_used (expr);
1739
1740   if (template_p)
1741     check_template_keyword (expr);
1742
1743   /* If EXPR occurs as the operand of '&', use special handling that
1744      permits a pointer-to-member.  */
1745   if (address_p && done)
1746     {
1747       if (TREE_CODE (expr) == SCOPE_REF)
1748         expr = TREE_OPERAND (expr, 1);
1749       expr = build_offset_ref (qualifying_class, expr,
1750                                /*address_p=*/true);
1751       return expr;
1752     }
1753
1754   /* Within the scope of a class, turn references to non-static
1755      members into expression of the form "this->...".  */
1756   if (template_arg_p)
1757     /* But, within a template argument, we do not want make the
1758        transformation, as there is no "this" pointer.  */
1759     ;
1760   else if (TREE_CODE (expr) == FIELD_DECL)
1761     {
1762       push_deferring_access_checks (dk_no_check);
1763       expr = finish_non_static_data_member (expr, NULL_TREE,
1764                                             qualifying_class);
1765       pop_deferring_access_checks ();
1766     }
1767   else if (BASELINK_P (expr) && !processing_template_decl)
1768     {
1769       tree ob;
1770
1771       /* See if any of the functions are non-static members.  */
1772       /* If so, the expression may be relative to 'this'.  */
1773       if (!shared_member_p (expr)
1774           && (ob = maybe_dummy_object (qualifying_class, NULL),
1775               !is_dummy_object (ob)))
1776         expr = (build_class_member_access_expr
1777                 (ob,
1778                  expr,
1779                  BASELINK_ACCESS_BINFO (expr),
1780                  /*preserve_reference=*/false,
1781                  tf_warning_or_error));
1782       else if (done)
1783         /* The expression is a qualified name whose address is not
1784            being taken.  */
1785         expr = build_offset_ref (qualifying_class, expr, /*address_p=*/false);
1786     }
1787
1788   return expr;
1789 }
1790
1791 /* Begin a statement-expression.  The value returned must be passed to
1792    finish_stmt_expr.  */
1793
1794 tree
1795 begin_stmt_expr (void)
1796 {
1797   return push_stmt_list ();
1798 }
1799
1800 /* Process the final expression of a statement expression. EXPR can be
1801    NULL, if the final expression is empty.  Return a STATEMENT_LIST
1802    containing all the statements in the statement-expression, or
1803    ERROR_MARK_NODE if there was an error.  */
1804
1805 tree
1806 finish_stmt_expr_expr (tree expr, tree stmt_expr)
1807 {
1808   if (error_operand_p (expr))
1809     {
1810       /* The type of the statement-expression is the type of the last
1811          expression.  */
1812       TREE_TYPE (stmt_expr) = error_mark_node;
1813       return error_mark_node;
1814     }
1815
1816   /* If the last statement does not have "void" type, then the value
1817      of the last statement is the value of the entire expression.  */
1818   if (expr)
1819     {
1820       tree type = TREE_TYPE (expr);
1821
1822       if (processing_template_decl)
1823         {
1824           expr = build_stmt (input_location, EXPR_STMT, expr);
1825           expr = add_stmt (expr);
1826           /* Mark the last statement so that we can recognize it as such at
1827              template-instantiation time.  */
1828           EXPR_STMT_STMT_EXPR_RESULT (expr) = 1;
1829         }
1830       else if (VOID_TYPE_P (type))
1831         {
1832           /* Just treat this like an ordinary statement.  */
1833           expr = finish_expr_stmt (expr);
1834         }
1835       else
1836         {
1837           /* It actually has a value we need to deal with.  First, force it
1838              to be an rvalue so that we won't need to build up a copy
1839              constructor call later when we try to assign it to something.  */
1840           expr = force_rvalue (expr);
1841           if (error_operand_p (expr))
1842             return error_mark_node;
1843
1844           /* Update for array-to-pointer decay.  */
1845           type = TREE_TYPE (expr);
1846
1847           /* Wrap it in a CLEANUP_POINT_EXPR and add it to the list like a
1848              normal statement, but don't convert to void or actually add
1849              the EXPR_STMT.  */
1850           if (TREE_CODE (expr) != CLEANUP_POINT_EXPR)
1851             expr = maybe_cleanup_point_expr (expr);
1852           add_stmt (expr);
1853         }
1854
1855       /* The type of the statement-expression is the type of the last
1856          expression.  */
1857       TREE_TYPE (stmt_expr) = type;
1858     }
1859
1860   return stmt_expr;
1861 }
1862
1863 /* Finish a statement-expression.  EXPR should be the value returned
1864    by the previous begin_stmt_expr.  Returns an expression
1865    representing the statement-expression.  */
1866
1867 tree
1868 finish_stmt_expr (tree stmt_expr, bool has_no_scope)
1869 {
1870   tree type;
1871   tree result;
1872
1873   if (error_operand_p (stmt_expr))
1874     {
1875       pop_stmt_list (stmt_expr);
1876       return error_mark_node;
1877     }
1878
1879   gcc_assert (TREE_CODE (stmt_expr) == STATEMENT_LIST);
1880
1881   type = TREE_TYPE (stmt_expr);
1882   result = pop_stmt_list (stmt_expr);
1883   TREE_TYPE (result) = type;
1884
1885   if (processing_template_decl)
1886     {
1887       result = build_min (STMT_EXPR, type, result);
1888       TREE_SIDE_EFFECTS (result) = 1;
1889       STMT_EXPR_NO_SCOPE (result) = has_no_scope;
1890     }
1891   else if (CLASS_TYPE_P (type))
1892     {
1893       /* Wrap the statement-expression in a TARGET_EXPR so that the
1894          temporary object created by the final expression is destroyed at
1895          the end of the full-expression containing the
1896          statement-expression.  */
1897       result = force_target_expr (type, result);
1898     }
1899
1900   return result;
1901 }
1902
1903 /* Returns the expression which provides the value of STMT_EXPR.  */
1904
1905 tree
1906 stmt_expr_value_expr (tree stmt_expr)
1907 {
1908   tree t = STMT_EXPR_STMT (stmt_expr);
1909
1910   if (TREE_CODE (t) == BIND_EXPR)
1911     t = BIND_EXPR_BODY (t);
1912
1913   if (TREE_CODE (t) == STATEMENT_LIST && STATEMENT_LIST_TAIL (t))
1914     t = STATEMENT_LIST_TAIL (t)->stmt;
1915
1916   if (TREE_CODE (t) == EXPR_STMT)
1917     t = EXPR_STMT_EXPR (t);
1918
1919   return t;
1920 }
1921
1922 /* Return TRUE iff EXPR_STMT is an empty list of
1923    expression statements.  */
1924
1925 bool
1926 empty_expr_stmt_p (tree expr_stmt)
1927 {
1928   tree body = NULL_TREE;
1929
1930   if (expr_stmt == void_zero_node)
1931     return true;
1932
1933   if (expr_stmt)
1934     {
1935       if (TREE_CODE (expr_stmt) == EXPR_STMT)
1936         body = EXPR_STMT_EXPR (expr_stmt);
1937       else if (TREE_CODE (expr_stmt) == STATEMENT_LIST)
1938         body = expr_stmt;
1939     }
1940
1941   if (body)
1942     {
1943       if (TREE_CODE (body) == STATEMENT_LIST)
1944         return tsi_end_p (tsi_start (body));
1945       else
1946         return empty_expr_stmt_p (body);
1947     }
1948   return false;
1949 }
1950
1951 /* Perform Koenig lookup.  FN is the postfix-expression representing
1952    the function (or functions) to call; ARGS are the arguments to the
1953    call; if INCLUDE_STD then the `std' namespace is automatically
1954    considered an associated namespace (used in range-based for loops).
1955    Returns the functions to be considered by overload resolution.  */
1956
1957 tree
1958 perform_koenig_lookup (tree fn, VEC(tree,gc) *args, bool include_std)
1959 {
1960   tree identifier = NULL_TREE;
1961   tree functions = NULL_TREE;
1962   tree tmpl_args = NULL_TREE;
1963   bool template_id = false;
1964
1965   if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
1966     {
1967       /* Use a separate flag to handle null args.  */
1968       template_id = true;
1969       tmpl_args = TREE_OPERAND (fn, 1);
1970       fn = TREE_OPERAND (fn, 0);
1971     }
1972
1973   /* Find the name of the overloaded function.  */
1974   if (TREE_CODE (fn) == IDENTIFIER_NODE)
1975     identifier = fn;
1976   else if (is_overloaded_fn (fn))
1977     {
1978       functions = fn;
1979       identifier = DECL_NAME (get_first_fn (functions));
1980     }
1981   else if (DECL_P (fn))
1982     {
1983       functions = fn;
1984       identifier = DECL_NAME (fn);
1985     }
1986
1987   /* A call to a namespace-scope function using an unqualified name.
1988
1989      Do Koenig lookup -- unless any of the arguments are
1990      type-dependent.  */
1991   if (!any_type_dependent_arguments_p (args)
1992       && !any_dependent_template_arguments_p (tmpl_args))
1993     {
1994       fn = lookup_arg_dependent (identifier, functions, args, include_std);
1995       if (!fn)
1996         /* The unqualified name could not be resolved.  */
1997         fn = unqualified_fn_lookup_error (identifier);
1998     }
1999
2000   if (fn && template_id)
2001     fn = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fn, tmpl_args);
2002   
2003   return fn;
2004 }
2005
2006 /* Generate an expression for `FN (ARGS)'.  This may change the
2007    contents of ARGS.
2008
2009    If DISALLOW_VIRTUAL is true, the call to FN will be not generated
2010    as a virtual call, even if FN is virtual.  (This flag is set when
2011    encountering an expression where the function name is explicitly
2012    qualified.  For example a call to `X::f' never generates a virtual
2013    call.)
2014
2015    Returns code for the call.  */
2016
2017 tree
2018 finish_call_expr (tree fn, VEC(tree,gc) **args, bool disallow_virtual,
2019                   bool koenig_p, tsubst_flags_t complain)
2020 {
2021   tree result;
2022   tree orig_fn;
2023   VEC(tree,gc) *orig_args = NULL;
2024
2025   if (fn == error_mark_node)
2026     return error_mark_node;
2027
2028   gcc_assert (!TYPE_P (fn));
2029
2030   orig_fn = fn;
2031
2032   if (processing_template_decl)
2033     {
2034       /* If the call expression is dependent, build a CALL_EXPR node
2035          with no type; type_dependent_expression_p recognizes
2036          expressions with no type as being dependent.  */
2037       if (type_dependent_expression_p (fn)
2038           || any_type_dependent_arguments_p (*args)
2039           /* For a non-static member function, we need to specifically
2040              test the type dependency of the "this" pointer because it
2041              is not included in *ARGS even though it is considered to
2042              be part of the list of arguments.  Note that this is
2043              related to CWG issues 515 and 1005.  */
2044           || ((TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
2045               && current_class_ref
2046               && type_dependent_expression_p (current_class_ref)))
2047         {
2048           result = build_nt_call_vec (fn, *args);
2049           KOENIG_LOOKUP_P (result) = koenig_p;
2050           if (cfun)
2051             {
2052               do
2053                 {
2054                   tree fndecl = OVL_CURRENT (fn);
2055                   if (TREE_CODE (fndecl) != FUNCTION_DECL
2056                       || !TREE_THIS_VOLATILE (fndecl))
2057                     break;
2058                   fn = OVL_NEXT (fn);
2059                 }
2060               while (fn);
2061               if (!fn)
2062                 current_function_returns_abnormally = 1;
2063             }
2064           return result;
2065         }
2066       orig_args = make_tree_vector_copy (*args);
2067       if (!BASELINK_P (fn)
2068           && TREE_CODE (fn) != PSEUDO_DTOR_EXPR
2069           && TREE_TYPE (fn) != unknown_type_node)
2070         fn = build_non_dependent_expr (fn);
2071       make_args_non_dependent (*args);
2072     }
2073
2074   if (is_overloaded_fn (fn))
2075     fn = baselink_for_fns (fn);
2076
2077   result = NULL_TREE;
2078   if (BASELINK_P (fn))
2079     {
2080       tree object;
2081
2082       /* A call to a member function.  From [over.call.func]:
2083
2084            If the keyword this is in scope and refers to the class of
2085            that member function, or a derived class thereof, then the
2086            function call is transformed into a qualified function call
2087            using (*this) as the postfix-expression to the left of the
2088            . operator.... [Otherwise] a contrived object of type T
2089            becomes the implied object argument.
2090
2091         In this situation:
2092
2093           struct A { void f(); };
2094           struct B : public A {};
2095           struct C : public A { void g() { B::f(); }};
2096
2097         "the class of that member function" refers to `A'.  But 11.2
2098         [class.access.base] says that we need to convert 'this' to B* as
2099         part of the access, so we pass 'B' to maybe_dummy_object.  */
2100
2101       object = maybe_dummy_object (BINFO_TYPE (BASELINK_ACCESS_BINFO (fn)),
2102                                    NULL);
2103
2104       if (processing_template_decl)
2105         {
2106           if (type_dependent_expression_p (object))
2107             {
2108               tree ret = build_nt_call_vec (orig_fn, orig_args);
2109               release_tree_vector (orig_args);
2110               return ret;
2111             }
2112           object = build_non_dependent_expr (object);
2113         }
2114
2115       result = build_new_method_call (object, fn, args, NULL_TREE,
2116                                       (disallow_virtual
2117                                        ? LOOKUP_NONVIRTUAL : 0),
2118                                       /*fn_p=*/NULL,
2119                                       complain);
2120     }
2121   else if (is_overloaded_fn (fn))
2122     {
2123       /* If the function is an overloaded builtin, resolve it.  */
2124       if (TREE_CODE (fn) == FUNCTION_DECL
2125           && (DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL
2126               || DECL_BUILT_IN_CLASS (fn) == BUILT_IN_MD))
2127         result = resolve_overloaded_builtin (input_location, fn, *args);
2128
2129       if (!result)
2130         /* A call to a namespace-scope function.  */
2131         result = build_new_function_call (fn, args, koenig_p, complain);
2132     }
2133   else if (TREE_CODE (fn) == PSEUDO_DTOR_EXPR)
2134     {
2135       if (!VEC_empty (tree, *args))
2136         error ("arguments to destructor are not allowed");
2137       /* Mark the pseudo-destructor call as having side-effects so
2138          that we do not issue warnings about its use.  */
2139       result = build1 (NOP_EXPR,
2140                        void_type_node,
2141                        TREE_OPERAND (fn, 0));
2142       TREE_SIDE_EFFECTS (result) = 1;
2143     }
2144   else if (CLASS_TYPE_P (TREE_TYPE (fn)))
2145     /* If the "function" is really an object of class type, it might
2146        have an overloaded `operator ()'.  */
2147     result = build_op_call (fn, args, complain);
2148
2149   if (!result)
2150     /* A call where the function is unknown.  */
2151     result = cp_build_function_call_vec (fn, args, complain);
2152
2153   if (processing_template_decl && result != error_mark_node)
2154     {
2155       if (TREE_CODE (result) == INDIRECT_REF)
2156         result = TREE_OPERAND (result, 0);
2157       result = build_call_vec (TREE_TYPE (result), orig_fn, orig_args);
2158       KOENIG_LOOKUP_P (result) = koenig_p;
2159       release_tree_vector (orig_args);
2160       result = convert_from_reference (result);
2161     }
2162
2163   if (koenig_p)
2164     {
2165       /* Free garbage OVERLOADs from arg-dependent lookup.  */
2166       tree next = NULL_TREE;
2167       for (fn = orig_fn;
2168            fn && TREE_CODE (fn) == OVERLOAD && OVL_ARG_DEPENDENT (fn);
2169            fn = next)
2170         {
2171           if (processing_template_decl)
2172             /* In a template, we'll re-use them at instantiation time.  */
2173             OVL_ARG_DEPENDENT (fn) = false;
2174           else
2175             {
2176               next = OVL_CHAIN (fn);
2177               ggc_free (fn);
2178             }
2179         }
2180     }
2181
2182   return result;
2183 }
2184
2185 /* Finish a call to a postfix increment or decrement or EXPR.  (Which
2186    is indicated by CODE, which should be POSTINCREMENT_EXPR or
2187    POSTDECREMENT_EXPR.)  */
2188
2189 tree
2190 finish_increment_expr (tree expr, enum tree_code code)
2191 {
2192   return build_x_unary_op (code, expr, tf_warning_or_error);
2193 }
2194
2195 /* Finish a use of `this'.  Returns an expression for `this'.  */
2196
2197 tree
2198 finish_this_expr (void)
2199 {
2200   tree result;
2201
2202   if (current_class_ptr)
2203     {
2204       tree type = TREE_TYPE (current_class_ref);
2205
2206       /* In a lambda expression, 'this' refers to the captured 'this'.  */
2207       if (LAMBDA_TYPE_P (type))
2208         result = lambda_expr_this_capture (CLASSTYPE_LAMBDA_EXPR (type));
2209       else
2210         result = current_class_ptr;
2211
2212     }
2213   else if (current_function_decl
2214            && DECL_STATIC_FUNCTION_P (current_function_decl))
2215     {
2216       error ("%<this%> is unavailable for static member functions");
2217       result = error_mark_node;
2218     }
2219   else
2220     {
2221       if (current_function_decl)
2222         error ("invalid use of %<this%> in non-member function");
2223       else
2224         error ("invalid use of %<this%> at top level");
2225       result = error_mark_node;
2226     }
2227
2228   return result;
2229 }
2230
2231 /* Finish a pseudo-destructor expression.  If SCOPE is NULL, the
2232    expression was of the form `OBJECT.~DESTRUCTOR' where DESTRUCTOR is
2233    the TYPE for the type given.  If SCOPE is non-NULL, the expression
2234    was of the form `OBJECT.SCOPE::~DESTRUCTOR'.  */
2235
2236 tree
2237 finish_pseudo_destructor_expr (tree object, tree scope, tree destructor)
2238 {
2239   if (object == error_mark_node || destructor == error_mark_node)
2240     return error_mark_node;
2241
2242   gcc_assert (TYPE_P (destructor));
2243
2244   if (!processing_template_decl)
2245     {
2246       if (scope == error_mark_node)
2247         {
2248           error ("invalid qualifying scope in pseudo-destructor name");
2249           return error_mark_node;
2250         }
2251       if (scope && TYPE_P (scope) && !check_dtor_name (scope, destructor))
2252         {
2253           error ("qualified type %qT does not match destructor name ~%qT",
2254                  scope, destructor);
2255           return error_mark_node;
2256         }
2257
2258
2259       /* [expr.pseudo] says both:
2260
2261            The type designated by the pseudo-destructor-name shall be
2262            the same as the object type.
2263
2264          and:
2265
2266            The cv-unqualified versions of the object type and of the
2267            type designated by the pseudo-destructor-name shall be the
2268            same type.
2269
2270          We implement the more generous second sentence, since that is
2271          what most other compilers do.  */
2272       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (object),
2273                                                       destructor))
2274         {
2275           error ("%qE is not of type %qT", object, destructor);
2276           return error_mark_node;
2277         }
2278     }
2279
2280   return build3 (PSEUDO_DTOR_EXPR, void_type_node, object, scope, destructor);
2281 }
2282
2283 /* Finish an expression of the form CODE EXPR.  */
2284
2285 tree
2286 finish_unary_op_expr (enum tree_code code, tree expr)
2287 {
2288   tree result = build_x_unary_op (code, expr, tf_warning_or_error);
2289   /* Inside a template, build_x_unary_op does not fold the
2290      expression. So check whether the result is folded before
2291      setting TREE_NEGATED_INT.  */
2292   if (code == NEGATE_EXPR && TREE_CODE (expr) == INTEGER_CST
2293       && TREE_CODE (result) == INTEGER_CST
2294       && !TYPE_UNSIGNED (TREE_TYPE (result))
2295       && INT_CST_LT (result, integer_zero_node))
2296     {
2297       /* RESULT may be a cached INTEGER_CST, so we must copy it before
2298          setting TREE_NEGATED_INT.  */
2299       result = copy_node (result);
2300       TREE_NEGATED_INT (result) = 1;
2301     }
2302   if (TREE_OVERFLOW_P (result) && !TREE_OVERFLOW_P (expr))
2303     overflow_warning (input_location, result);
2304
2305   return result;
2306 }
2307
2308 /* Finish a compound-literal expression.  TYPE is the type to which
2309    the CONSTRUCTOR in COMPOUND_LITERAL is being cast.  */
2310
2311 tree
2312 finish_compound_literal (tree type, tree compound_literal,
2313                          tsubst_flags_t complain)
2314 {
2315   if (type == error_mark_node)
2316     return error_mark_node;
2317
2318   if (!TYPE_OBJ_P (type))
2319     {
2320       if (complain & tf_error)
2321         error ("compound literal of non-object type %qT", type);
2322       return error_mark_node;
2323     }
2324
2325   if (processing_template_decl)
2326     {
2327       TREE_TYPE (compound_literal) = type;
2328       /* Mark the expression as a compound literal.  */
2329       TREE_HAS_CONSTRUCTOR (compound_literal) = 1;
2330       return compound_literal;
2331     }
2332
2333   type = complete_type (type);
2334
2335   if (TYPE_NON_AGGREGATE_CLASS (type))
2336     {
2337       /* Trying to deal with a CONSTRUCTOR instead of a TREE_LIST
2338          everywhere that deals with function arguments would be a pain, so
2339          just wrap it in a TREE_LIST.  The parser set a flag so we know
2340          that it came from T{} rather than T({}).  */
2341       CONSTRUCTOR_IS_DIRECT_INIT (compound_literal) = 1;
2342       compound_literal = build_tree_list (NULL_TREE, compound_literal);
2343       return build_functional_cast (type, compound_literal, complain);
2344     }
2345
2346   if (TREE_CODE (type) == ARRAY_TYPE
2347       && check_array_initializer (NULL_TREE, type, compound_literal))
2348     return error_mark_node;
2349   compound_literal = reshape_init (type, compound_literal);
2350   if (TREE_CODE (type) == ARRAY_TYPE)
2351     cp_complete_array_type (&type, compound_literal, false);
2352   compound_literal = digest_init (type, compound_literal);
2353   /* Put static/constant array temporaries in static variables, but always
2354      represent class temporaries with TARGET_EXPR so we elide copies.  */
2355   if ((!at_function_scope_p () || CP_TYPE_CONST_P (type))
2356       && TREE_CODE (type) == ARRAY_TYPE
2357       && initializer_constant_valid_p (compound_literal, type))
2358     {
2359       tree decl = create_temporary_var (type);
2360       DECL_INITIAL (decl) = compound_literal;
2361       TREE_STATIC (decl) = 1;
2362       if (literal_type_p (type) && CP_TYPE_CONST_NON_VOLATILE_P (type))
2363         {
2364           /* 5.19 says that a constant expression can include an
2365              lvalue-rvalue conversion applied to "a glvalue of literal type
2366              that refers to a non-volatile temporary object initialized
2367              with a constant expression".  Rather than try to communicate
2368              that this VAR_DECL is a temporary, just mark it constexpr.  */
2369           DECL_DECLARED_CONSTEXPR_P (decl) = true;
2370           DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
2371           TREE_CONSTANT (decl) = true;
2372         }
2373       cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
2374       decl = pushdecl_top_level (decl);
2375       DECL_NAME (decl) = make_anon_name ();
2376       SET_DECL_ASSEMBLER_NAME (decl, DECL_NAME (decl));
2377       return decl;
2378     }
2379   else
2380     return get_target_expr (compound_literal);
2381 }
2382
2383 /* Return the declaration for the function-name variable indicated by
2384    ID.  */
2385
2386 tree
2387 finish_fname (tree id)
2388 {
2389   tree decl;
2390
2391   decl = fname_decl (input_location, C_RID_CODE (id), id);
2392   if (processing_template_decl && current_function_decl)
2393     decl = DECL_NAME (decl);
2394   return decl;
2395 }
2396
2397 /* Finish a translation unit.  */
2398
2399 void
2400 finish_translation_unit (void)
2401 {
2402   /* In case there were missing closebraces,
2403      get us back to the global binding level.  */
2404   pop_everything ();
2405   while (current_namespace != global_namespace)
2406     pop_namespace ();
2407
2408   /* Do file scope __FUNCTION__ et al.  */
2409   finish_fname_decls ();
2410 }
2411
2412 /* Finish a template type parameter, specified as AGGR IDENTIFIER.
2413    Returns the parameter.  */
2414
2415 tree
2416 finish_template_type_parm (tree aggr, tree identifier)
2417 {
2418   if (aggr != class_type_node)
2419     {
2420       permerror (input_location, "template type parameters must use the keyword %<class%> or %<typename%>");
2421       aggr = class_type_node;
2422     }
2423
2424   return build_tree_list (aggr, identifier);
2425 }
2426
2427 /* Finish a template template parameter, specified as AGGR IDENTIFIER.
2428    Returns the parameter.  */
2429
2430 tree
2431 finish_template_template_parm (tree aggr, tree identifier)
2432 {
2433   tree decl = build_decl (input_location,
2434                           TYPE_DECL, identifier, NULL_TREE);
2435   tree tmpl = build_lang_decl (TEMPLATE_DECL, identifier, NULL_TREE);
2436   DECL_TEMPLATE_PARMS (tmpl) = current_template_parms;
2437   DECL_TEMPLATE_RESULT (tmpl) = decl;
2438   DECL_ARTIFICIAL (decl) = 1;
2439   end_template_decl ();
2440
2441   gcc_assert (DECL_TEMPLATE_PARMS (tmpl));
2442
2443   check_default_tmpl_args (decl, DECL_TEMPLATE_PARMS (tmpl), 
2444                            /*is_primary=*/true, /*is_partial=*/false,
2445                            /*is_friend=*/0);
2446
2447   return finish_template_type_parm (aggr, tmpl);
2448 }
2449
2450 /* ARGUMENT is the default-argument value for a template template
2451    parameter.  If ARGUMENT is invalid, issue error messages and return
2452    the ERROR_MARK_NODE.  Otherwise, ARGUMENT itself is returned.  */
2453
2454 tree
2455 check_template_template_default_arg (tree argument)
2456 {
2457   if (TREE_CODE (argument) != TEMPLATE_DECL
2458       && TREE_CODE (argument) != TEMPLATE_TEMPLATE_PARM
2459       && TREE_CODE (argument) != UNBOUND_CLASS_TEMPLATE)
2460     {
2461       if (TREE_CODE (argument) == TYPE_DECL)
2462         error ("invalid use of type %qT as a default value for a template "
2463                "template-parameter", TREE_TYPE (argument));
2464       else
2465         error ("invalid default argument for a template template parameter");
2466       return error_mark_node;
2467     }
2468
2469   return argument;
2470 }
2471
2472 /* Begin a class definition, as indicated by T.  */
2473
2474 tree
2475 begin_class_definition (tree t, tree attributes)
2476 {
2477   if (error_operand_p (t) || error_operand_p (TYPE_MAIN_DECL (t)))
2478     return error_mark_node;
2479
2480   if (processing_template_parmlist)
2481     {
2482       error ("definition of %q#T inside template parameter list", t);
2483       return error_mark_node;
2484     }
2485
2486   /* According to the C++ ABI, decimal classes defined in ISO/IEC TR 24733
2487      are passed the same as decimal scalar types.  */
2488   if (TREE_CODE (t) == RECORD_TYPE
2489       && !processing_template_decl)
2490     {
2491       tree ns = TYPE_CONTEXT (t);
2492       if (ns && TREE_CODE (ns) == NAMESPACE_DECL
2493           && DECL_CONTEXT (ns) == std_node
2494           && DECL_NAME (ns)
2495           && !strcmp (IDENTIFIER_POINTER (DECL_NAME (ns)), "decimal"))
2496         {
2497           const char *n = TYPE_NAME_STRING (t);
2498           if ((strcmp (n, "decimal32") == 0)
2499               || (strcmp (n, "decimal64") == 0)
2500               || (strcmp (n, "decimal128") == 0))
2501             TYPE_TRANSPARENT_AGGR (t) = 1;
2502         }
2503     }
2504
2505   /* A non-implicit typename comes from code like:
2506
2507        template <typename T> struct A {
2508          template <typename U> struct A<T>::B ...
2509
2510      This is erroneous.  */
2511   else if (TREE_CODE (t) == TYPENAME_TYPE)
2512     {
2513       error ("invalid definition of qualified type %qT", t);
2514       t = error_mark_node;
2515     }
2516
2517   if (t == error_mark_node || ! MAYBE_CLASS_TYPE_P (t))
2518     {
2519       t = make_class_type (RECORD_TYPE);
2520       pushtag (make_anon_name (), t, /*tag_scope=*/ts_current);
2521     }
2522
2523   if (TYPE_BEING_DEFINED (t))
2524     {
2525       t = make_class_type (TREE_CODE (t));
2526       pushtag (TYPE_IDENTIFIER (t), t, /*tag_scope=*/ts_current);
2527     }
2528   maybe_process_partial_specialization (t);
2529   pushclass (t);
2530   TYPE_BEING_DEFINED (t) = 1;
2531
2532   cplus_decl_attributes (&t, attributes, (int) ATTR_FLAG_TYPE_IN_PLACE);
2533   fixup_attribute_variants (t);
2534
2535   if (flag_pack_struct)
2536     {
2537       tree v;
2538       TYPE_PACKED (t) = 1;
2539       /* Even though the type is being defined for the first time
2540          here, there might have been a forward declaration, so there
2541          might be cv-qualified variants of T.  */
2542       for (v = TYPE_NEXT_VARIANT (t); v; v = TYPE_NEXT_VARIANT (v))
2543         TYPE_PACKED (v) = 1;
2544     }
2545   /* Reset the interface data, at the earliest possible
2546      moment, as it might have been set via a class foo;
2547      before.  */
2548   if (! TYPE_ANONYMOUS_P (t))
2549     {
2550       struct c_fileinfo *finfo = get_fileinfo (input_filename);
2551       CLASSTYPE_INTERFACE_ONLY (t) = finfo->interface_only;
2552       SET_CLASSTYPE_INTERFACE_UNKNOWN_X
2553         (t, finfo->interface_unknown);
2554     }
2555   reset_specialization();
2556
2557   /* Make a declaration for this class in its own scope.  */
2558   build_self_reference ();
2559
2560   return t;
2561 }
2562
2563 /* Finish the member declaration given by DECL.  */
2564
2565 void
2566 finish_member_declaration (tree decl)
2567 {
2568   if (decl == error_mark_node || decl == NULL_TREE)
2569     return;
2570
2571   if (decl == void_type_node)
2572     /* The COMPONENT was a friend, not a member, and so there's
2573        nothing for us to do.  */
2574     return;
2575
2576   /* We should see only one DECL at a time.  */
2577   gcc_assert (DECL_CHAIN (decl) == NULL_TREE);
2578
2579   /* Set up access control for DECL.  */
2580   TREE_PRIVATE (decl)
2581     = (current_access_specifier == access_private_node);
2582   TREE_PROTECTED (decl)
2583     = (current_access_specifier == access_protected_node);
2584   if (TREE_CODE (decl) == TEMPLATE_DECL)
2585     {
2586       TREE_PRIVATE (DECL_TEMPLATE_RESULT (decl)) = TREE_PRIVATE (decl);
2587       TREE_PROTECTED (DECL_TEMPLATE_RESULT (decl)) = TREE_PROTECTED (decl);
2588     }
2589
2590   /* Mark the DECL as a member of the current class.  */
2591   DECL_CONTEXT (decl) = current_class_type;
2592
2593   /* Check for bare parameter packs in the member variable declaration.  */
2594   if (TREE_CODE (decl) == FIELD_DECL)
2595     {
2596       if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
2597         TREE_TYPE (decl) = error_mark_node;
2598       if (check_for_bare_parameter_packs (DECL_ATTRIBUTES (decl)))
2599         DECL_ATTRIBUTES (decl) = NULL_TREE;
2600     }
2601
2602   /* [dcl.link]
2603
2604      A C language linkage is ignored for the names of class members
2605      and the member function type of class member functions.  */
2606   if (DECL_LANG_SPECIFIC (decl) && DECL_LANGUAGE (decl) == lang_c)
2607     SET_DECL_LANGUAGE (decl, lang_cplusplus);
2608
2609   /* Put functions on the TYPE_METHODS list and everything else on the
2610      TYPE_FIELDS list.  Note that these are built up in reverse order.
2611      We reverse them (to obtain declaration order) in finish_struct.  */
2612   if (TREE_CODE (decl) == FUNCTION_DECL
2613       || DECL_FUNCTION_TEMPLATE_P (decl))
2614     {
2615       /* We also need to add this function to the
2616          CLASSTYPE_METHOD_VEC.  */
2617       if (add_method (current_class_type, decl, NULL_TREE))
2618         {
2619           DECL_CHAIN (decl) = TYPE_METHODS (current_class_type);
2620           TYPE_METHODS (current_class_type) = decl;
2621
2622           maybe_add_class_template_decl_list (current_class_type, decl,
2623                                               /*friend_p=*/0);
2624         }
2625     }
2626   /* Enter the DECL into the scope of the class.  */
2627   else if ((TREE_CODE (decl) == USING_DECL && !DECL_DEPENDENT_P (decl))
2628            || pushdecl_class_level (decl))
2629     {
2630       /* All TYPE_DECLs go at the end of TYPE_FIELDS.  Ordinary fields
2631          go at the beginning.  The reason is that lookup_field_1
2632          searches the list in order, and we want a field name to
2633          override a type name so that the "struct stat hack" will
2634          work.  In particular:
2635
2636            struct S { enum E { }; int E } s;
2637            s.E = 3;
2638
2639          is valid.  In addition, the FIELD_DECLs must be maintained in
2640          declaration order so that class layout works as expected.
2641          However, we don't need that order until class layout, so we
2642          save a little time by putting FIELD_DECLs on in reverse order
2643          here, and then reversing them in finish_struct_1.  (We could
2644          also keep a pointer to the correct insertion points in the
2645          list.)  */
2646
2647       if (TREE_CODE (decl) == TYPE_DECL)
2648         TYPE_FIELDS (current_class_type)
2649           = chainon (TYPE_FIELDS (current_class_type), decl);
2650       else
2651         {
2652           DECL_CHAIN (decl) = TYPE_FIELDS (current_class_type);
2653           TYPE_FIELDS (current_class_type) = decl;
2654         }
2655
2656       maybe_add_class_template_decl_list (current_class_type, decl,
2657                                           /*friend_p=*/0);
2658     }
2659
2660   if (pch_file)
2661     note_decl_for_pch (decl);
2662 }
2663
2664 /* DECL has been declared while we are building a PCH file.  Perform
2665    actions that we might normally undertake lazily, but which can be
2666    performed now so that they do not have to be performed in
2667    translation units which include the PCH file.  */
2668
2669 void
2670 note_decl_for_pch (tree decl)
2671 {
2672   gcc_assert (pch_file);
2673
2674   /* There's a good chance that we'll have to mangle names at some
2675      point, even if only for emission in debugging information.  */
2676   if ((TREE_CODE (decl) == VAR_DECL
2677        || TREE_CODE (decl) == FUNCTION_DECL)
2678       && !processing_template_decl)
2679     mangle_decl (decl);
2680 }
2681
2682 /* Finish processing a complete template declaration.  The PARMS are
2683    the template parameters.  */
2684
2685 void
2686 finish_template_decl (tree parms)
2687 {
2688   if (parms)
2689     end_template_decl ();
2690   else
2691     end_specialization ();
2692 }
2693
2694 /* Finish processing a template-id (which names a type) of the form
2695    NAME < ARGS >.  Return the TYPE_DECL for the type named by the
2696    template-id.  If ENTERING_SCOPE is nonzero we are about to enter
2697    the scope of template-id indicated.  */
2698
2699 tree
2700 finish_template_type (tree name, tree args, int entering_scope)
2701 {
2702   tree decl;
2703
2704   decl = lookup_template_class (name, args,
2705                                 NULL_TREE, NULL_TREE, entering_scope,
2706                                 tf_warning_or_error | tf_user);
2707   if (decl != error_mark_node)
2708     decl = TYPE_STUB_DECL (decl);
2709
2710   return decl;
2711 }
2712
2713 /* Finish processing a BASE_CLASS with the indicated ACCESS_SPECIFIER.
2714    Return a TREE_LIST containing the ACCESS_SPECIFIER and the
2715    BASE_CLASS, or NULL_TREE if an error occurred.  The
2716    ACCESS_SPECIFIER is one of
2717    access_{default,public,protected_private}_node.  For a virtual base
2718    we set TREE_TYPE.  */
2719
2720 tree
2721 finish_base_specifier (tree base, tree access, bool virtual_p)
2722 {
2723   tree result;
2724
2725   if (base == error_mark_node)
2726     {
2727       error ("invalid base-class specification");
2728       result = NULL_TREE;
2729     }
2730   else if (! MAYBE_CLASS_TYPE_P (base))
2731     {
2732       error ("%qT is not a class type", base);
2733       result = NULL_TREE;
2734     }
2735   else
2736     {
2737       if (cp_type_quals (base) != 0)
2738         {
2739           error ("base class %qT has cv qualifiers", base);
2740           base = TYPE_MAIN_VARIANT (base);
2741         }
2742       result = build_tree_list (access, base);
2743       if (virtual_p)
2744         TREE_TYPE (result) = integer_type_node;
2745     }
2746
2747   return result;
2748 }
2749
2750 /* If FNS is a member function, a set of member functions, or a
2751    template-id referring to one or more member functions, return a
2752    BASELINK for FNS, incorporating the current access context.
2753    Otherwise, return FNS unchanged.  */
2754
2755 tree
2756 baselink_for_fns (tree fns)
2757 {
2758   tree fn;
2759   tree cl;
2760
2761   if (BASELINK_P (fns) 
2762       || error_operand_p (fns))
2763     return fns;
2764   
2765   fn = fns;
2766   if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
2767     fn = TREE_OPERAND (fn, 0);
2768   fn = get_first_fn (fn);
2769   if (!DECL_FUNCTION_MEMBER_P (fn))
2770     return fns;
2771
2772   cl = currently_open_derived_class (DECL_CONTEXT (fn));
2773   if (!cl)
2774     cl = DECL_CONTEXT (fn);
2775   cl = TYPE_BINFO (cl);
2776   return build_baselink (cl, cl, fns, /*optype=*/NULL_TREE);
2777 }
2778
2779 /* Returns true iff DECL is an automatic variable from a function outside
2780    the current one.  */
2781
2782 static bool
2783 outer_automatic_var_p (tree decl)
2784 {
2785   return ((TREE_CODE (decl) == VAR_DECL || TREE_CODE (decl) == PARM_DECL)
2786           && DECL_FUNCTION_SCOPE_P (decl)
2787           && !TREE_STATIC (decl)
2788           && DECL_CONTEXT (decl) != current_function_decl);
2789 }
2790
2791 /* Returns true iff DECL is a capture field from a lambda that is not our
2792    immediate context.  */
2793
2794 static bool
2795 outer_lambda_capture_p (tree decl)
2796 {
2797   return (TREE_CODE (decl) == FIELD_DECL
2798           && LAMBDA_TYPE_P (DECL_CONTEXT (decl))
2799           && (!current_class_type
2800               || !DERIVED_FROM_P (DECL_CONTEXT (decl), current_class_type)));
2801 }
2802
2803 /* ID_EXPRESSION is a representation of parsed, but unprocessed,
2804    id-expression.  (See cp_parser_id_expression for details.)  SCOPE,
2805    if non-NULL, is the type or namespace used to explicitly qualify
2806    ID_EXPRESSION.  DECL is the entity to which that name has been
2807    resolved.
2808
2809    *CONSTANT_EXPRESSION_P is true if we are presently parsing a
2810    constant-expression.  In that case, *NON_CONSTANT_EXPRESSION_P will
2811    be set to true if this expression isn't permitted in a
2812    constant-expression, but it is otherwise not set by this function.
2813    *ALLOW_NON_CONSTANT_EXPRESSION_P is true if we are parsing a
2814    constant-expression, but a non-constant expression is also
2815    permissible.
2816
2817    DONE is true if this expression is a complete postfix-expression;
2818    it is false if this expression is followed by '->', '[', '(', etc.
2819    ADDRESS_P is true iff this expression is the operand of '&'.
2820    TEMPLATE_P is true iff the qualified-id was of the form
2821    "A::template B".  TEMPLATE_ARG_P is true iff this qualified name
2822    appears as a template argument.
2823
2824    If an error occurs, and it is the kind of error that might cause
2825    the parser to abort a tentative parse, *ERROR_MSG is filled in.  It
2826    is the caller's responsibility to issue the message.  *ERROR_MSG
2827    will be a string with static storage duration, so the caller need
2828    not "free" it.
2829
2830    Return an expression for the entity, after issuing appropriate
2831    diagnostics.  This function is also responsible for transforming a
2832    reference to a non-static member into a COMPONENT_REF that makes
2833    the use of "this" explicit.
2834
2835    Upon return, *IDK will be filled in appropriately.  */
2836 tree
2837 finish_id_expression (tree id_expression,
2838                       tree decl,
2839                       tree scope,
2840                       cp_id_kind *idk,
2841                       bool integral_constant_expression_p,
2842                       bool allow_non_integral_constant_expression_p,
2843                       bool *non_integral_constant_expression_p,
2844                       bool template_p,
2845                       bool done,
2846                       bool address_p,
2847                       bool template_arg_p,
2848                       const char **error_msg,
2849                       location_t location)
2850 {
2851   /* Initialize the output parameters.  */
2852   *idk = CP_ID_KIND_NONE;
2853   *error_msg = NULL;
2854
2855   if (id_expression == error_mark_node)
2856     return error_mark_node;
2857   /* If we have a template-id, then no further lookup is
2858      required.  If the template-id was for a template-class, we
2859      will sometimes have a TYPE_DECL at this point.  */
2860   else if (TREE_CODE (decl) == TEMPLATE_ID_EXPR
2861            || TREE_CODE (decl) == TYPE_DECL)
2862     ;
2863   /* Look up the name.  */
2864   else
2865     {
2866       if (decl == error_mark_node)
2867         {
2868           /* Name lookup failed.  */
2869           if (scope
2870               && (!TYPE_P (scope)
2871                   || (!dependent_type_p (scope)
2872                       && !(TREE_CODE (id_expression) == IDENTIFIER_NODE
2873                            && IDENTIFIER_TYPENAME_P (id_expression)
2874                            && dependent_type_p (TREE_TYPE (id_expression))))))
2875             {
2876               /* If the qualifying type is non-dependent (and the name
2877                  does not name a conversion operator to a dependent
2878                  type), issue an error.  */
2879               qualified_name_lookup_error (scope, id_expression, decl, location);
2880               return error_mark_node;
2881             }
2882           else if (!scope)
2883             {
2884               /* It may be resolved via Koenig lookup.  */
2885               *idk = CP_ID_KIND_UNQUALIFIED;
2886               return id_expression;
2887             }
2888           else
2889             decl = id_expression;
2890         }
2891       /* If DECL is a variable that would be out of scope under
2892          ANSI/ISO rules, but in scope in the ARM, name lookup
2893          will succeed.  Issue a diagnostic here.  */
2894       else
2895         decl = check_for_out_of_scope_variable (decl);
2896
2897       /* Remember that the name was used in the definition of
2898          the current class so that we can check later to see if
2899          the meaning would have been different after the class
2900          was entirely defined.  */
2901       if (!scope && decl != error_mark_node
2902           && TREE_CODE (id_expression) == IDENTIFIER_NODE)
2903         maybe_note_name_used_in_class (id_expression, decl);
2904
2905       /* Disallow uses of local variables from containing functions, except
2906          within lambda-expressions.  */
2907       if ((outer_automatic_var_p (decl)
2908            || outer_lambda_capture_p (decl))
2909           /* It's not a use (3.2) if we're in an unevaluated context.  */
2910           && !cp_unevaluated_operand)
2911         {
2912           tree context = DECL_CONTEXT (decl);
2913           tree containing_function = current_function_decl;
2914           tree lambda_stack = NULL_TREE;
2915           tree lambda_expr = NULL_TREE;
2916           tree initializer = decl;
2917
2918           /* Core issue 696: "[At the July 2009 meeting] the CWG expressed
2919              support for an approach in which a reference to a local
2920              [constant] automatic variable in a nested class or lambda body
2921              would enter the expression as an rvalue, which would reduce
2922              the complexity of the problem"
2923
2924              FIXME update for final resolution of core issue 696.  */
2925           if (decl_constant_var_p (decl))
2926             return integral_constant_value (decl);
2927
2928           if (TYPE_P (context))
2929             {
2930               /* Implicit capture of an explicit capture.  */
2931               context = lambda_function (context);
2932               initializer = thisify_lambda_field (decl);
2933             }
2934
2935           /* If we are in a lambda function, we can move out until we hit
2936              1. the context,
2937              2. a non-lambda function, or
2938              3. a non-default capturing lambda function.  */
2939           while (context != containing_function
2940                  && LAMBDA_FUNCTION_P (containing_function))
2941             {
2942               lambda_expr = CLASSTYPE_LAMBDA_EXPR
2943                 (DECL_CONTEXT (containing_function));
2944
2945               if (LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (lambda_expr)
2946                   == CPLD_NONE)
2947                 break;
2948
2949               lambda_stack = tree_cons (NULL_TREE,
2950                                         lambda_expr,
2951                                         lambda_stack);
2952
2953               containing_function
2954                 = decl_function_context (containing_function);
2955             }
2956
2957           if (context == containing_function)
2958             {
2959               decl = add_default_capture (lambda_stack,
2960                                           /*id=*/DECL_NAME (decl),
2961                                           initializer);
2962             }
2963           else if (lambda_expr)
2964             {
2965               error ("%qD is not captured", decl);
2966               return error_mark_node;
2967             }
2968           else
2969             {
2970               error (TREE_CODE (decl) == VAR_DECL
2971                      ? "use of %<auto%> variable from containing function"
2972                      : "use of parameter from containing function");
2973               error ("  %q+#D declared here", decl);
2974               return error_mark_node;
2975             }
2976         }
2977
2978       /* Also disallow uses of function parameters outside the function
2979          body, except inside an unevaluated context (i.e. decltype).  */
2980       if (TREE_CODE (decl) == PARM_DECL
2981           && DECL_CONTEXT (decl) == NULL_TREE
2982           && !cp_unevaluated_operand)
2983         {
2984           error ("use of parameter %qD outside function body", decl);
2985           return error_mark_node;
2986         }
2987     }
2988
2989   /* If we didn't find anything, or what we found was a type,
2990      then this wasn't really an id-expression.  */
2991   if (TREE_CODE (decl) == TEMPLATE_DECL
2992       && !DECL_FUNCTION_TEMPLATE_P (decl))
2993     {
2994       *error_msg = "missing template arguments";
2995       return error_mark_node;
2996     }
2997   else if (TREE_CODE (decl) == TYPE_DECL
2998            || TREE_CODE (decl) == NAMESPACE_DECL)
2999     {
3000       *error_msg = "expected primary-expression";
3001       return error_mark_node;
3002     }
3003
3004   /* If the name resolved to a template parameter, there is no
3005      need to look it up again later.  */
3006   if ((TREE_CODE (decl) == CONST_DECL && DECL_TEMPLATE_PARM_P (decl))
3007       || TREE_CODE (decl) == TEMPLATE_PARM_INDEX)
3008     {
3009       tree r;
3010
3011       *idk = CP_ID_KIND_NONE;
3012       if (TREE_CODE (decl) == TEMPLATE_PARM_INDEX)
3013         decl = TEMPLATE_PARM_DECL (decl);
3014       r = convert_from_reference (DECL_INITIAL (decl));
3015
3016       if (integral_constant_expression_p
3017           && !dependent_type_p (TREE_TYPE (decl))
3018           && !(INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (r))))
3019         {
3020           if (!allow_non_integral_constant_expression_p)
3021             error ("template parameter %qD of type %qT is not allowed in "
3022                    "an integral constant expression because it is not of "
3023                    "integral or enumeration type", decl, TREE_TYPE (decl));
3024           *non_integral_constant_expression_p = true;
3025         }
3026       return r;
3027     }
3028   /* Similarly, we resolve enumeration constants to their
3029      underlying values.  */
3030   else if (TREE_CODE (decl) == CONST_DECL)
3031     {
3032       *idk = CP_ID_KIND_NONE;
3033       if (!processing_template_decl)
3034         {
3035           used_types_insert (TREE_TYPE (decl));
3036           return DECL_INITIAL (decl);
3037         }
3038       return decl;
3039     }
3040   else
3041     {
3042       bool dependent_p;
3043
3044       /* If the declaration was explicitly qualified indicate
3045          that.  The semantics of `A::f(3)' are different than
3046          `f(3)' if `f' is virtual.  */
3047       *idk = (scope
3048               ? CP_ID_KIND_QUALIFIED
3049               : (TREE_CODE (decl) == TEMPLATE_ID_EXPR
3050                  ? CP_ID_KIND_TEMPLATE_ID
3051                  : CP_ID_KIND_UNQUALIFIED));
3052
3053
3054       /* [temp.dep.expr]
3055
3056          An id-expression is type-dependent if it contains an
3057          identifier that was declared with a dependent type.
3058
3059          The standard is not very specific about an id-expression that
3060          names a set of overloaded functions.  What if some of them
3061          have dependent types and some of them do not?  Presumably,
3062          such a name should be treated as a dependent name.  */
3063       /* Assume the name is not dependent.  */
3064       dependent_p = false;
3065       if (!processing_template_decl)
3066         /* No names are dependent outside a template.  */
3067         ;
3068       /* A template-id where the name of the template was not resolved
3069          is definitely dependent.  */
3070       else if (TREE_CODE (decl) == TEMPLATE_ID_EXPR
3071                && (TREE_CODE (TREE_OPERAND (decl, 0))
3072                    == IDENTIFIER_NODE))
3073         dependent_p = true;
3074       /* For anything except an overloaded function, just check its
3075          type.  */
3076       else if (!is_overloaded_fn (decl))
3077         dependent_p
3078           = dependent_type_p (TREE_TYPE (decl));
3079       /* For a set of overloaded functions, check each of the
3080          functions.  */
3081       else
3082         {
3083           tree fns = decl;
3084
3085           if (BASELINK_P (fns))
3086             fns = BASELINK_FUNCTIONS (fns);
3087
3088           /* For a template-id, check to see if the template
3089              arguments are dependent.  */
3090           if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
3091             {
3092               tree args = TREE_OPERAND (fns, 1);
3093               dependent_p = any_dependent_template_arguments_p (args);
3094               /* The functions are those referred to by the
3095                  template-id.  */
3096               fns = TREE_OPERAND (fns, 0);
3097             }
3098
3099           /* If there are no dependent template arguments, go through
3100              the overloaded functions.  */
3101           while (fns && !dependent_p)
3102             {
3103               tree fn = OVL_CURRENT (fns);
3104
3105               /* Member functions of dependent classes are
3106                  dependent.  */
3107               if (TREE_CODE (fn) == FUNCTION_DECL
3108                   && type_dependent_expression_p (fn))
3109                 dependent_p = true;
3110               else if (TREE_CODE (fn) == TEMPLATE_DECL
3111                        && dependent_template_p (fn))
3112                 dependent_p = true;
3113
3114               fns = OVL_NEXT (fns);
3115             }
3116         }
3117
3118       /* If the name was dependent on a template parameter, we will
3119          resolve the name at instantiation time.  */
3120       if (dependent_p)
3121         {
3122           /* Create a SCOPE_REF for qualified names, if the scope is
3123              dependent.  */
3124           if (scope)
3125             {
3126               if (TYPE_P (scope))
3127                 {
3128                   if (address_p && done)
3129                     decl = finish_qualified_id_expr (scope, decl,
3130                                                      done, address_p,
3131                                                      template_p,
3132                                                      template_arg_p);
3133                   else
3134                     {
3135                       tree type = NULL_TREE;
3136                       if (DECL_P (decl) && !dependent_scope_p (scope))
3137                         type = TREE_TYPE (decl);
3138                       decl = build_qualified_name (type,
3139                                                    scope,
3140                                                    id_expression,
3141                                                    template_p);
3142                     }
3143                 }
3144               if (TREE_TYPE (decl))
3145                 decl = convert_from_reference (decl);
3146               return decl;
3147             }
3148           /* A TEMPLATE_ID already contains all the information we
3149              need.  */
3150           if (TREE_CODE (id_expression) == TEMPLATE_ID_EXPR)
3151             return id_expression;
3152           *idk = CP_ID_KIND_UNQUALIFIED_DEPENDENT;
3153           /* If we found a variable, then name lookup during the
3154              instantiation will always resolve to the same VAR_DECL
3155              (or an instantiation thereof).  */
3156           if (TREE_CODE (decl) == VAR_DECL
3157               || TREE_CODE (decl) == PARM_DECL)
3158             return convert_from_reference (decl);
3159           /* The same is true for FIELD_DECL, but we also need to
3160              make sure that the syntax is correct.  */
3161           else if (TREE_CODE (decl) == FIELD_DECL)
3162             {
3163               /* Since SCOPE is NULL here, this is an unqualified name.
3164                  Access checking has been performed during name lookup
3165                  already.  Turn off checking to avoid duplicate errors.  */
3166               push_deferring_access_checks (dk_no_check);
3167               decl = finish_non_static_data_member
3168                        (decl, NULL_TREE,
3169                         /*qualifying_scope=*/NULL_TREE);
3170               pop_deferring_access_checks ();
3171               return decl;
3172             }
3173           return id_expression;
3174         }
3175
3176       if (TREE_CODE (decl) == NAMESPACE_DECL)
3177         {
3178           error ("use of namespace %qD as expression", decl);
3179           return error_mark_node;
3180         }
3181       else if (DECL_CLASS_TEMPLATE_P (decl))
3182         {
3183           error ("use of class template %qT as expression", decl);
3184           return error_mark_node;
3185         }
3186       else if (TREE_CODE (decl) == TREE_LIST)
3187         {
3188           /* Ambiguous reference to base members.  */
3189           error ("request for member %qD is ambiguous in "
3190                  "multiple inheritance lattice", id_expression);
3191           print_candidates (decl);
3192           return error_mark_node;
3193         }
3194
3195       /* Mark variable-like entities as used.  Functions are similarly
3196          marked either below or after overload resolution.  */
3197       if (TREE_CODE (decl) == VAR_DECL
3198           || TREE_CODE (decl) == PARM_DECL
3199           || TREE_CODE (decl) == RESULT_DECL)
3200         mark_used (decl);
3201
3202       /* Only certain kinds of names are allowed in constant
3203          expression.  Enumerators and template parameters have already
3204          been handled above.  */
3205       if (! error_operand_p (decl)
3206           && integral_constant_expression_p
3207           && ! decl_constant_var_p (decl)
3208           && ! builtin_valid_in_constant_expr_p (decl))
3209         {
3210           if (!allow_non_integral_constant_expression_p)
3211             {
3212               error ("%qD cannot appear in a constant-expression", decl);
3213               return error_mark_node;
3214             }
3215           *non_integral_constant_expression_p = true;
3216         }
3217
3218       if (scope)
3219         {
3220           decl = (adjust_result_of_qualified_name_lookup
3221                   (decl, scope, current_class_type));
3222
3223           if (TREE_CODE (decl) == FUNCTION_DECL)
3224             mark_used (decl);
3225
3226           if (TREE_CODE (decl) == FIELD_DECL || BASELINK_P (decl))
3227             decl = finish_qualified_id_expr (scope,
3228                                              decl,
3229                                              done,
3230                                              address_p,
3231                                              template_p,
3232                                              template_arg_p);
3233           else
3234             {
3235               tree r = convert_from_reference (decl);
3236
3237               /* In a template, return a SCOPE_REF for most qualified-ids
3238                  so that we can check access at instantiation time.  But if
3239                  we're looking at a member of the current instantiation, we
3240                  know we have access and building up the SCOPE_REF confuses
3241                  non-type template argument handling.  */
3242               if (processing_template_decl && TYPE_P (scope)
3243                   && !currently_open_class (scope))
3244                 r = build_qualified_name (TREE_TYPE (r),
3245                                           scope, decl,
3246                                           template_p);
3247               decl = r;
3248             }
3249         }
3250       else if (TREE_CODE (decl) == FIELD_DECL)
3251         {
3252           /* Since SCOPE is NULL here, this is an unqualified name.
3253              Access checking has been performed during name lookup
3254              already.  Turn off checking to avoid duplicate errors.  */
3255           push_deferring_access_checks (dk_no_check);
3256           decl = finish_non_static_data_member (decl, NULL_TREE,
3257                                                 /*qualifying_scope=*/NULL_TREE);
3258           pop_deferring_access_checks ();
3259         }
3260       else if (is_overloaded_fn (decl))
3261         {
3262           tree first_fn;
3263
3264           first_fn = get_first_fn (decl);
3265           if (TREE_CODE (first_fn) == TEMPLATE_DECL)
3266             first_fn = DECL_TEMPLATE_RESULT (first_fn);
3267
3268           if (!really_overloaded_fn (decl))
3269             mark_used (first_fn);
3270
3271           if (!template_arg_p
3272               && TREE_CODE (first_fn) == FUNCTION_DECL
3273               && DECL_FUNCTION_MEMBER_P (first_fn)
3274               && !shared_member_p (decl))
3275             {
3276               /* A set of member functions.  */
3277               decl = maybe_dummy_object (DECL_CONTEXT (first_fn), 0);
3278               return finish_class_member_access_expr (decl, id_expression,
3279                                                       /*template_p=*/false,
3280                                                       tf_warning_or_error);
3281             }
3282
3283           decl = baselink_for_fns (decl);
3284         }
3285       else
3286         {
3287           if (DECL_P (decl) && DECL_NONLOCAL (decl)
3288               && DECL_CLASS_SCOPE_P (decl))
3289             {
3290               tree context = context_for_name_lookup (decl); 
3291               if (context != current_class_type)
3292                 {
3293                   tree path = currently_open_derived_class (context);
3294                   perform_or_defer_access_check (TYPE_BINFO (path),
3295                                                  decl, decl);
3296                 }
3297             }
3298
3299           decl = convert_from_reference (decl);
3300         }
3301     }
3302
3303   if (TREE_DEPRECATED (decl))
3304     warn_deprecated_use (decl, NULL_TREE);
3305
3306   return decl;
3307 }
3308
3309 /* Implement the __typeof keyword: Return the type of EXPR, suitable for
3310    use as a type-specifier.  */
3311
3312 tree
3313 finish_typeof (tree expr)
3314 {
3315   tree type;
3316
3317   if (type_dependent_expression_p (expr))
3318     {
3319       type = cxx_make_type (TYPEOF_TYPE);
3320       TYPEOF_TYPE_EXPR (type) = expr;
3321       SET_TYPE_STRUCTURAL_EQUALITY (type);
3322
3323       return type;
3324     }
3325
3326   expr = mark_type_use (expr);
3327
3328   type = unlowered_expr_type (expr);
3329
3330   if (!type || type == unknown_type_node)
3331     {
3332       error ("type of %qE is unknown", expr);
3333       return error_mark_node;
3334     }
3335
3336   return type;
3337 }
3338
3339 /* Perform C++-specific checks for __builtin_offsetof before calling
3340    fold_offsetof.  */
3341
3342 tree
3343 finish_offsetof (tree expr)
3344 {
3345   if (TREE_CODE (expr) == PSEUDO_DTOR_EXPR)
3346     {
3347       error ("cannot apply %<offsetof%> to destructor %<~%T%>",
3348               TREE_OPERAND (expr, 2));
3349       return error_mark_node;
3350     }
3351   if (TREE_CODE (TREE_TYPE (expr)) == FUNCTION_TYPE
3352       || TREE_CODE (TREE_TYPE (expr)) == METHOD_TYPE
3353       || TREE_TYPE (expr) == unknown_type_node)
3354     {
3355       if (TREE_CODE (expr) == COMPONENT_REF
3356           || TREE_CODE (expr) == COMPOUND_EXPR)
3357         expr = TREE_OPERAND (expr, 1);
3358       error ("cannot apply %<offsetof%> to member function %qD", expr);
3359       return error_mark_node;
3360     }
3361   if (TREE_CODE (expr) == INDIRECT_REF && REFERENCE_REF_P (expr))
3362     expr = TREE_OPERAND (expr, 0);
3363   return fold_offsetof (expr, NULL_TREE);
3364 }
3365
3366 /* Replace the AGGR_INIT_EXPR at *TP with an equivalent CALL_EXPR.  This
3367    function is broken out from the above for the benefit of the tree-ssa
3368    project.  */
3369
3370 void
3371 simplify_aggr_init_expr (tree *tp)
3372 {
3373   tree aggr_init_expr = *tp;
3374
3375   /* Form an appropriate CALL_EXPR.  */
3376   tree fn = AGGR_INIT_EXPR_FN (aggr_init_expr);
3377   tree slot = AGGR_INIT_EXPR_SLOT (aggr_init_expr);
3378   tree type = TREE_TYPE (slot);
3379
3380   tree call_expr;
3381   enum style_t { ctor, arg, pcc } style;
3382
3383   if (AGGR_INIT_VIA_CTOR_P (aggr_init_expr))
3384     style = ctor;
3385 #ifdef PCC_STATIC_STRUCT_RETURN
3386   else if (1)
3387     style = pcc;
3388 #endif
3389   else
3390     {
3391       gcc_assert (TREE_ADDRESSABLE (type));
3392       style = arg;
3393     }
3394
3395   call_expr = build_call_array_loc (input_location,
3396                                     TREE_TYPE (TREE_TYPE (TREE_TYPE (fn))),
3397                                     fn,
3398                                     aggr_init_expr_nargs (aggr_init_expr),
3399                                     AGGR_INIT_EXPR_ARGP (aggr_init_expr));
3400   TREE_NOTHROW (call_expr) = TREE_NOTHROW (aggr_init_expr);
3401
3402   if (style == ctor)
3403     {
3404       /* Replace the first argument to the ctor with the address of the
3405          slot.  */
3406       cxx_mark_addressable (slot);
3407       CALL_EXPR_ARG (call_expr, 0) =
3408         build1 (ADDR_EXPR, build_pointer_type (type), slot);
3409     }
3410   else if (style == arg)
3411     {
3412       /* Just mark it addressable here, and leave the rest to
3413          expand_call{,_inline}.  */
3414       cxx_mark_addressable (slot);
3415       CALL_EXPR_RETURN_SLOT_OPT (call_expr) = true;
3416       call_expr = build2 (INIT_EXPR, TREE_TYPE (call_expr), slot, call_expr);
3417     }
3418   else if (style == pcc)
3419     {
3420       /* If we're using the non-reentrant PCC calling convention, then we
3421          need to copy the returned value out of the static buffer into the
3422          SLOT.  */
3423       push_deferring_access_checks (dk_no_check);
3424       call_expr = build_aggr_init (slot, call_expr,
3425                                    DIRECT_BIND | LOOKUP_ONLYCONVERTING,
3426                                    tf_warning_or_error);
3427       pop_deferring_access_checks ();
3428       call_expr = build2 (COMPOUND_EXPR, TREE_TYPE (slot), call_expr, slot);
3429     }
3430
3431   if (AGGR_INIT_ZERO_FIRST (aggr_init_expr))
3432     {
3433       tree init = build_zero_init (type, NULL_TREE,
3434                                    /*static_storage_p=*/false);
3435       init = build2 (INIT_EXPR, void_type_node, slot, init);
3436       call_expr = build2 (COMPOUND_EXPR, TREE_TYPE (call_expr),
3437                           init, call_expr);
3438     }
3439
3440   *tp = call_expr;
3441 }
3442
3443 /* Emit all thunks to FN that should be emitted when FN is emitted.  */
3444
3445 void
3446 emit_associated_thunks (tree fn)
3447 {
3448   /* When we use vcall offsets, we emit thunks with the virtual
3449      functions to which they thunk. The whole point of vcall offsets
3450      is so that you can know statically the entire set of thunks that
3451      will ever be needed for a given virtual function, thereby
3452      enabling you to output all the thunks with the function itself.  */
3453   if (DECL_VIRTUAL_P (fn)
3454       /* Do not emit thunks for extern template instantiations.  */
3455       && ! DECL_REALLY_EXTERN (fn))
3456     {
3457       tree thunk;
3458
3459       for (thunk = DECL_THUNKS (fn); thunk; thunk = DECL_CHAIN (thunk))
3460         {
3461           if (!THUNK_ALIAS (thunk))
3462             {
3463               use_thunk (thunk, /*emit_p=*/1);
3464               if (DECL_RESULT_THUNK_P (thunk))
3465                 {
3466                   tree probe;
3467
3468                   for (probe = DECL_THUNKS (thunk);
3469                        probe; probe = DECL_CHAIN (probe))
3470                     use_thunk (probe, /*emit_p=*/1);
3471                 }
3472             }
3473           else
3474             gcc_assert (!DECL_THUNKS (thunk));
3475         }
3476     }
3477 }
3478
3479 /* Generate RTL for FN.  */
3480
3481 bool
3482 expand_or_defer_fn_1 (tree fn)
3483 {
3484   /* When the parser calls us after finishing the body of a template
3485      function, we don't really want to expand the body.  */
3486   if (processing_template_decl)
3487     {
3488       /* Normally, collection only occurs in rest_of_compilation.  So,
3489          if we don't collect here, we never collect junk generated
3490          during the processing of templates until we hit a
3491          non-template function.  It's not safe to do this inside a
3492          nested class, though, as the parser may have local state that
3493          is not a GC root.  */
3494       if (!function_depth)
3495         ggc_collect ();
3496       return false;
3497     }
3498
3499   gcc_assert (DECL_SAVED_TREE (fn));
3500
3501   /* If this is a constructor or destructor body, we have to clone
3502      it.  */
3503   if (maybe_clone_body (fn))
3504     {
3505       /* We don't want to process FN again, so pretend we've written
3506          it out, even though we haven't.  */
3507       TREE_ASM_WRITTEN (fn) = 1;
3508       DECL_SAVED_TREE (fn) = NULL_TREE;
3509       return false;
3510     }
3511
3512   /* We make a decision about linkage for these functions at the end
3513      of the compilation.  Until that point, we do not want the back
3514      end to output them -- but we do want it to see the bodies of
3515      these functions so that it can inline them as appropriate.  */
3516   if (DECL_DECLARED_INLINE_P (fn) || DECL_IMPLICIT_INSTANTIATION (fn))
3517     {
3518       if (DECL_INTERFACE_KNOWN (fn))
3519         /* We've already made a decision as to how this function will
3520            be handled.  */;
3521       else if (!at_eof)
3522         {
3523           DECL_EXTERNAL (fn) = 1;
3524           DECL_NOT_REALLY_EXTERN (fn) = 1;
3525           note_vague_linkage_fn (fn);
3526           /* A non-template inline function with external linkage will
3527              always be COMDAT.  As we must eventually determine the
3528              linkage of all functions, and as that causes writes to
3529              the data mapped in from the PCH file, it's advantageous
3530              to mark the functions at this point.  */
3531           if (!DECL_IMPLICIT_INSTANTIATION (fn))
3532             {
3533               /* This function must have external linkage, as
3534                  otherwise DECL_INTERFACE_KNOWN would have been
3535                  set.  */
3536               gcc_assert (TREE_PUBLIC (fn));
3537               comdat_linkage (fn);
3538               DECL_INTERFACE_KNOWN (fn) = 1;
3539             }
3540         }
3541       else
3542         import_export_decl (fn);
3543
3544       /* If the user wants us to keep all inline functions, then mark
3545          this function as needed so that finish_file will make sure to
3546          output it later.  Similarly, all dllexport'd functions must
3547          be emitted; there may be callers in other DLLs.  */
3548       if ((flag_keep_inline_functions
3549            && DECL_DECLARED_INLINE_P (fn)
3550            && !DECL_REALLY_EXTERN (fn))
3551           || (flag_keep_inline_dllexport
3552               && lookup_attribute ("dllexport", DECL_ATTRIBUTES (fn))))
3553         mark_needed (fn);
3554     }
3555
3556   /* There's no reason to do any of the work here if we're only doing
3557      semantic analysis; this code just generates RTL.  */
3558   if (flag_syntax_only)
3559     return false;
3560
3561   return true;
3562 }
3563
3564 void
3565 expand_or_defer_fn (tree fn)
3566 {
3567   if (expand_or_defer_fn_1 (fn))
3568     {
3569       function_depth++;
3570
3571       /* Expand or defer, at the whim of the compilation unit manager.  */
3572       cgraph_finalize_function (fn, function_depth > 1);
3573       emit_associated_thunks (fn);
3574
3575       function_depth--;
3576     }
3577 }
3578
3579 struct nrv_data
3580 {
3581   tree var;
3582   tree result;
3583   htab_t visited;
3584 };
3585
3586 /* Helper function for walk_tree, used by finalize_nrv below.  */
3587
3588 static tree
3589 finalize_nrv_r (tree* tp, int* walk_subtrees, void* data)
3590 {
3591   struct nrv_data *dp = (struct nrv_data *)data;
3592   void **slot;
3593
3594   /* No need to walk into types.  There wouldn't be any need to walk into
3595      non-statements, except that we have to consider STMT_EXPRs.  */
3596   if (TYPE_P (*tp))
3597     *walk_subtrees = 0;
3598   /* Change all returns to just refer to the RESULT_DECL; this is a nop,
3599      but differs from using NULL_TREE in that it indicates that we care
3600      about the value of the RESULT_DECL.  */
3601   else if (TREE_CODE (*tp) == RETURN_EXPR)
3602     TREE_OPERAND (*tp, 0) = dp->result;
3603   /* Change all cleanups for the NRV to only run when an exception is
3604      thrown.  */
3605   else if (TREE_CODE (*tp) == CLEANUP_STMT
3606            && CLEANUP_DECL (*tp) == dp->var)
3607     CLEANUP_EH_ONLY (*tp) = 1;
3608   /* Replace the DECL_EXPR for the NRV with an initialization of the
3609      RESULT_DECL, if needed.  */
3610   else if (TREE_CODE (*tp) == DECL_EXPR
3611            && DECL_EXPR_DECL (*tp) == dp->var)
3612     {
3613       tree init;
3614       if (DECL_INITIAL (dp->var)
3615           && DECL_INITIAL (dp->var) != error_mark_node)
3616         init = build2 (INIT_EXPR, void_type_node, dp->result,
3617                        DECL_INITIAL (dp->var));
3618       else
3619         init = build_empty_stmt (EXPR_LOCATION (*tp));
3620       DECL_INITIAL (dp->var) = NULL_TREE;
3621       SET_EXPR_LOCATION (init, EXPR_LOCATION (*tp));
3622       *tp = init;
3623     }
3624   /* And replace all uses of the NRV with the RESULT_DECL.  */
3625   else if (*tp == dp->var)
3626     *tp = dp->result;
3627
3628   /* Avoid walking into the same tree more than once.  Unfortunately, we
3629      can't just use walk_tree_without duplicates because it would only call
3630      us for the first occurrence of dp->var in the function body.  */
3631   slot = htab_find_slot (dp->visited, *tp, INSERT);
3632   if (*slot)
3633     *walk_subtrees = 0;
3634   else
3635     *slot = *tp;
3636
3637   /* Keep iterating.  */
3638   return NULL_TREE;
3639 }
3640
3641 /* Called from finish_function to implement the named return value
3642    optimization by overriding all the RETURN_EXPRs and pertinent
3643    CLEANUP_STMTs and replacing all occurrences of VAR with RESULT, the
3644    RESULT_DECL for the function.  */
3645
3646 void
3647 finalize_nrv (tree *tp, tree var, tree result)
3648 {
3649   struct nrv_data data;
3650
3651   /* Copy name from VAR to RESULT.  */
3652   DECL_NAME (result) = DECL_NAME (var);
3653   /* Don't forget that we take its address.  */
3654   TREE_ADDRESSABLE (result) = TREE_ADDRESSABLE (var);
3655   /* Finally set DECL_VALUE_EXPR to avoid assigning
3656      a stack slot at -O0 for the original var and debug info
3657      uses RESULT location for VAR.  */
3658   SET_DECL_VALUE_EXPR (var, result);
3659   DECL_HAS_VALUE_EXPR_P (var) = 1;
3660
3661   data.var = var;
3662   data.result = result;
3663   data.visited = htab_create (37, htab_hash_pointer, htab_eq_pointer, NULL);
3664   cp_walk_tree (tp, finalize_nrv_r, &data, 0);
3665   htab_delete (data.visited);
3666 }
3667 \f
3668 /* Create CP_OMP_CLAUSE_INFO for clause C.  Returns true if it is invalid.  */
3669
3670 bool
3671 cxx_omp_create_clause_info (tree c, tree type, bool need_default_ctor,
3672                             bool need_copy_ctor, bool need_copy_assignment)
3673 {
3674   int save_errorcount = errorcount;
3675   tree info, t;
3676
3677   /* Always allocate 3 elements for simplicity.  These are the
3678      function decls for the ctor, dtor, and assignment op.
3679      This layout is known to the three lang hooks,
3680      cxx_omp_clause_default_init, cxx_omp_clause_copy_init,
3681      and cxx_omp_clause_assign_op.  */
3682   info = make_tree_vec (3);
3683   CP_OMP_CLAUSE_INFO (c) = info;
3684
3685   if (need_default_ctor || need_copy_ctor)
3686     {
3687       if (need_default_ctor)
3688         t = get_default_ctor (type);
3689       else
3690         t = get_copy_ctor (type);
3691
3692       if (t && !trivial_fn_p (t))
3693         TREE_VEC_ELT (info, 0) = t;
3694     }
3695
3696   if ((need_default_ctor || need_copy_ctor)
3697       && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
3698     TREE_VEC_ELT (info, 1) = get_dtor (type);
3699
3700   if (need_copy_assignment)
3701     {
3702       t = get_copy_assign (type);
3703
3704       if (t && !trivial_fn_p (t))
3705         TREE_VEC_ELT (info, 2) = t;
3706     }
3707
3708   return errorcount != save_errorcount;
3709 }
3710
3711 /* For all elements of CLAUSES, validate them vs OpenMP constraints.
3712    Remove any elements from the list that are invalid.  */
3713
3714 tree
3715 finish_omp_clauses (tree clauses)
3716 {
3717   bitmap_head generic_head, firstprivate_head, lastprivate_head;
3718   tree c, t, *pc = &clauses;
3719   const char *name;
3720
3721   bitmap_obstack_initialize (NULL);
3722   bitmap_initialize (&generic_head, &bitmap_default_obstack);
3723   bitmap_initialize (&firstprivate_head, &bitmap_default_obstack);
3724   bitmap_initialize (&lastprivate_head, &bitmap_default_obstack);
3725
3726   for (pc = &clauses, c = clauses; c ; c = *pc)
3727     {
3728       bool remove = false;
3729
3730       switch (OMP_CLAUSE_CODE (c))
3731         {
3732         case OMP_CLAUSE_SHARED:
3733           name = "shared";
3734           goto check_dup_generic;
3735         case OMP_CLAUSE_PRIVATE:
3736           name = "private";
3737           goto check_dup_generic;
3738         case OMP_CLAUSE_REDUCTION:
3739           name = "reduction";
3740           goto check_dup_generic;
3741         case OMP_CLAUSE_COPYPRIVATE:
3742           name = "copyprivate";
3743           goto check_dup_generic;
3744         case OMP_CLAUSE_COPYIN:
3745           name = "copyin";
3746           goto check_dup_generic;
3747         check_dup_generic:
3748           t = OMP_CLAUSE_DECL (c);
3749           if (TREE_CODE (t) != VAR_DECL && TREE_CODE (t) != PARM_DECL)
3750             {
3751               if (processing_template_decl)
3752                 break;
3753               if (DECL_P (t))
3754                 error ("%qD is not a variable in clause %qs", t, name);
3755               else
3756                 error ("%qE is not a variable in clause %qs", t, name);
3757               remove = true;
3758             }
3759           else if (bitmap_bit_p (&generic_head, DECL_UID (t))
3760                    || bitmap_bit_p (&firstprivate_head, DECL_UID (t))
3761                    || bitmap_bit_p (&lastprivate_head, DECL_UID (t)))
3762             {
3763               error ("%qD appears more than once in data clauses", t);
3764               remove = true;
3765             }
3766           else
3767             bitmap_set_bit (&generic_head, DECL_UID (t));
3768           break;
3769
3770         case OMP_CLAUSE_FIRSTPRIVATE:
3771           t = OMP_CLAUSE_DECL (c);
3772           if (TREE_CODE (t) != VAR_DECL && TREE_CODE (t) != PARM_DECL)
3773             {
3774               if (processing_template_decl)
3775                 break;
3776               if (DECL_P (t))
3777                 error ("%qD is not a variable in clause %<firstprivate%>", t);
3778               else
3779                 error ("%qE is not a variable in clause %<firstprivate%>", t);
3780               remove = true;
3781             }
3782           else if (bitmap_bit_p (&generic_head, DECL_UID (t))
3783                    || bitmap_bit_p (&firstprivate_head, DECL_UID (t)))
3784             {
3785               error ("%qD appears more than once in data clauses", t);
3786               remove = true;
3787             }
3788           else
3789             bitmap_set_bit (&firstprivate_head, DECL_UID (t));
3790           break;
3791
3792         case OMP_CLAUSE_LASTPRIVATE:
3793           t = OMP_CLAUSE_DECL (c);
3794           if (TREE_CODE (t) != VAR_DECL && TREE_CODE (t) != PARM_DECL)
3795             {
3796               if (processing_template_decl)
3797                 break;
3798               if (DECL_P (t))
3799                 error ("%qD is not a variable in clause %<lastprivate%>", t);
3800               else
3801                 error ("%qE is not a variable in clause %<lastprivate%>", t);
3802               remove = true;
3803             }
3804           else if (bitmap_bit_p (&generic_head, DECL_UID (t))
3805                    || bitmap_bit_p (&lastprivate_head, DECL_UID (t)))
3806             {
3807               error ("%qD appears more than once in data clauses", t);
3808               remove = true;
3809             }
3810           else
3811             bitmap_set_bit (&lastprivate_head, DECL_UID (t));
3812           break;
3813
3814         case OMP_CLAUSE_IF:
3815           t = OMP_CLAUSE_IF_EXPR (c);
3816           t = maybe_convert_cond (t);
3817           if (t == error_mark_node)
3818             remove = true;
3819           OMP_CLAUSE_IF_EXPR (c) = t;
3820           break;
3821
3822         case OMP_CLAUSE_NUM_THREADS:
3823           t = OMP_CLAUSE_NUM_THREADS_EXPR (c);
3824           if (t == error_mark_node)
3825             remove = true;
3826           else if (!type_dependent_expression_p (t)
3827                    && !INTEGRAL_TYPE_P (TREE_TYPE (t)))
3828             {
3829               error ("num_threads expression must be integral");
3830               remove = true;
3831             }
3832           break;
3833
3834         case OMP_CLAUSE_SCHEDULE:
3835           t = OMP_CLAUSE_SCHEDULE_CHUNK_EXPR (c);
3836           if (t == NULL)
3837             ;
3838           else if (t == error_mark_node)
3839             remove = true;
3840           else if (!type_dependent_expression_p (t)
3841                    && !INTEGRAL_TYPE_P (TREE_TYPE (t)))
3842             {
3843               error ("schedule chunk size expression must be integral");
3844               remove = true;
3845             }
3846           break;
3847
3848         case OMP_CLAUSE_NOWAIT:
3849         case OMP_CLAUSE_ORDERED:
3850         case OMP_CLAUSE_DEFAULT:
3851         case OMP_CLAUSE_UNTIED:
3852         case OMP_CLAUSE_COLLAPSE:
3853           break;
3854
3855         default:
3856           gcc_unreachable ();
3857         }
3858
3859       if (remove)
3860         *pc = OMP_CLAUSE_CHAIN (c);
3861       else
3862         pc = &OMP_CLAUSE_CHAIN (c);
3863     }
3864
3865   for (pc = &clauses, c = clauses; c ; c = *pc)
3866     {
3867       enum omp_clause_code c_kind = OMP_CLAUSE_CODE (c);
3868       bool remove = false;
3869       bool need_complete_non_reference = false;
3870       bool need_default_ctor = false;
3871       bool need_copy_ctor = false;
3872       bool need_copy_assignment = false;
3873       bool need_implicitly_determined = false;
3874       tree type, inner_type;
3875
3876       switch (c_kind)
3877         {
3878         case OMP_CLAUSE_SHARED:
3879           name = "shared";
3880           need_implicitly_determined = true;
3881           break;
3882         case OMP_CLAUSE_PRIVATE:
3883           name = "private";
3884           need_complete_non_reference = true;
3885           need_default_ctor = true;
3886           need_implicitly_determined = true;
3887           break;
3888         case OMP_CLAUSE_FIRSTPRIVATE:
3889           name = "firstprivate";
3890           need_complete_non_reference = true;
3891           need_copy_ctor = true;
3892           need_implicitly_determined = true;
3893           break;
3894         case OMP_CLAUSE_LASTPRIVATE:
3895           name = "lastprivate";
3896           need_complete_non_reference = true;
3897           need_copy_assignment = true;
3898           need_implicitly_determined = true;
3899           break;
3900         case OMP_CLAUSE_REDUCTION:
3901           name = "reduction";
3902           need_implicitly_determined = true;
3903           break;
3904         case OMP_CLAUSE_COPYPRIVATE:
3905           name = "copyprivate";
3906           need_copy_assignment = true;
3907           break;
3908         case OMP_CLAUSE_COPYIN:
3909           name = "copyin";
3910           need_copy_assignment = true;
3911           break;
3912         default:
3913           pc = &OMP_CLAUSE_CHAIN (c);
3914           continue;
3915         }
3916
3917       t = OMP_CLAUSE_DECL (c);
3918       if (processing_template_decl
3919           && TREE_CODE (t) != VAR_DECL && TREE_CODE (t) != PARM_DECL)
3920         {
3921           pc = &OMP_CLAUSE_CHAIN (c);
3922           continue;
3923         }
3924
3925       switch (c_kind)
3926         {
3927         case OMP_CLAUSE_LASTPRIVATE:
3928           if (!bitmap_bit_p (&firstprivate_head, DECL_UID (t)))
3929             need_default_ctor = true;
3930           break;
3931
3932         case OMP_CLAUSE_REDUCTION:
3933           if (AGGREGATE_TYPE_P (TREE_TYPE (t))
3934               || POINTER_TYPE_P (TREE_TYPE (t)))
3935             {
3936               error ("%qE has invalid type for %<reduction%>", t);
3937               remove = true;
3938             }
3939           else if (FLOAT_TYPE_P (TREE_TYPE (t)))
3940             {
3941               enum tree_code r_code = OMP_CLAUSE_REDUCTION_CODE (c);
3942               switch (r_code)
3943                 {
3944                 case PLUS_EXPR:
3945                 case MULT_EXPR:
3946                 case MINUS_EXPR:
3947                   break;
3948                 default:
3949                   error ("%qE has invalid type for %<reduction(%s)%>",
3950                          t, operator_name_info[r_code].name);
3951                   remove = true;
3952                 }
3953             }
3954           break;
3955
3956         case OMP_CLAUSE_COPYIN:
3957           if (TREE_CODE (t) != VAR_DECL || !DECL_THREAD_LOCAL_P (t))
3958             {
3959               error ("%qE must be %<threadprivate%> for %<copyin%>", t);
3960               remove = true;
3961             }
3962           break;
3963
3964         default:
3965           break;
3966         }
3967
3968       if (need_complete_non_reference)
3969         {
3970           t = require_complete_type (t);
3971           if (t == error_mark_node)
3972             remove = true;
3973           else if (TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE)
3974             {
3975               error ("%qE has reference type for %qs", t, name);
3976               remove = true;
3977             }
3978         }
3979       if (need_implicitly_determined)
3980         {
3981           const char *share_name = NULL;
3982
3983           if (TREE_CODE (t) == VAR_DECL && DECL_THREAD_LOCAL_P (t))
3984             share_name = "threadprivate";
3985           else switch (cxx_omp_predetermined_sharing (t))
3986             {
3987             case OMP_CLAUSE_DEFAULT_UNSPECIFIED:
3988               break;
3989             case OMP_CLAUSE_DEFAULT_SHARED:
3990               share_name = "shared";
3991               break;
3992             case OMP_CLAUSE_DEFAULT_PRIVATE:
3993               share_name = "private";
3994               break;
3995             default:
3996               gcc_unreachable ();
3997             }
3998           if (share_name)
3999             {
4000               error ("%qE is predetermined %qs for %qs",
4001                      t, share_name, name);
4002               remove = true;
4003             }
4004         }
4005
4006       /* We're interested in the base element, not arrays.  */
4007       inner_type = type = TREE_TYPE (t);
4008       while (TREE_CODE (inner_type) == ARRAY_TYPE)
4009         inner_type = TREE_TYPE (inner_type);
4010
4011       /* Check for special function availability by building a call to one.
4012          Save the results, because later we won't be in the right context
4013          for making these queries.  */
4014       if (CLASS_TYPE_P (inner_type)
4015           && (need_default_ctor || need_copy_ctor || need_copy_assignment)
4016           && !type_dependent_expression_p (t)
4017           && cxx_omp_create_clause_info (c, inner_type, need_default_ctor,
4018                                          need_copy_ctor, need_copy_assignment))
4019         remove = true;
4020
4021       if (remove)
4022         *pc = OMP_CLAUSE_CHAIN (c);
4023       else
4024         pc = &OMP_CLAUSE_CHAIN (c);
4025     }
4026
4027   bitmap_obstack_release (NULL);
4028   return clauses;
4029 }
4030
4031 /* For all variables in the tree_list VARS, mark them as thread local.  */
4032
4033 void
4034 finish_omp_threadprivate (tree vars)
4035 {
4036   tree t;
4037
4038   /* Mark every variable in VARS to be assigned thread local storage.  */
4039   for (t = vars; t; t = TREE_CHAIN (t))
4040     {
4041       tree v = TREE_PURPOSE (t);
4042
4043       if (error_operand_p (v))
4044         ;
4045       else if (TREE_CODE (v) != VAR_DECL)
4046         error ("%<threadprivate%> %qD is not file, namespace "
4047                "or block scope variable", v);
4048       /* If V had already been marked threadprivate, it doesn't matter
4049          whether it had been used prior to this point.  */
4050       else if (TREE_USED (v)
4051           && (DECL_LANG_SPECIFIC (v) == NULL
4052               || !CP_DECL_THREADPRIVATE_P (v)))
4053         error ("%qE declared %<threadprivate%> after first use", v);
4054       else if (! TREE_STATIC (v) && ! DECL_EXTERNAL (v))
4055         error ("automatic variable %qE cannot be %<threadprivate%>", v);
4056       else if (! COMPLETE_TYPE_P (TREE_TYPE (v)))
4057         error ("%<threadprivate%> %qE has incomplete type", v);
4058       else if (TREE_STATIC (v) && TYPE_P (CP_DECL_CONTEXT (v))
4059                && CP_DECL_CONTEXT (v) != current_class_type)
4060         error ("%<threadprivate%> %qE directive not "
4061                "in %qT definition", v, CP_DECL_CONTEXT (v));
4062       else
4063         {
4064           /* Allocate a LANG_SPECIFIC structure for V, if needed.  */
4065           if (DECL_LANG_SPECIFIC (v) == NULL)
4066             {
4067               retrofit_lang_decl (v);
4068
4069               /* Make sure that DECL_DISCRIMINATOR_P continues to be true
4070                  after the allocation of the lang_decl structure.  */
4071               if (DECL_DISCRIMINATOR_P (v))
4072                 DECL_LANG_SPECIFIC (v)->u.base.u2sel = 1;
4073             }
4074
4075           if (! DECL_THREAD_LOCAL_P (v))
4076             {
4077               DECL_TLS_MODEL (v) = decl_default_tls_model (v);
4078               /* If rtl has been already set for this var, call
4079                  make_decl_rtl once again, so that encode_section_info
4080                  has a chance to look at the new decl flags.  */
4081               if (DECL_RTL_SET_P (v))
4082                 make_decl_rtl (v);
4083             }
4084           CP_DECL_THREADPRIVATE_P (v) = 1;
4085         }
4086     }
4087 }
4088
4089 /* Build an OpenMP structured block.  */
4090
4091 tree
4092 begin_omp_structured_block (void)
4093 {
4094   return do_pushlevel (sk_omp);
4095 }
4096
4097 tree
4098 finish_omp_structured_block (tree block)
4099 {
4100   return do_poplevel (block);
4101 }
4102
4103 /* Similarly, except force the retention of the BLOCK.  */
4104
4105 tree
4106 begin_omp_parallel (void)
4107 {
4108   keep_next_level (true);
4109   return begin_omp_structured_block ();
4110 }
4111
4112 tree
4113 finish_omp_parallel (tree clauses, tree body)
4114 {
4115   tree stmt;
4116
4117   body = finish_omp_structured_block (body);
4118
4119   stmt = make_node (OMP_PARALLEL);
4120   TREE_TYPE (stmt) = void_type_node;
4121   OMP_PARALLEL_CLAUSES (stmt) = clauses;
4122   OMP_PARALLEL_BODY (stmt) = body;
4123
4124   return add_stmt (stmt);
4125 }
4126
4127 tree
4128 begin_omp_task (void)
4129 {
4130   keep_next_level (true);
4131   return begin_omp_structured_block ();
4132 }
4133
4134 tree
4135 finish_omp_task (tree clauses, tree body)
4136 {
4137   tree stmt;
4138
4139   body = finish_omp_structured_block (body);
4140
4141   stmt = make_node (OMP_TASK);
4142   TREE_TYPE (stmt) = void_type_node;
4143   OMP_TASK_CLAUSES (stmt) = clauses;
4144   OMP_TASK_BODY (stmt) = body;
4145
4146   return add_stmt (stmt);
4147 }
4148
4149 /* Helper function for finish_omp_for.  Convert Ith random access iterator
4150    into integral iterator.  Return FALSE if successful.  */
4151
4152 static bool
4153 handle_omp_for_class_iterator (int i, location_t locus, tree declv, tree initv,
4154                                tree condv, tree incrv, tree *body,
4155                                tree *pre_body, tree clauses)
4156 {
4157   tree diff, iter_init, iter_incr = NULL, last;
4158   tree incr_var = NULL, orig_pre_body, orig_body, c;
4159   tree decl = TREE_VEC_ELT (declv, i);
4160   tree init = TREE_VEC_ELT (initv, i);
4161   tree cond = TREE_VEC_ELT (condv, i);
4162   tree incr = TREE_VEC_ELT (incrv, i);
4163   tree iter = decl;
4164   location_t elocus = locus;
4165
4166   if (init && EXPR_HAS_LOCATION (init))
4167     elocus = EXPR_LOCATION (init);
4168
4169   switch (TREE_CODE (cond))
4170     {
4171     case GT_EXPR:
4172     case GE_EXPR:
4173     case LT_EXPR:
4174     case LE_EXPR:
4175       if (TREE_OPERAND (cond, 1) == iter)
4176         cond = build2 (swap_tree_comparison (TREE_CODE (cond)),
4177                        TREE_TYPE (cond), iter, TREE_OPERAND (cond, 0));
4178       if (TREE_OPERAND (cond, 0) != iter)
4179         cond = error_mark_node;
4180       else
4181         {
4182           tree tem = build_x_binary_op (TREE_CODE (cond), iter, ERROR_MARK,
4183                                         TREE_OPERAND (cond, 1), ERROR_MARK,
4184                                         NULL, tf_warning_or_error);
4185           if (error_operand_p (tem))
4186             return true;
4187         }
4188       break;
4189     default:
4190       cond = error_mark_node;
4191       break;
4192     }
4193   if (cond == error_mark_node)
4194     {
4195       error_at (elocus, "invalid controlling predicate");
4196       return true;
4197     }
4198   diff = build_x_binary_op (MINUS_EXPR, TREE_OPERAND (cond, 1),
4199                             ERROR_MARK, iter, ERROR_MARK, NULL,
4200                             tf_warning_or_error);
4201   if (error_operand_p (diff))
4202     return true;
4203   if (TREE_CODE (TREE_TYPE (diff)) != INTEGER_TYPE)
4204     {
4205       error_at (elocus, "difference between %qE and %qD does not have integer type",
4206                 TREE_OPERAND (cond, 1), iter);
4207       return true;
4208     }
4209
4210   switch (TREE_CODE (incr))
4211     {
4212     case PREINCREMENT_EXPR:
4213     case PREDECREMENT_EXPR:
4214     case POSTINCREMENT_EXPR:
4215     case POSTDECREMENT_EXPR:
4216       if (TREE_OPERAND (incr, 0) != iter)
4217         {
4218           incr = error_mark_node;
4219           break;
4220         }
4221       iter_incr = build_x_unary_op (TREE_CODE (incr), iter,
4222                                     tf_warning_or_error);
4223       if (error_operand_p (iter_incr))
4224         return true;
4225       else if (TREE_CODE (incr) == PREINCREMENT_EXPR
4226                || TREE_CODE (incr) == POSTINCREMENT_EXPR)
4227         incr = integer_one_node;
4228       else
4229         incr = integer_minus_one_node;
4230       break;
4231     case MODIFY_EXPR:
4232       if (TREE_OPERAND (incr, 0) != iter)
4233         incr = error_mark_node;
4234       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
4235                || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
4236         {
4237           tree rhs = TREE_OPERAND (incr, 1);
4238           if (TREE_OPERAND (rhs, 0) == iter)
4239             {
4240               if (TREE_CODE (TREE_TYPE (TREE_OPERAND (rhs, 1)))
4241                   != INTEGER_TYPE)
4242                 incr = error_mark_node;
4243               else
4244                 {
4245                   iter_incr = build_x_modify_expr (iter, TREE_CODE (rhs),
4246                                                    TREE_OPERAND (rhs, 1),
4247                                                    tf_warning_or_error);
4248                   if (error_operand_p (iter_incr))
4249                     return true;
4250                   incr = TREE_OPERAND (rhs, 1);
4251                   incr = cp_convert (TREE_TYPE (diff), incr);
4252                   if (TREE_CODE (rhs) == MINUS_EXPR)
4253                     {
4254                       incr = build1 (NEGATE_EXPR, TREE_TYPE (diff), incr);
4255                       incr = fold_if_not_in_template (incr);
4256                     }
4257                   if (TREE_CODE (incr) != INTEGER_CST
4258                       && (TREE_CODE (incr) != NOP_EXPR
4259                           || (TREE_CODE (TREE_OPERAND (incr, 0))
4260                               != INTEGER_CST)))
4261                     iter_incr = NULL;
4262                 }
4263             }
4264           else if (TREE_OPERAND (rhs, 1) == iter)
4265             {
4266               if (TREE_CODE (TREE_TYPE (TREE_OPERAND (rhs, 0))) != INTEGER_TYPE
4267                   || TREE_CODE (rhs) != PLUS_EXPR)
4268                 incr = error_mark_node;
4269               else
4270                 {
4271                   iter_incr = build_x_binary_op (PLUS_EXPR,
4272                                                  TREE_OPERAND (rhs, 0),
4273                                                  ERROR_MARK, iter,
4274                                                  ERROR_MARK, NULL,
4275                                                  tf_warning_or_error);
4276                   if (error_operand_p (iter_incr))
4277                     return true;
4278                   iter_incr = build_x_modify_expr (iter, NOP_EXPR,
4279                                                    iter_incr,
4280                                                    tf_warning_or_error);
4281                   if (error_operand_p (iter_incr))
4282                     return true;
4283                   incr = TREE_OPERAND (rhs, 0);
4284                   iter_incr = NULL;
4285                 }
4286             }
4287           else
4288             incr = error_mark_node;
4289         }
4290       else
4291         incr = error_mark_node;
4292       break;
4293     default:
4294       incr = error_mark_node;
4295       break;
4296     }
4297
4298   if (incr == error_mark_node)
4299     {
4300       error_at (elocus, "invalid increment expression");
4301       return true;
4302     }
4303
4304   incr = cp_convert (TREE_TYPE (diff), incr);
4305   for (c = clauses; c ; c = OMP_CLAUSE_CHAIN (c))
4306     if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE
4307         && OMP_CLAUSE_DECL (c) == iter)
4308       break;
4309
4310   decl = create_temporary_var (TREE_TYPE (diff));
4311   pushdecl (decl);
4312   add_decl_expr (decl);
4313   last = create_temporary_var (TREE_TYPE (diff));
4314   pushdecl (last);
4315   add_decl_expr (last);
4316   if (c && iter_incr == NULL)
4317     {
4318       incr_var = create_temporary_var (TREE_TYPE (diff));
4319       pushdecl (incr_var);
4320       add_decl_expr (incr_var);
4321     }
4322   gcc_assert (stmts_are_full_exprs_p ());
4323
4324   orig_pre_body = *pre_body;
4325   *pre_body = push_stmt_list ();
4326   if (orig_pre_body)
4327     add_stmt (orig_pre_body);
4328   if (init != NULL)
4329     finish_expr_stmt (build_x_modify_expr (iter, NOP_EXPR, init,
4330                                            tf_warning_or_error));
4331   init = build_int_cst (TREE_TYPE (diff), 0);
4332   if (c && iter_incr == NULL)
4333     {
4334       finish_expr_stmt (build_x_modify_expr (incr_var, NOP_EXPR,
4335                                              incr, tf_warning_or_error));
4336       incr = incr_var;
4337       iter_incr = build_x_modify_expr (iter, PLUS_EXPR, incr,
4338                                        tf_warning_or_error);
4339     }
4340   finish_expr_stmt (build_x_modify_expr (last, NOP_EXPR, init,
4341                                          tf_warning_or_error));
4342   *pre_body = pop_stmt_list (*pre_body);
4343
4344   cond = cp_build_binary_op (elocus,
4345                              TREE_CODE (cond), decl, diff,
4346                              tf_warning_or_error);
4347   incr = build_modify_expr (elocus, decl, NULL_TREE, PLUS_EXPR,
4348                             elocus, incr, NULL_TREE);
4349
4350   orig_body = *body;
4351   *body = push_stmt_list ();
4352   iter_init = build2 (MINUS_EXPR, TREE_TYPE (diff), decl, last);
4353   iter_init = build_x_modify_expr (iter, PLUS_EXPR, iter_init,
4354                                    tf_warning_or_error);
4355   iter_init = build1 (NOP_EXPR, void_type_node, iter_init);
4356   finish_expr_stmt (iter_init);
4357   finish_expr_stmt (build_x_modify_expr (last, NOP_EXPR, decl,
4358                                          tf_warning_or_error));
4359   add_stmt (orig_body);
4360   *body = pop_stmt_list (*body);
4361
4362   if (c)
4363     {
4364       OMP_CLAUSE_LASTPRIVATE_STMT (c) = push_stmt_list ();
4365       finish_expr_stmt (iter_incr);
4366       OMP_CLAUSE_LASTPRIVATE_STMT (c)
4367         = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (c));
4368     }
4369
4370   TREE_VEC_ELT (declv, i) = decl;
4371   TREE_VEC_ELT (initv, i) = init;
4372   TREE_VEC_ELT (condv, i) = cond;
4373   TREE_VEC_ELT (incrv, i) = incr;
4374
4375   return false;
4376 }
4377
4378 /* Build and validate an OMP_FOR statement.  CLAUSES, BODY, COND, INCR
4379    are directly for their associated operands in the statement.  DECL
4380    and INIT are a combo; if DECL is NULL then INIT ought to be a
4381    MODIFY_EXPR, and the DECL should be extracted.  PRE_BODY are
4382    optional statements that need to go before the loop into its
4383    sk_omp scope.  */
4384
4385 tree
4386 finish_omp_for (location_t locus, tree declv, tree initv, tree condv,
4387                 tree incrv, tree body, tree pre_body, tree clauses)
4388 {
4389   tree omp_for = NULL, orig_incr = NULL;
4390   tree decl, init, cond, incr;
4391   location_t elocus;
4392   int i;
4393
4394   gcc_assert (TREE_VEC_LENGTH (declv) == TREE_VEC_LENGTH (initv));
4395   gcc_assert (TREE_VEC_LENGTH (declv) == TREE_VEC_LENGTH (condv));
4396   gcc_assert (TREE_VEC_LENGTH (declv) == TREE_VEC_LENGTH (incrv));
4397   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
4398     {
4399       decl = TREE_VEC_ELT (declv, i);
4400       init = TREE_VEC_ELT (initv, i);
4401       cond = TREE_VEC_ELT (condv, i);
4402       incr = TREE_VEC_ELT (incrv, i);
4403       elocus = locus;
4404
4405       if (decl == NULL)
4406         {
4407           if (init != NULL)
4408             switch (TREE_CODE (init))
4409               {
4410               case MODIFY_EXPR:
4411                 decl = TREE_OPERAND (init, 0);
4412                 init = TREE_OPERAND (init, 1);
4413                 break;
4414               case MODOP_EXPR:
4415                 if (TREE_CODE (TREE_OPERAND (init, 1)) == NOP_EXPR)
4416                   {
4417                     decl = TREE_OPERAND (init, 0);
4418                     init = TREE_OPERAND (init, 2);
4419                   }
4420                 break;
4421               default:
4422                 break;
4423               }
4424
4425           if (decl == NULL)
4426             {
4427               error_at (locus,
4428                         "expected iteration declaration or initialization");
4429               return NULL;
4430             }
4431         }
4432
4433       if (init && EXPR_HAS_LOCATION (init))
4434         elocus = EXPR_LOCATION (init);
4435
4436       if (cond == NULL)
4437         {
4438           error_at (elocus, "missing controlling predicate");
4439           return NULL;
4440         }
4441
4442       if (incr == NULL)
4443         {
4444           error_at (elocus, "missing increment expression");
4445           return NULL;
4446         }
4447
4448       TREE_VEC_ELT (declv, i) = decl;
4449       TREE_VEC_ELT (initv, i) = init;
4450     }
4451
4452   if (dependent_omp_for_p (declv, initv, condv, incrv))
4453     {
4454       tree stmt;
4455
4456       stmt = make_node (OMP_FOR);
4457
4458       for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
4459         {
4460           /* This is really just a place-holder.  We'll be decomposing this
4461              again and going through the cp_build_modify_expr path below when
4462              we instantiate the thing.  */
4463           TREE_VEC_ELT (initv, i)
4464             = build2 (MODIFY_EXPR, void_type_node, TREE_VEC_ELT (declv, i),
4465                       TREE_VEC_ELT (initv, i));
4466         }
4467
4468       TREE_TYPE (stmt) = void_type_node;
4469       OMP_FOR_INIT (stmt) = initv;
4470       OMP_FOR_COND (stmt) = condv;
4471       OMP_FOR_INCR (stmt) = incrv;
4472       OMP_FOR_BODY (stmt) = body;
4473       OMP_FOR_PRE_BODY (stmt) = pre_body;
4474       OMP_FOR_CLAUSES (stmt) = clauses;
4475
4476       SET_EXPR_LOCATION (stmt, locus);
4477       return add_stmt (stmt);
4478     }
4479
4480   if (processing_template_decl)
4481     orig_incr = make_tree_vec (TREE_VEC_LENGTH (incrv));
4482
4483   for (i = 0; i < TREE_VEC_LENGTH (declv); )
4484     {
4485       decl = TREE_VEC_ELT (declv, i);
4486       init = TREE_VEC_ELT (initv, i);
4487       cond = TREE_VEC_ELT (condv, i);
4488       incr = TREE_VEC_ELT (incrv, i);
4489       if (orig_incr)
4490         TREE_VEC_ELT (orig_incr, i) = incr;
4491       elocus = locus;
4492
4493       if (init && EXPR_HAS_LOCATION (init))
4494         elocus = EXPR_LOCATION (init);
4495
4496       if (!DECL_P (decl))
4497         {
4498           error_at (elocus, "expected iteration declaration or initialization");
4499           return NULL;
4500         }
4501
4502       if (incr && TREE_CODE (incr) == MODOP_EXPR)
4503         {
4504           if (orig_incr)
4505             TREE_VEC_ELT (orig_incr, i) = incr;
4506           incr = cp_build_modify_expr (TREE_OPERAND (incr, 0),
4507                                        TREE_CODE (TREE_OPERAND (incr, 1)),
4508                                        TREE_OPERAND (incr, 2),
4509                                        tf_warning_or_error);
4510         }
4511
4512       if (CLASS_TYPE_P (TREE_TYPE (decl)))
4513         {
4514           if (handle_omp_for_class_iterator (i, locus, declv, initv, condv,
4515                                              incrv, &body, &pre_body, clauses))
4516             return NULL;
4517           continue;
4518         }
4519
4520       if (!INTEGRAL_TYPE_P (TREE_TYPE (decl))
4521           && TREE_CODE (TREE_TYPE (decl)) != POINTER_TYPE)
4522         {
4523           error_at (elocus, "invalid type for iteration variable %qE", decl);
4524           return NULL;
4525         }
4526
4527       if (!processing_template_decl)
4528         {
4529           init = fold_build_cleanup_point_expr (TREE_TYPE (init), init);
4530           init = cp_build_modify_expr (decl, NOP_EXPR, init, tf_warning_or_error);
4531         }
4532       else
4533         init = build2 (MODIFY_EXPR, void_type_node, decl, init);
4534       if (cond
4535           && TREE_SIDE_EFFECTS (cond)
4536           && COMPARISON_CLASS_P (cond)
4537           && !processing_template_decl)
4538         {
4539           tree t = TREE_OPERAND (cond, 0);
4540           if (TREE_SIDE_EFFECTS (t)
4541               && t != decl
4542               && (TREE_CODE (t) != NOP_EXPR
4543                   || TREE_OPERAND (t, 0) != decl))
4544             TREE_OPERAND (cond, 0)
4545               = fold_build_cleanup_point_expr (TREE_TYPE (t), t);
4546
4547           t = TREE_OPERAND (cond, 1);
4548           if (TREE_SIDE_EFFECTS (t)
4549               && t != decl
4550               && (TREE_CODE (t) != NOP_EXPR
4551                   || TREE_OPERAND (t, 0) != decl))
4552             TREE_OPERAND (cond, 1)
4553               = fold_build_cleanup_point_expr (TREE_TYPE (t), t);
4554         }
4555       if (decl == error_mark_node || init == error_mark_node)
4556         return NULL;
4557
4558       TREE_VEC_ELT (declv, i) = decl;
4559       TREE_VEC_ELT (initv, i) = init;
4560       TREE_VEC_ELT (condv, i) = cond;
4561       TREE_VEC_ELT (incrv, i) = incr;
4562       i++;
4563     }
4564
4565   if (IS_EMPTY_STMT (pre_body))
4566     pre_body = NULL;
4567
4568   omp_for = c_finish_omp_for (locus, declv, initv, condv, incrv,
4569                               body, pre_body);
4570
4571   if (omp_for == NULL)
4572     return NULL;
4573
4574   for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INCR (omp_for)); i++)
4575     {
4576       decl = TREE_OPERAND (TREE_VEC_ELT (OMP_FOR_INIT (omp_for), i), 0);
4577       incr = TREE_VEC_ELT (OMP_FOR_INCR (omp_for), i);
4578
4579       if (TREE_CODE (incr) != MODIFY_EXPR)
4580         continue;
4581
4582       if (TREE_SIDE_EFFECTS (TREE_OPERAND (incr, 1))
4583           && BINARY_CLASS_P (TREE_OPERAND (incr, 1))
4584           && !processing_template_decl)
4585         {
4586           tree t = TREE_OPERAND (TREE_OPERAND (incr, 1), 0);
4587           if (TREE_SIDE_EFFECTS (t)
4588               && t != decl
4589               && (TREE_CODE (t) != NOP_EXPR
4590                   || TREE_OPERAND (t, 0) != decl))
4591             TREE_OPERAND (TREE_OPERAND (incr, 1), 0)
4592               = fold_build_cleanup_point_expr (TREE_TYPE (t), t);
4593
4594           t = TREE_OPERAND (TREE_OPERAND (incr, 1), 1);
4595           if (TREE_SIDE_EFFECTS (t)
4596               && t != decl
4597               && (TREE_CODE (t) != NOP_EXPR
4598                   || TREE_OPERAND (t, 0) != decl))
4599             TREE_OPERAND (TREE_OPERAND (incr, 1), 1)
4600               = fold_build_cleanup_point_expr (TREE_TYPE (t), t);
4601         }
4602
4603       if (orig_incr)
4604         TREE_VEC_ELT (OMP_FOR_INCR (omp_for), i) = TREE_VEC_ELT (orig_incr, i);
4605     }
4606   if (omp_for != NULL)
4607     OMP_FOR_CLAUSES (omp_for) = clauses;
4608   return omp_for;
4609 }
4610
4611 void
4612 finish_omp_atomic (enum tree_code code, tree lhs, tree rhs)
4613 {
4614   tree orig_lhs;
4615   tree orig_rhs;
4616   bool dependent_p;
4617   tree stmt;
4618
4619   orig_lhs = lhs;
4620   orig_rhs = rhs;
4621   dependent_p = false;
4622   stmt = NULL_TREE;
4623
4624   /* Even in a template, we can detect invalid uses of the atomic
4625      pragma if neither LHS nor RHS is type-dependent.  */
4626   if (processing_template_decl)
4627     {
4628       dependent_p = (type_dependent_expression_p (lhs)
4629                      || type_dependent_expression_p (rhs));
4630       if (!dependent_p)
4631         {
4632           lhs = build_non_dependent_expr (lhs);
4633           rhs = build_non_dependent_expr (rhs);
4634         }
4635     }
4636   if (!dependent_p)
4637     {
4638       stmt = c_finish_omp_atomic (input_location, code, lhs, rhs);
4639       if (stmt == error_mark_node)
4640         return;
4641     }
4642   if (processing_template_decl)
4643     stmt = build2 (OMP_ATOMIC, void_type_node, integer_zero_node,
4644                    build2 (code, void_type_node, orig_lhs, orig_rhs));
4645   add_stmt (stmt);
4646 }
4647
4648 void
4649 finish_omp_barrier (void)
4650 {
4651   tree fn = built_in_decls[BUILT_IN_GOMP_BARRIER];
4652   VEC(tree,gc) *vec = make_tree_vector ();
4653   tree stmt = finish_call_expr (fn, &vec, false, false, tf_warning_or_error);
4654   release_tree_vector (vec);
4655   finish_expr_stmt (stmt);
4656 }
4657
4658 void
4659 finish_omp_flush (void)
4660 {
4661   tree fn = built_in_decls[BUILT_IN_SYNCHRONIZE];
4662   VEC(tree,gc) *vec = make_tree_vector ();
4663   tree stmt = finish_call_expr (fn, &vec, false, false, tf_warning_or_error);
4664   release_tree_vector (vec);
4665   finish_expr_stmt (stmt);
4666 }
4667
4668 void
4669 finish_omp_taskwait (void)
4670 {
4671   tree fn = built_in_decls[BUILT_IN_GOMP_TASKWAIT];
4672   VEC(tree,gc) *vec = make_tree_vector ();
4673   tree stmt = finish_call_expr (fn, &vec, false, false, tf_warning_or_error);
4674   release_tree_vector (vec);
4675   finish_expr_stmt (stmt);
4676 }
4677 \f
4678 void
4679 init_cp_semantics (void)
4680 {
4681 }
4682 \f
4683 /* Build a STATIC_ASSERT for a static assertion with the condition
4684    CONDITION and the message text MESSAGE.  LOCATION is the location
4685    of the static assertion in the source code.  When MEMBER_P, this
4686    static assertion is a member of a class.  */
4687 void 
4688 finish_static_assert (tree condition, tree message, location_t location, 
4689                       bool member_p)
4690 {
4691   if (check_for_bare_parameter_packs (condition))
4692     condition = error_mark_node;
4693
4694   if (type_dependent_expression_p (condition) 
4695       || value_dependent_expression_p (condition))
4696     {
4697       /* We're in a template; build a STATIC_ASSERT and put it in
4698          the right place. */
4699       tree assertion;
4700
4701       assertion = make_node (STATIC_ASSERT);
4702       STATIC_ASSERT_CONDITION (assertion) = condition;
4703       STATIC_ASSERT_MESSAGE (assertion) = message;
4704       STATIC_ASSERT_SOURCE_LOCATION (assertion) = location;
4705
4706       if (member_p)
4707         maybe_add_class_template_decl_list (current_class_type, 
4708                                             assertion,
4709                                             /*friend_p=*/0);
4710       else
4711         add_stmt (assertion);
4712
4713       return;
4714     }
4715
4716   /* Fold the expression and convert it to a boolean value. */
4717   condition = fold_non_dependent_expr (condition);
4718   condition = cp_convert (boolean_type_node, condition);
4719   condition = maybe_constant_value (condition);
4720
4721   if (TREE_CODE (condition) == INTEGER_CST && !integer_zerop (condition))
4722     /* Do nothing; the condition is satisfied. */
4723     ;
4724   else 
4725     {
4726       location_t saved_loc = input_location;
4727
4728       input_location = location;
4729       if (TREE_CODE (condition) == INTEGER_CST 
4730           && integer_zerop (condition))
4731         /* Report the error. */
4732         error ("static assertion failed: %E", message);
4733       else if (condition && condition != error_mark_node)
4734         {
4735           error ("non-constant condition for static assertion");
4736           cxx_constant_value (condition);
4737         }
4738       input_location = saved_loc;
4739     }
4740 }
4741 \f
4742 /* Returns the type of EXPR for cases where we can determine it even though
4743    EXPR is a type-dependent expression.  */
4744
4745 tree
4746 describable_type (tree expr)
4747 {
4748   tree type = NULL_TREE;
4749
4750   if (! type_dependent_expression_p (expr)
4751       && ! type_unknown_p (expr))
4752     {
4753       type = unlowered_expr_type (expr);
4754       if (real_lvalue_p (expr))
4755         type = build_reference_type (type);
4756     }
4757
4758   if (type)
4759     return type;
4760
4761   switch (TREE_CODE (expr))
4762     {
4763     case VAR_DECL:
4764     case PARM_DECL:
4765     case RESULT_DECL:
4766     case FUNCTION_DECL:
4767       return TREE_TYPE (expr);
4768       break;
4769
4770     case NEW_EXPR:
4771     case CONST_DECL:
4772     case TEMPLATE_PARM_INDEX:
4773     case CAST_EXPR:
4774     case STATIC_CAST_EXPR:
4775     case REINTERPRET_CAST_EXPR:
4776     case CONST_CAST_EXPR:
4777     case DYNAMIC_CAST_EXPR:
4778       type = TREE_TYPE (expr);
4779       break;
4780
4781     case INDIRECT_REF:
4782       {
4783         tree ptrtype = describable_type (TREE_OPERAND (expr, 0));
4784         if (ptrtype && POINTER_TYPE_P (ptrtype))
4785           type = build_reference_type (TREE_TYPE (ptrtype));
4786       }
4787       break;
4788
4789     default:
4790       if (TREE_CODE_CLASS (TREE_CODE (expr)) == tcc_constant)
4791         type = TREE_TYPE (expr);
4792       break;
4793     }
4794
4795   if (type && type_uses_auto (type))
4796     return NULL_TREE;
4797   else
4798     return type;
4799 }
4800
4801 /* Implements the C++0x decltype keyword. Returns the type of EXPR,
4802    suitable for use as a type-specifier.
4803
4804    ID_EXPRESSION_OR_MEMBER_ACCESS_P is true when EXPR was parsed as an
4805    id-expression or a class member access, FALSE when it was parsed as
4806    a full expression.  */
4807
4808 tree
4809 finish_decltype_type (tree expr, bool id_expression_or_member_access_p,
4810                       tsubst_flags_t complain)
4811 {
4812   tree type = NULL_TREE;
4813
4814   if (!expr || error_operand_p (expr))
4815     return error_mark_node;
4816
4817   if (TYPE_P (expr)
4818       || TREE_CODE (expr) == TYPE_DECL
4819       || (TREE_CODE (expr) == BIT_NOT_EXPR
4820           && TYPE_P (TREE_OPERAND (expr, 0))))
4821     {
4822       if (complain & tf_error)
4823         error ("argument to decltype must be an expression");
4824       return error_mark_node;
4825     }
4826
4827   /* FIXME instantiation-dependent  */
4828   if (type_dependent_expression_p (expr)
4829       /* In a template, a COMPONENT_REF has an IDENTIFIER_NODE for op1 even
4830          if it isn't dependent, so that we can check access control at
4831          instantiation time, so defer the decltype as well (PR 42277).  */
4832       || (id_expression_or_member_access_p
4833           && processing_template_decl
4834           && TREE_CODE (expr) == COMPONENT_REF))
4835     {
4836       type = cxx_make_type (DECLTYPE_TYPE);
4837       DECLTYPE_TYPE_EXPR (type) = expr;
4838       DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (type)
4839         = id_expression_or_member_access_p;
4840       SET_TYPE_STRUCTURAL_EQUALITY (type);
4841
4842       return type;
4843     }
4844
4845   /* The type denoted by decltype(e) is defined as follows:  */
4846
4847   expr = resolve_nondeduced_context (expr);
4848
4849   if (type_unknown_p (expr))
4850     {
4851       if (complain & tf_error)
4852         error ("decltype cannot resolve address of overloaded function");
4853       return error_mark_node;
4854     }
4855
4856   /* To get the size of a static data member declared as an array of
4857      unknown bound, we need to instantiate it.  */
4858   if (TREE_CODE (expr) == VAR_DECL
4859       && VAR_HAD_UNKNOWN_BOUND (expr)
4860       && DECL_TEMPLATE_INSTANTIATION (expr))
4861     instantiate_decl (expr, /*defer_ok*/true, /*expl_inst_mem*/false);
4862
4863   if (id_expression_or_member_access_p)
4864     {
4865       /* If e is an id-expression or a class member access (5.2.5
4866          [expr.ref]), decltype(e) is defined as the type of the entity
4867          named by e. If there is no such entity, or e names a set of
4868          overloaded functions, the program is ill-formed.  */
4869       if (TREE_CODE (expr) == IDENTIFIER_NODE)
4870         expr = lookup_name (expr);
4871
4872       if (TREE_CODE (expr) == INDIRECT_REF)
4873         /* This can happen when the expression is, e.g., "a.b". Just
4874            look at the underlying operand.  */
4875         expr = TREE_OPERAND (expr, 0);
4876
4877       if (TREE_CODE (expr) == OFFSET_REF
4878           || TREE_CODE (expr) == MEMBER_REF)
4879         /* We're only interested in the field itself. If it is a
4880            BASELINK, we will need to see through it in the next
4881            step.  */
4882         expr = TREE_OPERAND (expr, 1);
4883
4884       if (TREE_CODE (expr) == BASELINK)
4885         /* See through BASELINK nodes to the underlying function.  */
4886         expr = BASELINK_FUNCTIONS (expr);
4887
4888       switch (TREE_CODE (expr))
4889         {
4890         case FIELD_DECL:
4891           if (DECL_BIT_FIELD_TYPE (expr))
4892             {
4893               type = DECL_BIT_FIELD_TYPE (expr);
4894               break;
4895             }
4896           /* Fall through for fields that aren't bitfields.  */
4897
4898         case FUNCTION_DECL:
4899         case VAR_DECL:
4900         case CONST_DECL:
4901         case PARM_DECL:
4902         case RESULT_DECL:
4903         case TEMPLATE_PARM_INDEX:
4904           expr = mark_type_use (expr);
4905           type = TREE_TYPE (expr);
4906           break;
4907
4908         case ERROR_MARK:
4909           type = error_mark_node;
4910           break;
4911
4912         case COMPONENT_REF:
4913           mark_type_use (expr);
4914           type = is_bitfield_expr_with_lowered_type (expr);
4915           if (!type)
4916             type = TREE_TYPE (TREE_OPERAND (expr, 1));
4917           break;
4918
4919         case BIT_FIELD_REF:
4920           gcc_unreachable ();
4921
4922         case INTEGER_CST:
4923           /* We can get here when the id-expression refers to an
4924              enumerator.  */
4925           type = TREE_TYPE (expr);
4926           break;
4927
4928         default:
4929           gcc_unreachable ();
4930           return error_mark_node;
4931         }
4932     }
4933   else
4934     {
4935       /* Within a lambda-expression:
4936
4937          Every occurrence of decltype((x)) where x is a possibly
4938          parenthesized id-expression that names an entity of
4939          automatic storage duration is treated as if x were
4940          transformed into an access to a corresponding data member
4941          of the closure type that would have been declared if x
4942          were a use of the denoted entity.  */
4943       if (outer_automatic_var_p (expr)
4944           && current_function_decl
4945           && LAMBDA_FUNCTION_P (current_function_decl))
4946         type = capture_decltype (expr);
4947       else if (error_operand_p (expr))
4948         type = error_mark_node;
4949       else if (expr == current_class_ptr)
4950         /* If the expression is just "this", we want the
4951            cv-unqualified pointer for the "this" type.  */
4952         type = TYPE_MAIN_VARIANT (TREE_TYPE (expr));
4953       else
4954         {
4955           /* Otherwise, where T is the type of e, if e is an lvalue,
4956              decltype(e) is defined as T&; if an xvalue, T&&; otherwise, T. */
4957           cp_lvalue_kind clk = lvalue_kind (expr);
4958           type = unlowered_expr_type (expr);
4959           gcc_assert (TREE_CODE (type) != REFERENCE_TYPE);
4960           if (clk != clk_none && !(clk & clk_class))
4961             type = cp_build_reference_type (type, (clk & clk_rvalueref));
4962         }
4963     }
4964
4965   return type;
4966 }
4967
4968 /* Called from trait_expr_value to evaluate either __has_nothrow_assign or 
4969    __has_nothrow_copy, depending on assign_p.  */
4970
4971 static bool
4972 classtype_has_nothrow_assign_or_copy_p (tree type, bool assign_p)
4973 {
4974   tree fns;
4975
4976   if (assign_p)
4977     {
4978       int ix;
4979       ix = lookup_fnfields_1 (type, ansi_assopname (NOP_EXPR));
4980       if (ix < 0)
4981         return false;
4982       fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (type), ix);
4983     } 
4984   else if (TYPE_HAS_COPY_CTOR (type))
4985     {
4986       /* If construction of the copy constructor was postponed, create
4987          it now.  */
4988       if (CLASSTYPE_LAZY_COPY_CTOR (type))
4989         lazily_declare_fn (sfk_copy_constructor, type);
4990       if (CLASSTYPE_LAZY_MOVE_CTOR (type))
4991         lazily_declare_fn (sfk_move_constructor, type);
4992       fns = CLASSTYPE_CONSTRUCTORS (type);
4993     }
4994   else
4995     return false;
4996
4997   for (; fns; fns = OVL_NEXT (fns))
4998     {
4999       tree fn = OVL_CURRENT (fns);
5000  
5001       if (assign_p)
5002         {
5003           if (copy_fn_p (fn) == 0)
5004             continue;
5005         }
5006       else if (copy_fn_p (fn) <= 0)
5007         continue;
5008
5009       if (!TYPE_NOTHROW_P (TREE_TYPE (fn)))
5010         return false;
5011     }
5012
5013   return true;
5014 }
5015
5016 /* Actually evaluates the trait.  */
5017
5018 static bool
5019 trait_expr_value (cp_trait_kind kind, tree type1, tree type2)
5020 {
5021   enum tree_code type_code1;
5022   tree t;
5023
5024   type_code1 = TREE_CODE (type1);
5025
5026   switch (kind)
5027     {
5028     case CPTK_HAS_NOTHROW_ASSIGN:
5029       type1 = strip_array_types (type1);
5030       return (!CP_TYPE_CONST_P (type1) && type_code1 != REFERENCE_TYPE
5031               && (trait_expr_value (CPTK_HAS_TRIVIAL_ASSIGN, type1, type2)
5032                   || (CLASS_TYPE_P (type1)
5033                       && classtype_has_nothrow_assign_or_copy_p (type1,
5034                                                                  true))));
5035
5036     case CPTK_HAS_TRIVIAL_ASSIGN:
5037       /* ??? The standard seems to be missing the "or array of such a class
5038          type" wording for this trait.  */
5039       type1 = strip_array_types (type1);
5040       return (!CP_TYPE_CONST_P (type1) && type_code1 != REFERENCE_TYPE
5041               && (trivial_type_p (type1)
5042                     || (CLASS_TYPE_P (type1)
5043                         && TYPE_HAS_TRIVIAL_COPY_ASSIGN (type1))));
5044
5045     case CPTK_HAS_NOTHROW_CONSTRUCTOR:
5046       type1 = strip_array_types (type1);
5047       return (trait_expr_value (CPTK_HAS_TRIVIAL_CONSTRUCTOR, type1, type2) 
5048               || (CLASS_TYPE_P (type1)
5049                   && (t = locate_ctor (type1))
5050                   && TYPE_NOTHROW_P (TREE_TYPE (t))));
5051
5052     case CPTK_HAS_TRIVIAL_CONSTRUCTOR:
5053       type1 = strip_array_types (type1);
5054       return (trivial_type_p (type1)
5055               || (CLASS_TYPE_P (type1) && TYPE_HAS_TRIVIAL_DFLT (type1)));
5056
5057     case CPTK_HAS_NOTHROW_COPY:
5058       type1 = strip_array_types (type1);
5059       return (trait_expr_value (CPTK_HAS_TRIVIAL_COPY, type1, type2)
5060               || (CLASS_TYPE_P (type1)
5061                   && classtype_has_nothrow_assign_or_copy_p (type1, false)));
5062
5063     case CPTK_HAS_TRIVIAL_COPY:
5064       /* ??? The standard seems to be missing the "or array of such a class
5065          type" wording for this trait.  */
5066       type1 = strip_array_types (type1);
5067       return (trivial_type_p (type1) || type_code1 == REFERENCE_TYPE
5068               || (CLASS_TYPE_P (type1) && TYPE_HAS_TRIVIAL_COPY_CTOR (type1)));
5069
5070     case CPTK_HAS_TRIVIAL_DESTRUCTOR:
5071       type1 = strip_array_types (type1);
5072       return (trivial_type_p (type1) || type_code1 == REFERENCE_TYPE
5073               || (CLASS_TYPE_P (type1)
5074                   && TYPE_HAS_TRIVIAL_DESTRUCTOR (type1)));
5075
5076     case CPTK_HAS_VIRTUAL_DESTRUCTOR:
5077       return type_has_virtual_destructor (type1);
5078
5079     case CPTK_IS_ABSTRACT:
5080       return (CLASS_TYPE_P (type1) && CLASSTYPE_PURE_VIRTUALS (type1));
5081
5082     case CPTK_IS_BASE_OF:
5083       return (NON_UNION_CLASS_TYPE_P (type1) && NON_UNION_CLASS_TYPE_P (type2)
5084               && DERIVED_FROM_P (type1, type2));
5085
5086     case CPTK_IS_CLASS:
5087       return (NON_UNION_CLASS_TYPE_P (type1));
5088
5089     case CPTK_IS_CONVERTIBLE_TO:
5090       /* TODO  */
5091       return false;
5092
5093     case CPTK_IS_EMPTY:
5094       return (NON_UNION_CLASS_TYPE_P (type1) && CLASSTYPE_EMPTY_P (type1));
5095
5096     case CPTK_IS_ENUM:
5097       return (type_code1 == ENUMERAL_TYPE);
5098
5099     case CPTK_IS_POD:
5100       return (pod_type_p (type1));
5101
5102     case CPTK_IS_POLYMORPHIC:
5103       return (CLASS_TYPE_P (type1) && TYPE_POLYMORPHIC_P (type1));
5104
5105     case CPTK_IS_STD_LAYOUT:
5106       return (std_layout_type_p (type1));
5107
5108     case CPTK_IS_TRIVIAL:
5109       return (trivial_type_p (type1));
5110
5111     case CPTK_IS_UNION:
5112       return (type_code1 == UNION_TYPE);
5113
5114     case CPTK_IS_LITERAL_TYPE:
5115       return (literal_type_p (type1));
5116
5117     default:
5118       gcc_unreachable ();
5119       return false;
5120     }
5121 }
5122
5123 /* Returns true if TYPE is a complete type, an array of unknown bound,
5124    or (possibly cv-qualified) void, returns false otherwise.  */
5125
5126 static bool
5127 check_trait_type (tree type)
5128 {
5129   if (COMPLETE_TYPE_P (type))
5130     return true;
5131
5132   if (TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type)
5133       && COMPLETE_TYPE_P (TREE_TYPE (type)))
5134     return true;
5135
5136   if (VOID_TYPE_P (type))
5137     return true;
5138
5139   return false;
5140 }
5141
5142 /* Process a trait expression.  */
5143
5144 tree
5145 finish_trait_expr (cp_trait_kind kind, tree type1, tree type2)
5146 {
5147   gcc_assert (kind == CPTK_HAS_NOTHROW_ASSIGN
5148               || kind == CPTK_HAS_NOTHROW_CONSTRUCTOR
5149               || kind == CPTK_HAS_NOTHROW_COPY
5150               || kind == CPTK_HAS_TRIVIAL_ASSIGN
5151               || kind == CPTK_HAS_TRIVIAL_CONSTRUCTOR
5152               || kind == CPTK_HAS_TRIVIAL_COPY
5153               || kind == CPTK_HAS_TRIVIAL_DESTRUCTOR
5154               || kind == CPTK_HAS_VIRTUAL_DESTRUCTOR          
5155               || kind == CPTK_IS_ABSTRACT
5156               || kind == CPTK_IS_BASE_OF
5157               || kind == CPTK_IS_CLASS
5158               || kind == CPTK_IS_CONVERTIBLE_TO
5159               || kind == CPTK_IS_EMPTY
5160               || kind == CPTK_IS_ENUM
5161               || kind == CPTK_IS_POD
5162               || kind == CPTK_IS_POLYMORPHIC
5163               || kind == CPTK_IS_STD_LAYOUT
5164               || kind == CPTK_IS_TRIVIAL
5165               || kind == CPTK_IS_LITERAL_TYPE
5166               || kind == CPTK_IS_UNION);
5167
5168   if (kind == CPTK_IS_CONVERTIBLE_TO)
5169     {
5170       sorry ("__is_convertible_to");
5171       return error_mark_node;
5172     }
5173
5174   if (type1 == error_mark_node
5175       || ((kind == CPTK_IS_BASE_OF || kind == CPTK_IS_CONVERTIBLE_TO)
5176           && type2 == error_mark_node))
5177     return error_mark_node;
5178
5179   if (processing_template_decl)
5180     {
5181       tree trait_expr = make_node (TRAIT_EXPR);
5182       TREE_TYPE (trait_expr) = boolean_type_node;
5183       TRAIT_EXPR_TYPE1 (trait_expr) = type1;
5184       TRAIT_EXPR_TYPE2 (trait_expr) = type2;
5185       TRAIT_EXPR_KIND (trait_expr) = kind;
5186       return trait_expr;
5187     }
5188
5189   complete_type (type1);
5190   if (type2)
5191     complete_type (type2);
5192
5193   switch (kind)
5194     {
5195     case CPTK_HAS_NOTHROW_ASSIGN:
5196     case CPTK_HAS_TRIVIAL_ASSIGN:
5197     case CPTK_HAS_NOTHROW_CONSTRUCTOR:
5198     case CPTK_HAS_TRIVIAL_CONSTRUCTOR:
5199     case CPTK_HAS_NOTHROW_COPY:
5200     case CPTK_HAS_TRIVIAL_COPY:
5201     case CPTK_HAS_TRIVIAL_DESTRUCTOR:
5202     case CPTK_HAS_VIRTUAL_DESTRUCTOR:
5203     case CPTK_IS_ABSTRACT:
5204     case CPTK_IS_EMPTY:
5205     case CPTK_IS_POD:
5206     case CPTK_IS_POLYMORPHIC:
5207     case CPTK_IS_STD_LAYOUT:
5208     case CPTK_IS_TRIVIAL:
5209     case CPTK_IS_LITERAL_TYPE:
5210       if (!check_trait_type (type1))
5211         {
5212           error ("incomplete type %qT not allowed", type1);
5213           return error_mark_node;
5214         }
5215       break;
5216
5217     case CPTK_IS_BASE_OF:
5218       if (NON_UNION_CLASS_TYPE_P (type1) && NON_UNION_CLASS_TYPE_P (type2)
5219           && !same_type_ignoring_top_level_qualifiers_p (type1, type2)
5220           && !COMPLETE_TYPE_P (type2))
5221         {
5222           error ("incomplete type %qT not allowed", type2);
5223           return error_mark_node;
5224         }
5225       break;
5226
5227     case CPTK_IS_CLASS:
5228     case CPTK_IS_ENUM:
5229     case CPTK_IS_UNION:
5230       break;
5231     
5232     case CPTK_IS_CONVERTIBLE_TO:
5233     default:
5234       gcc_unreachable ();
5235     }
5236
5237   return (trait_expr_value (kind, type1, type2)
5238           ? boolean_true_node : boolean_false_node);
5239 }
5240
5241 /* Do-nothing variants of functions to handle pragma FLOAT_CONST_DECIMAL64,
5242    which is ignored for C++.  */
5243
5244 void
5245 set_float_const_decimal64 (void)
5246 {
5247 }
5248
5249 void
5250 clear_float_const_decimal64 (void)
5251 {
5252 }
5253
5254 bool
5255 float_const_decimal64_p (void)
5256 {
5257   return 0;
5258 }
5259
5260 \f
5261 /* Return true if T is a literal type.   */
5262
5263 bool
5264 literal_type_p (tree t)
5265 {
5266   if (SCALAR_TYPE_P (t))
5267     return true;
5268   if (CLASS_TYPE_P (t))
5269     return CLASSTYPE_LITERAL_P (t);
5270   if (TREE_CODE (t) == ARRAY_TYPE)
5271     return literal_type_p (strip_array_types (t));
5272   return false;
5273 }
5274
5275 /* If DECL is a variable declared `constexpr', require its type
5276    be literal.  Return the DECL if OK, otherwise NULL.  */
5277
5278 tree
5279 ensure_literal_type_for_constexpr_object (tree decl)
5280 {
5281   tree type = TREE_TYPE (decl);
5282   if (TREE_CODE (decl) == VAR_DECL && DECL_DECLARED_CONSTEXPR_P (decl)
5283       && !processing_template_decl
5284       /* The call to complete_type is just for initializer_list.  */
5285       && !literal_type_p (complete_type (type)))
5286     {
5287       error ("the type %qT of constexpr variable %qD is not literal",
5288              type, decl);
5289       return NULL;
5290     }
5291   return decl;
5292 }
5293
5294 /* Representation of entries in the constexpr function definition table.  */
5295
5296 typedef struct GTY(()) constexpr_fundef {
5297   tree decl;
5298   tree body;
5299 } constexpr_fundef;
5300
5301 /* This table holds all constexpr function definitions seen in
5302    the current translation unit.  */
5303
5304 static GTY ((param_is (constexpr_fundef))) htab_t constexpr_fundef_table;
5305
5306 /* Utility function used for managing the constexpr function table.
5307    Return true if the entries pointed to by P and Q are for the
5308    same constexpr function.  */
5309
5310 static inline int
5311 constexpr_fundef_equal (const void *p, const void *q)
5312 {
5313   const constexpr_fundef *lhs = (const constexpr_fundef *) p;
5314   const constexpr_fundef *rhs = (const constexpr_fundef *) q;
5315   return lhs->decl == rhs->decl;
5316 }
5317
5318 /* Utility function used for managing the constexpr function table.
5319    Return a hash value for the entry pointed to by Q.  */
5320
5321 static inline hashval_t
5322 constexpr_fundef_hash (const void *p)
5323 {
5324   const constexpr_fundef *fundef = (const constexpr_fundef *) p;
5325   return DECL_UID (fundef->decl);
5326 }
5327
5328 /* Return a previously saved definition of function FUN.   */
5329
5330 static constexpr_fundef *
5331 retrieve_constexpr_fundef (tree fun)
5332 {
5333   constexpr_fundef fundef = { NULL, NULL };
5334   if (constexpr_fundef_table == NULL)
5335     return NULL;
5336
5337   fundef.decl = fun;
5338   return (constexpr_fundef *) htab_find (constexpr_fundef_table, &fundef);
5339 }
5340
5341 /* Return true if type expression T is a valid parameter type, or
5342    a valid return type, of a constexpr function.  */
5343
5344 static bool
5345 valid_type_in_constexpr_fundecl_p (tree t)
5346 {
5347   return (literal_type_p (t)
5348           /* FIXME we allow ref to non-literal; should change standard to
5349              match, or change back if not.  */
5350           || TREE_CODE (t) == REFERENCE_TYPE);
5351 }
5352
5353 /* Check whether the parameter and return types of FUN are valid for a
5354    constexpr function, and complain if COMPLAIN.  */
5355
5356 static bool
5357 is_valid_constexpr_fn (tree fun, bool complain)
5358 {
5359   tree parm = FUNCTION_FIRST_USER_PARM (fun);
5360   bool ret = true;
5361   for (; parm != NULL; parm = TREE_CHAIN (parm))
5362     if (!valid_type_in_constexpr_fundecl_p (TREE_TYPE (parm)))
5363       {
5364         ret = false;
5365         if (complain)
5366           error ("invalid type for parameter %d of constexpr "
5367                  "function %q+#D", DECL_PARM_INDEX (parm), fun);
5368       }
5369
5370   if (!DECL_CONSTRUCTOR_P (fun))
5371     {
5372       tree rettype = TREE_TYPE (TREE_TYPE (fun));
5373       if (!valid_type_in_constexpr_fundecl_p (rettype))
5374         {
5375           ret = false;
5376           if (complain)
5377             error ("invalid return type %qT of constexpr function %q+D",
5378                    rettype, fun);
5379         }
5380
5381       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
5382           && !CLASSTYPE_LITERAL_P (DECL_CONTEXT (fun)))
5383         {
5384           ret = false;
5385           if (complain)
5386             error ("enclosing class of %q+#D is not a literal type", fun);
5387         }
5388     }
5389
5390   return ret;
5391 }
5392
5393 /* Return non-null if FUN certainly designates a valid constexpr function
5394    declaration.  Otherwise return NULL.  Issue appropriate diagnostics
5395    if necessary.  Note that we only check the declaration, not the body
5396    of the function.  */
5397
5398 tree
5399 validate_constexpr_fundecl (tree fun)
5400 {
5401   constexpr_fundef entry;
5402   constexpr_fundef **slot;
5403
5404   if (processing_template_decl || !DECL_DECLARED_CONSTEXPR_P (fun))
5405     return NULL;
5406   else if (DECL_CLONED_FUNCTION_P (fun))
5407     /* We already checked the original function.  */
5408     return fun;
5409
5410   if (!is_valid_constexpr_fn (fun, !DECL_TEMPLATE_INSTANTIATION (fun)))
5411     {
5412       DECL_DECLARED_CONSTEXPR_P (fun) = false;
5413       return NULL;
5414     }
5415
5416   /* Create the constexpr function table if necessary.  */
5417   if (constexpr_fundef_table == NULL)
5418     constexpr_fundef_table = htab_create_ggc (101,
5419                                               constexpr_fundef_hash,
5420                                               constexpr_fundef_equal,
5421                                               ggc_free);
5422   entry.decl = fun;
5423   entry.body = NULL;
5424   slot = (constexpr_fundef **)
5425     htab_find_slot (constexpr_fundef_table, &entry, INSERT);
5426   if (*slot == NULL)
5427     {
5428       *slot = ggc_alloc_constexpr_fundef ();
5429       **slot = entry;
5430     }
5431   return fun;
5432 }
5433
5434 /* Subroutine of  build_constexpr_constructor_member_initializers.
5435    The expression tree T represents a data member initialization
5436    in a (constexpr) constructor definition.  Build a pairing of
5437    the data member with its initializer, and prepend that pair
5438    to the existing initialization pair INITS.  */
5439
5440 static bool
5441 build_data_member_initialization (tree t, VEC(constructor_elt,gc) **vec)
5442 {
5443   tree member, init;
5444   if (TREE_CODE (t) == CLEANUP_POINT_EXPR)
5445     t = TREE_OPERAND (t, 0);
5446   if (TREE_CODE (t) == EXPR_STMT)
5447     t = TREE_OPERAND (t, 0);
5448   if (t == error_mark_node)
5449     return false;
5450   if (TREE_CODE (t) == STATEMENT_LIST)
5451     {
5452       tree_stmt_iterator i;
5453       for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
5454         {
5455           if (! build_data_member_initialization (tsi_stmt (i), vec))
5456             return false;
5457         }
5458       return true;
5459     }
5460   if (TREE_CODE (t) == CLEANUP_STMT)
5461     {
5462       /* We can't see a CLEANUP_STMT in a constructor for a literal class,
5463          but we can in a constexpr constructor for a non-literal class.  Just
5464          ignore it; either all the initialization will be constant, in which
5465          case the cleanup can't run, or it can't be constexpr.
5466          Still recurse into CLEANUP_BODY.  */
5467       return build_data_member_initialization (CLEANUP_BODY (t), vec);
5468     }
5469   if (TREE_CODE (t) == CONVERT_EXPR)
5470     t = TREE_OPERAND (t, 0);
5471   if (TREE_CODE (t) == INIT_EXPR
5472       || TREE_CODE (t) == MODIFY_EXPR)
5473     {
5474       member = TREE_OPERAND (t, 0);
5475       init = unshare_expr (TREE_OPERAND (t, 1));
5476     }
5477   else
5478     {
5479       gcc_assert (TREE_CODE (t) == CALL_EXPR);
5480       member = CALL_EXPR_ARG (t, 0);
5481       /* We don't use build_cplus_new here because it complains about
5482          abstract bases.  Leaving the call unwrapped means that it has the
5483          wrong type, but cxx_eval_constant_expression doesn't care.  */
5484       init = unshare_expr (t);
5485     }
5486   if (TREE_CODE (member) == INDIRECT_REF)
5487     member = TREE_OPERAND (member, 0);
5488   if (TREE_CODE (member) == NOP_EXPR)
5489     {
5490       tree op = member;
5491       STRIP_NOPS (op);
5492       if (TREE_CODE (op) == ADDR_EXPR)
5493         {
5494           gcc_assert (same_type_ignoring_top_level_qualifiers_p
5495                       (TREE_TYPE (TREE_TYPE (op)),
5496                        TREE_TYPE (TREE_TYPE (member))));
5497           /* Initializing a cv-qualified member; we need to look through
5498              the const_cast.  */
5499           member = op;
5500         }
5501       else
5502         {
5503           /* We don't put out anything for an empty base.  */
5504           gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (member))));
5505           /* But if the initializer isn't constexpr, leave it in so we
5506              complain later.  */
5507           if (potential_constant_expression (init))
5508             return true;
5509         }
5510     }
5511   if (TREE_CODE (member) == ADDR_EXPR)
5512     member = TREE_OPERAND (member, 0);
5513   if (TREE_CODE (member) == COMPONENT_REF
5514       /* If we're initializing a member of a subaggregate, it's a vtable
5515          pointer.  Leave it as COMPONENT_REF so we remember the path to get
5516          to the vfield.  */
5517       && TREE_CODE (TREE_OPERAND (member, 0)) != COMPONENT_REF)
5518     member = TREE_OPERAND (member, 1);
5519   CONSTRUCTOR_APPEND_ELT (*vec, member, init);
5520   return true;
5521 }
5522
5523 /* Make sure that there are no statements after LAST in the constructor
5524    body represented by LIST.  */
5525
5526 bool
5527 check_constexpr_ctor_body (tree last, tree list)
5528 {
5529   bool ok = true;
5530   if (TREE_CODE (list) == STATEMENT_LIST)
5531     {
5532       tree_stmt_iterator i = tsi_last (list);
5533       for (; !tsi_end_p (i); tsi_prev (&i))
5534         {
5535           tree t = tsi_stmt (i);
5536           if (t == last)
5537             break;
5538           if (TREE_CODE (t) == BIND_EXPR)
5539             {
5540               if (!check_constexpr_ctor_body (last, BIND_EXPR_BODY (t)))
5541                 return false;
5542               else
5543                 continue;
5544             }
5545           /* We currently allow typedefs and static_assert.
5546              FIXME allow them in the standard, too.  */
5547           if (TREE_CODE (t) != STATIC_ASSERT)
5548             {
5549               ok = false;
5550               break;
5551             }
5552         }
5553     }
5554   else if (list != last
5555            && TREE_CODE (list) != STATIC_ASSERT)
5556     ok = false;
5557   if (!ok)
5558     {
5559       error ("constexpr constructor does not have empty body");
5560       DECL_DECLARED_CONSTEXPR_P (current_function_decl) = false;
5561     }
5562   return ok;
5563 }
5564
5565 /* Build compile-time evalable representations of member-initializer list
5566    for a constexpr constructor.  */
5567
5568 static tree
5569 build_constexpr_constructor_member_initializers (tree type, tree body)
5570 {
5571   VEC(constructor_elt,gc) *vec = NULL;
5572   bool ok = true;
5573   if (TREE_CODE (body) == MUST_NOT_THROW_EXPR
5574       || TREE_CODE (body) == EH_SPEC_BLOCK)
5575     body = TREE_OPERAND (body, 0);
5576   if (TREE_CODE (body) == STATEMENT_LIST)
5577     body = STATEMENT_LIST_HEAD (body)->stmt;
5578   body = BIND_EXPR_BODY (body);
5579   if (TREE_CODE (body) == CLEANUP_POINT_EXPR)
5580     {
5581       body = TREE_OPERAND (body, 0);
5582       if (TREE_CODE (body) == EXPR_STMT)
5583         body = TREE_OPERAND (body, 0);
5584       if (TREE_CODE (body) == INIT_EXPR
5585           && (same_type_ignoring_top_level_qualifiers_p
5586               (TREE_TYPE (TREE_OPERAND (body, 0)),
5587                current_class_type)))
5588         {
5589           /* Trivial copy.  */
5590           return TREE_OPERAND (body, 1);
5591         }
5592       ok = build_data_member_initialization (body, &vec);
5593     }
5594   else if (TREE_CODE (body) == STATEMENT_LIST)
5595     {
5596       tree_stmt_iterator i;
5597       for (i = tsi_start (body); !tsi_end_p (i); tsi_next (&i))
5598         {
5599           ok = build_data_member_initialization (tsi_stmt (i), &vec);
5600           if (!ok)
5601             break;
5602         }
5603     }
5604   else
5605     gcc_assert (errorcount > 0);
5606   if (ok)
5607     return build_constructor (type, vec);
5608   else
5609     return error_mark_node;
5610 }
5611
5612 /* Subroutine of register_constexpr_fundef.  BODY is the body of a function
5613    declared to be constexpr, or a sub-statement thereof.  Returns the
5614    return value if suitable, error_mark_node for a statement not allowed in
5615    a constexpr function, or NULL_TREE if no return value was found.  */
5616
5617 static tree
5618 constexpr_fn_retval (tree body)
5619 {
5620   switch (TREE_CODE (body))
5621     {
5622     case STATEMENT_LIST:
5623       {
5624         tree_stmt_iterator i;
5625         tree expr = NULL_TREE;
5626         for (i = tsi_start (body); !tsi_end_p (i); tsi_next (&i))
5627           {
5628             tree s = constexpr_fn_retval (tsi_stmt (i));
5629             if (s == error_mark_node)
5630               return error_mark_node;
5631             else if (s == NULL_TREE)
5632               /* Keep iterating.  */;
5633             else if (expr)
5634               /* Multiple return statements.  */
5635               return error_mark_node;
5636             else
5637               expr = s;
5638           }
5639         return expr;
5640       }
5641
5642     case RETURN_EXPR:
5643       return unshare_expr (TREE_OPERAND (body, 0));
5644
5645     case DECL_EXPR:
5646       if (TREE_CODE (DECL_EXPR_DECL (body)) == USING_DECL)
5647         return NULL_TREE;
5648       return error_mark_node;
5649
5650     case USING_STMT:
5651       return NULL_TREE;
5652
5653     default:
5654       return error_mark_node;
5655     }
5656 }
5657
5658 /* We are processing the definition of the constexpr function FUN.
5659    Check that its BODY fulfills the propriate requirements and
5660    enter it in the constexpr function definition table.
5661    For constructor BODY is actually the TREE_LIST of the
5662    member-initializer list.  */
5663
5664 tree
5665 register_constexpr_fundef (tree fun, tree body)
5666 {
5667   constexpr_fundef *fundef = retrieve_constexpr_fundef (fun);
5668   gcc_assert (fundef != NULL && fundef->body == NULL);
5669
5670   if (DECL_CONSTRUCTOR_P (fun))
5671     body = build_constexpr_constructor_member_initializers
5672       (DECL_CONTEXT (fun), body);
5673   else
5674     {
5675       if (TREE_CODE (body) == BIND_EXPR)
5676         body = BIND_EXPR_BODY (body);
5677       if (TREE_CODE (body) == EH_SPEC_BLOCK)
5678         body = EH_SPEC_STMTS (body);
5679       if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
5680         body = TREE_OPERAND (body, 0);
5681       if (TREE_CODE (body) == CLEANUP_POINT_EXPR)
5682         body = TREE_OPERAND (body, 0);
5683       body = constexpr_fn_retval (body);
5684       if (body == NULL_TREE || body == error_mark_node)
5685         {
5686           error ("body of constexpr function %qD not a return-statement", fun);
5687           DECL_DECLARED_CONSTEXPR_P (fun) = false;
5688           return NULL;
5689         }
5690     }
5691
5692   if (!potential_rvalue_constant_expression (body))
5693     {
5694       DECL_DECLARED_CONSTEXPR_P (fun) = false;
5695       if (!DECL_TEMPLATE_INSTANTIATION (fun))
5696         require_potential_rvalue_constant_expression (body);
5697       return NULL;
5698     }
5699   fundef->body = body;
5700   return fun;
5701 }
5702
5703 /* Objects of this type represent calls to constexpr functions
5704    along with the bindings of parameters to their arguments, for
5705    the purpose of compile time evaluation.  */
5706
5707 typedef struct GTY(()) constexpr_call {
5708   /* Description of the constexpr function definition.  */
5709   constexpr_fundef *fundef;
5710   /* Parameter bindings enironment.  A TREE_LIST where each TREE_PURPOSE
5711      is a parameter _DECL and the TREE_VALUE is the value of the parameter.
5712      Note: This arrangement is made to accomodate the use of
5713      iterative_hash_template_arg (see pt.c).  If you change this
5714      representation, also change the hash calculation in
5715      cxx_eval_call_expression.  */
5716   tree bindings;
5717   /* Result of the call.
5718        NULL means the call is being evaluated.
5719        error_mark_node means that the evaluation was erroneous;
5720        otherwise, the actuall value of the call.  */
5721   tree result;
5722   /* The hash of this call; we remember it here to avoid having to
5723      recalculate it when expanding the hash table.  */
5724   hashval_t hash;
5725 } constexpr_call;
5726
5727 /* A table of all constexpr calls that have been evaluated by the
5728    compiler in this translation unit.  */
5729
5730 static GTY ((param_is (constexpr_call))) htab_t constexpr_call_table;
5731
5732 static tree cxx_eval_constant_expression (const constexpr_call *, tree,
5733                                           bool, bool, bool *);
5734
5735 /* Compute a hash value for a constexpr call representation.  */
5736
5737 static hashval_t
5738 constexpr_call_hash (const void *p)
5739 {
5740   const constexpr_call *info = (const constexpr_call *) p;
5741   return info->hash;
5742 }
5743
5744 /* Return 1 if the objects pointed to by P and Q represent calls
5745    to the same constexpr function with the same arguments.
5746    Otherwise, return 0.  */
5747
5748 static int
5749 constexpr_call_equal (const void *p, const void *q)
5750 {
5751   const constexpr_call *lhs = (const constexpr_call *) p;
5752   const constexpr_call *rhs = (const constexpr_call *) q;
5753   tree lhs_bindings;
5754   tree rhs_bindings;
5755   if (lhs == rhs)
5756     return 1;
5757   if (!constexpr_fundef_equal (lhs->fundef, rhs->fundef))
5758     return 0;
5759   lhs_bindings = lhs->bindings;
5760   rhs_bindings = rhs->bindings;
5761   while (lhs_bindings != NULL && rhs_bindings != NULL)
5762     {
5763       tree lhs_arg = TREE_VALUE (lhs_bindings);
5764       tree rhs_arg = TREE_VALUE (rhs_bindings);
5765       gcc_assert (TREE_TYPE (lhs_arg) == TREE_TYPE (rhs_arg));
5766       if (!cp_tree_equal (lhs_arg, rhs_arg))
5767         return 0;
5768       lhs_bindings = TREE_CHAIN (lhs_bindings);
5769       rhs_bindings = TREE_CHAIN (rhs_bindings);
5770     }
5771   return lhs_bindings == rhs_bindings;
5772 }
5773
5774 /* Initialize the constexpr call table, if needed.  */
5775
5776 static void
5777 maybe_initialize_constexpr_call_table (void)
5778 {
5779   if (constexpr_call_table == NULL)
5780     constexpr_call_table = htab_create_ggc (101,
5781                                             constexpr_call_hash,
5782                                             constexpr_call_equal,
5783                                             ggc_free);
5784 }
5785
5786 /* Return true if T designates the implied `this' parameter.  */
5787
5788 static inline bool
5789 is_this_parameter (tree t)
5790 {
5791   return t == current_class_ptr;
5792 }
5793
5794 /* We have an expression tree T that represents a call, either CALL_EXPR
5795    or AGGR_INIT_EXPR.  If the call is lexically to a named function,
5796    retrun the _DECL for that function.  */
5797
5798 static tree
5799 get_function_named_in_call (tree t)
5800 {
5801   tree fun = NULL;
5802   switch (TREE_CODE (t))
5803     {
5804     case CALL_EXPR:
5805       fun = CALL_EXPR_FN (t);
5806       break;
5807
5808     case AGGR_INIT_EXPR:
5809       fun = AGGR_INIT_EXPR_FN (t);
5810       break;
5811
5812     default:
5813       gcc_unreachable();
5814       break;
5815     }
5816   if (TREE_CODE (fun) == ADDR_EXPR
5817       && TREE_CODE (TREE_OPERAND (fun, 0)) == FUNCTION_DECL)
5818     fun = TREE_OPERAND (fun, 0);
5819   return fun;
5820 }
5821
5822 /* We have an expression tree T that represents a call, either CALL_EXPR
5823    or AGGR_INIT_EXPR.  Return the Nth argument.  */
5824
5825 static inline tree
5826 get_nth_callarg (tree t, int n)
5827 {
5828   switch (TREE_CODE (t))
5829     {
5830     case CALL_EXPR:
5831       return CALL_EXPR_ARG (t, n);
5832
5833     case AGGR_INIT_EXPR:
5834       return AGGR_INIT_EXPR_ARG (t, n);
5835
5836     default:
5837       gcc_unreachable ();
5838       return NULL;
5839     }
5840 }
5841
5842 /* Look up the binding of the function parameter T in a constexpr
5843    function call context CALL.  */
5844
5845 static tree
5846 lookup_parameter_binding (const constexpr_call *call, tree t)
5847 {
5848   tree b = purpose_member (t, call->bindings);
5849   return TREE_VALUE (b);
5850 }
5851
5852 /* Attempt to evaluate T which represents a call to a builtin function.
5853    We assume here that all builtin functions evaluate to scalar types
5854    represented by _CST nodes.  */
5855
5856 static tree
5857 cxx_eval_builtin_function_call (const constexpr_call *call, tree t,
5858                                 bool allow_non_constant, bool addr,
5859                                 bool *non_constant_p)
5860 {
5861   const int nargs = call_expr_nargs (t);
5862   tree *args = (tree *) alloca (nargs * sizeof (tree));
5863   tree new_call;
5864   int i;
5865   for (i = 0; i < nargs; ++i)
5866     {
5867       args[i] = cxx_eval_constant_expression (call, CALL_EXPR_ARG (t, i),
5868                                               allow_non_constant, addr,
5869                                               non_constant_p);
5870       if (allow_non_constant && *non_constant_p)
5871         return t;
5872     }
5873   if (*non_constant_p)
5874     return t;
5875   new_call = build_call_array_loc (EXPR_LOCATION (t), TREE_TYPE (t),
5876                                    CALL_EXPR_FN (t), nargs, args);
5877   return fold (new_call);
5878 }
5879
5880 /* TEMP is the constant value of a temporary object of type TYPE.  Adjust
5881    the type of the value to match.  */
5882
5883 static tree
5884 adjust_temp_type (tree type, tree temp)
5885 {
5886   if (TREE_TYPE (temp) == type)
5887     return temp;
5888   /* Avoid wrapping an aggregate value in a NOP_EXPR.  */
5889   if (TREE_CODE (temp) == CONSTRUCTOR)
5890     return build_constructor (type, CONSTRUCTOR_ELTS (temp));
5891   gcc_assert (SCALAR_TYPE_P (type));
5892   return cp_fold_convert (type, temp);
5893 }
5894
5895 /* Subroutine of cxx_eval_call_expression.
5896    We are processing a call expression (either CALL_EXPR or
5897    AGGR_INIT_EXPR) in the call context of OLD_CALL.  Evaluate
5898    all arguments and bind their values to correspondings
5899    parameters, making up the NEW_CALL context.  */
5900
5901 static void
5902 cxx_bind_parameters_in_call (const constexpr_call *old_call, tree t,
5903                              constexpr_call *new_call,
5904                              bool allow_non_constant,
5905                              bool *non_constant_p)
5906 {
5907   const int nargs = call_expr_nargs (t);
5908   tree fun = new_call->fundef->decl;
5909   tree parms = DECL_ARGUMENTS (fun);
5910   int i;
5911   for (i = 0; i < nargs; ++i)
5912     {
5913       tree x, arg;
5914       tree type = parms ? TREE_TYPE (parms) : void_type_node;
5915       /* For member function, the first argument is a pointer to the implied
5916          object.  And for an object contruction, don't bind `this' before
5917          it is fully constructed.  */
5918       if (i == 0 && DECL_CONSTRUCTOR_P (fun))
5919         goto next;
5920       x = get_nth_callarg (t, i);
5921       arg = cxx_eval_constant_expression (old_call, x, allow_non_constant,
5922                                           TREE_CODE (type) == REFERENCE_TYPE,
5923                                           non_constant_p);
5924       /* Don't VERIFY_CONSTANT here.  */
5925       if (*non_constant_p && allow_non_constant)
5926         return;
5927       /* Just discard ellipsis args after checking their constantitude.  */
5928       if (!parms)
5929         continue;
5930       if (*non_constant_p)
5931         /* Don't try to adjust the type of non-constant args.  */
5932         goto next;
5933
5934       /* Make sure the binding has the same type as the parm.  */
5935       if (TREE_CODE (type) != REFERENCE_TYPE)
5936         arg = adjust_temp_type (type, arg);
5937       new_call->bindings = tree_cons (parms, arg, new_call->bindings);
5938     next:
5939       parms = TREE_CHAIN (parms);
5940     }
5941 }
5942
5943 /* Variables and functions to manage constexpr call expansion context.
5944    These do not need to be marked for PCH or GC.  */
5945
5946 /* FIXME remember and print actual constant arguments.  */
5947 static VEC(tree,heap) *call_stack = NULL;
5948 static int call_stack_tick;
5949 static int last_cx_error_tick;
5950
5951 static bool
5952 push_cx_call_context (tree call)
5953 {
5954   ++call_stack_tick;
5955   if (!EXPR_HAS_LOCATION (call))
5956     SET_EXPR_LOCATION (call, input_location);
5957   VEC_safe_push (tree, heap, call_stack, call);
5958   if (VEC_length (tree, call_stack) > (unsigned) max_constexpr_depth)
5959     return false;
5960   return true;
5961 }
5962
5963 static void
5964 pop_cx_call_context (void)
5965 {
5966   ++call_stack_tick;
5967   VEC_pop (tree, call_stack);
5968 }
5969
5970 VEC(tree,heap) *
5971 cx_error_context (void)
5972 {
5973   VEC(tree,heap) *r = NULL;
5974   if (call_stack_tick != last_cx_error_tick
5975       && !VEC_empty (tree, call_stack))
5976     r = call_stack;
5977   last_cx_error_tick = call_stack_tick;
5978   return r;
5979 }
5980
5981 /* Subroutine of cxx_eval_constant_expression.
5982    Evaluate the call expression tree T in the context of OLD_CALL expression
5983    evaluation.  */
5984
5985 static tree
5986 cxx_eval_call_expression (const constexpr_call *old_call, tree t,
5987                           bool allow_non_constant, bool addr,
5988                           bool *non_constant_p)
5989 {
5990   location_t loc = EXPR_LOC_OR_HERE (t);
5991   tree fun = get_function_named_in_call (t);
5992   tree result;
5993   constexpr_call new_call = { NULL, NULL, NULL, 0 };
5994   constexpr_call **slot;
5995   constexpr_call *entry;
5996   bool depth_ok;
5997
5998   if (TREE_CODE (fun) != FUNCTION_DECL)
5999     {
6000       /* Might be a constexpr function pointer.  */
6001       fun = cxx_eval_constant_expression (old_call, fun, allow_non_constant,
6002                                           /*addr*/false, non_constant_p);
6003       if (TREE_CODE (fun) == ADDR_EXPR)
6004         fun = TREE_OPERAND (fun, 0);
6005     }
6006   if (TREE_CODE (fun) != FUNCTION_DECL)
6007     {
6008       if (!allow_non_constant)
6009         error_at (loc, "expression %qE does not designate a constexpr "
6010                   "function", fun);
6011       *non_constant_p = true;
6012       return t;
6013     }
6014   if (DECL_CLONED_FUNCTION_P (fun))
6015     fun = DECL_CLONED_FUNCTION (fun);
6016   if (is_builtin_fn (fun))
6017     return cxx_eval_builtin_function_call (old_call, t, allow_non_constant,
6018                                            addr, non_constant_p);
6019   if (!DECL_DECLARED_CONSTEXPR_P (fun))
6020     {
6021       if (!allow_non_constant)
6022         {
6023           error_at (loc, "%qD is not a constexpr function", fun);
6024           if (DECL_TEMPLATE_INSTANTIATION (fun)
6025               && DECL_DECLARED_CONSTEXPR_P (DECL_TEMPLATE_RESULT
6026                                             (DECL_TI_TEMPLATE (fun))))
6027             is_valid_constexpr_fn (fun, true);
6028         }
6029       *non_constant_p = true;
6030       return t;
6031     }
6032
6033   /* Shortcut trivial copy constructor/op=.  */
6034   if (call_expr_nargs (t) == 2 && trivial_fn_p (fun))
6035     {
6036       tree arg = convert_from_reference (get_nth_callarg (t, 1));
6037       return cxx_eval_constant_expression (old_call, arg, allow_non_constant,
6038                                            addr, non_constant_p);
6039     }
6040
6041   /* If in direct recursive call, optimize definition search.  */
6042   if (old_call != NULL && old_call->fundef->decl == fun)
6043     new_call.fundef = old_call->fundef;
6044   else
6045     {
6046       new_call.fundef = retrieve_constexpr_fundef (fun);
6047       if (new_call.fundef == NULL || new_call.fundef->body == NULL)
6048         {
6049           if (!allow_non_constant)
6050             error_at (loc, "%qD used before its definition", fun);
6051           *non_constant_p = true;
6052           return t;
6053         }
6054     }
6055   cxx_bind_parameters_in_call (old_call, t, &new_call,
6056                                allow_non_constant, non_constant_p);
6057   if (*non_constant_p)
6058     return t;
6059
6060   depth_ok = push_cx_call_context (t);
6061
6062   new_call.hash
6063     = iterative_hash_template_arg (new_call.bindings,
6064                                    constexpr_fundef_hash (new_call.fundef));
6065
6066   /* If we have seen this call before, we are done.  */
6067   maybe_initialize_constexpr_call_table ();
6068   slot = (constexpr_call **)
6069     htab_find_slot (constexpr_call_table, &new_call, INSERT);
6070   entry = *slot;
6071   if (entry == NULL)
6072     {
6073       /* We need to keep a pointer to the entry, not just the slot, as the
6074          slot can move in the call to cxx_eval_builtin_function_call.  */
6075       *slot = entry = ggc_alloc_constexpr_call ();
6076       *entry = new_call;
6077     }
6078   /* Calls which are in progress have their result set to NULL
6079      so that we can detect circular dependencies.  */
6080   else if (entry->result == NULL)
6081     {
6082       if (!allow_non_constant)
6083         error ("call has circular dependency");
6084       *non_constant_p = true;
6085       entry->result = result = error_mark_node;
6086     }
6087
6088   if (!depth_ok)
6089     {
6090       if (!allow_non_constant)
6091         error ("constexpr evaluation depth exceeds maximum of %d (use "
6092                "-fconstexpr-depth= to increase the maximum)",
6093                max_constexpr_depth);
6094       *non_constant_p = true;
6095       entry->result = result = error_mark_node;
6096     }
6097   else
6098     {
6099       result = entry->result;
6100       if (!result || (result == error_mark_node && !allow_non_constant))
6101         result = (cxx_eval_constant_expression
6102                   (&new_call, new_call.fundef->body,
6103                    allow_non_constant, addr,
6104                    non_constant_p));
6105       if (result == error_mark_node)
6106         *non_constant_p = true;
6107       if (*non_constant_p)
6108         entry->result = result = error_mark_node;
6109       else
6110         {
6111           /* If this was a call to initialize an object, set the type of
6112              the CONSTRUCTOR to the type of that object.  */
6113           if (DECL_CONSTRUCTOR_P (fun))
6114             {
6115               tree ob_arg = get_nth_callarg (t, 0);
6116               STRIP_NOPS (ob_arg);
6117               gcc_assert (TREE_CODE (TREE_TYPE (ob_arg)) == POINTER_TYPE
6118                           && CLASS_TYPE_P (TREE_TYPE (TREE_TYPE (ob_arg))));
6119               result = adjust_temp_type (TREE_TYPE (TREE_TYPE (ob_arg)),
6120                                          result);
6121             }
6122           entry->result = result;
6123         }
6124     }
6125
6126   pop_cx_call_context ();
6127   return unshare_expr (result);
6128 }
6129
6130 /* FIXME speed this up, it's taking 16% of compile time on sieve testcase.  */
6131
6132 bool
6133 reduced_constant_expression_p (tree t)
6134 {
6135   if (TREE_OVERFLOW_P (t))
6136     /* Integer overflow makes this not a constant expression.  */
6137     return false;
6138   /* FIXME are we calling this too much?  */
6139   return initializer_constant_valid_p (t, TREE_TYPE (t)) != NULL_TREE;
6140 }
6141
6142 /* Some expressions may have constant operands but are not constant
6143    themselves, such as 1/0.  Call this function (or rather, the macro
6144    following it) to check for that condition.
6145
6146    We only call this in places that require an arithmetic constant, not in
6147    places where we might have a non-constant expression that can be a
6148    component of a constant expression, such as the address of a constexpr
6149    variable that might be dereferenced later.  */
6150
6151 static bool
6152 verify_constant (tree t, bool allow_non_constant, bool *non_constant_p)
6153 {
6154   if (!*non_constant_p && !reduced_constant_expression_p (t))
6155     {
6156       if (!allow_non_constant)
6157         {
6158           /* If T was already folded to a _CST with TREE_OVERFLOW set,
6159              printing the folded constant isn't helpful.  */
6160           if (TREE_OVERFLOW_P (t))
6161             {
6162               permerror (input_location, "overflow in constant expression");
6163               /* If we're being permissive (and are in an enforcing
6164                  context), consider this constant.  */
6165               if (flag_permissive)
6166                 return false;
6167             }
6168           else
6169             error ("%q+E is not a constant expression", t);
6170         }
6171       *non_constant_p = true;
6172     }
6173   return *non_constant_p;
6174 }
6175 #define VERIFY_CONSTANT(X)                                              \
6176 do {                                                                    \
6177   if (verify_constant ((X), allow_non_constant, non_constant_p))        \
6178     return t;                                                           \
6179  } while (0)
6180
6181 /* Subroutine of cxx_eval_constant_expression.
6182    Attempt to reduce the unary expression tree T to a compile time value.
6183    If successful, return the value.  Otherwise issue a diagnostic
6184    and return error_mark_node.  */
6185
6186 static tree
6187 cxx_eval_unary_expression (const constexpr_call *call, tree t,
6188                            bool allow_non_constant, bool addr,
6189                            bool *non_constant_p)
6190 {
6191   tree r;
6192   tree orig_arg = TREE_OPERAND (t, 0);
6193   tree arg = cxx_eval_constant_expression (call, orig_arg, allow_non_constant,
6194                                            addr, non_constant_p);
6195   VERIFY_CONSTANT (arg);
6196   if (arg == orig_arg)
6197     return t;
6198   r = fold_build1 (TREE_CODE (t), TREE_TYPE (t), arg);
6199   VERIFY_CONSTANT (r);
6200   return r;
6201 }
6202
6203 /* Subroutine of cxx_eval_constant_expression.
6204    Like cxx_eval_unary_expression, except for binary expressions.  */
6205
6206 static tree
6207 cxx_eval_binary_expression (const constexpr_call *call, tree t,
6208                             bool allow_non_constant, bool addr,
6209                             bool *non_constant_p)
6210 {
6211   tree r;
6212   tree orig_lhs = TREE_OPERAND (t, 0);
6213   tree orig_rhs = TREE_OPERAND (t, 1);
6214   tree lhs, rhs;
6215   lhs = cxx_eval_constant_expression (call, orig_lhs,
6216                                       allow_non_constant, addr,
6217                                       non_constant_p);
6218   VERIFY_CONSTANT (lhs);
6219   rhs = cxx_eval_constant_expression (call, orig_rhs,
6220                                       allow_non_constant, addr,
6221                                       non_constant_p);
6222   VERIFY_CONSTANT (rhs);
6223   if (lhs == orig_lhs && rhs == orig_rhs)
6224     return t;
6225   r = fold_build2 (TREE_CODE (t), TREE_TYPE (t), lhs, rhs);
6226   VERIFY_CONSTANT (r);
6227   return r;
6228 }
6229
6230 /* Subroutine of cxx_eval_constant_expression.
6231    Attempt to evaluate condition expressions.  Dead branches are not
6232    looked into.  */
6233
6234 static tree
6235 cxx_eval_conditional_expression (const constexpr_call *call, tree t,
6236                                  bool allow_non_constant, bool addr,
6237                                  bool *non_constant_p)
6238 {
6239   tree val = cxx_eval_constant_expression (call, TREE_OPERAND (t, 0),
6240                                            allow_non_constant, addr,
6241                                            non_constant_p);
6242   VERIFY_CONSTANT (val);
6243   if (val == boolean_true_node)
6244     return cxx_eval_constant_expression (call, TREE_OPERAND (t, 1),
6245                                          allow_non_constant, addr,
6246                                          non_constant_p);
6247   gcc_assert (val == boolean_false_node);
6248   /* Don't VERIFY_CONSTANT here.  */
6249   return cxx_eval_constant_expression (call, TREE_OPERAND (t, 2),
6250                                        allow_non_constant, addr,
6251                                        non_constant_p);
6252 }
6253
6254 /* Subroutine of cxx_eval_constant_expression.
6255    Attempt to reduce a reference to an array slot.  */
6256
6257 static tree
6258 cxx_eval_array_reference (const constexpr_call *call, tree t,
6259                           bool allow_non_constant, bool addr,
6260                           bool *non_constant_p)
6261 {
6262   tree oldary = TREE_OPERAND (t, 0);
6263   tree ary = cxx_eval_constant_expression (call, oldary,
6264                                            allow_non_constant, addr,
6265                                            non_constant_p);
6266   tree index, oldidx;
6267   HOST_WIDE_INT i;
6268   unsigned len;
6269   if (*non_constant_p)
6270     return t;
6271   oldidx = TREE_OPERAND (t, 1);
6272   index = cxx_eval_constant_expression (call, oldidx,
6273                                         allow_non_constant, false,
6274                                         non_constant_p);
6275   VERIFY_CONSTANT (index);
6276   if (addr && ary == oldary && index == oldidx)
6277     return t;
6278   else if (addr)
6279     return build4 (ARRAY_REF, TREE_TYPE (t), ary, index, NULL, NULL);
6280   len = (TREE_CODE (ary) == CONSTRUCTOR
6281          ? CONSTRUCTOR_NELTS (ary)
6282          : (unsigned)TREE_STRING_LENGTH (ary));
6283   if (compare_tree_int (index, len) >= 0)
6284     {
6285       if (!allow_non_constant)
6286         error ("array subscript out of bound");
6287       *non_constant_p = true;
6288       return t;
6289     }
6290   i = tree_low_cst (index, 0);
6291   if (TREE_CODE (ary) == CONSTRUCTOR)
6292     return VEC_index (constructor_elt, CONSTRUCTOR_ELTS (ary), i)->value;
6293   else
6294     return build_int_cst (cv_unqualified (TREE_TYPE (TREE_TYPE (ary))),
6295                           TREE_STRING_POINTER (ary)[i]);
6296   /* Don't VERIFY_CONSTANT here.  */
6297 }
6298
6299 /* Subroutine of cxx_eval_constant_expression.
6300    Attempt to reduce a field access of a value of class type.  */
6301
6302 static tree
6303 cxx_eval_component_reference (const constexpr_call *call, tree t,
6304                               bool allow_non_constant, bool addr,
6305                               bool *non_constant_p)
6306 {
6307   unsigned HOST_WIDE_INT i;
6308   tree field;
6309   tree value;
6310   tree part = TREE_OPERAND (t, 1);
6311   tree orig_whole = TREE_OPERAND (t, 0);
6312   tree whole = cxx_eval_constant_expression (call, orig_whole,
6313                                              allow_non_constant, addr,
6314                                              non_constant_p);
6315   if (whole == orig_whole)
6316     return t;
6317   if (addr)
6318     return fold_build3 (COMPONENT_REF, TREE_TYPE (t),
6319                         whole, part, NULL_TREE);
6320   /* Don't VERIFY_CONSTANT here; we only want to check that we got a
6321      CONSTRUCTOR.  */
6322   if (!*non_constant_p && TREE_CODE (whole) != CONSTRUCTOR)
6323     {
6324       if (!allow_non_constant)
6325         error ("%qE is not a constant expression", orig_whole);
6326       *non_constant_p = true;
6327     }
6328   if (*non_constant_p)
6329     return t;
6330   FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
6331     {
6332       if (field == part)
6333         return value;
6334     }
6335   if (TREE_CODE (TREE_TYPE (whole)) == UNION_TYPE)
6336     {
6337       /* FIXME Mike Miller wants this to be OK.  */
6338       if (!allow_non_constant)
6339         error ("accessing %qD member instead of initialized %qD member in "
6340                "constant expression", part, CONSTRUCTOR_ELT (whole, 0)->index);
6341       *non_constant_p = true;
6342       return t;
6343     }
6344   gcc_unreachable();
6345   return error_mark_node;
6346 }
6347
6348 /* Subroutine of cxx_eval_constant_expression.
6349    Attempt to reduce a field access of a value of class type that is
6350    expressed as a BIT_FIELD_REF.  */
6351
6352 static tree
6353 cxx_eval_bit_field_ref (const constexpr_call *call, tree t,
6354                         bool allow_non_constant, bool addr,
6355                         bool *non_constant_p)
6356 {
6357   tree orig_whole = TREE_OPERAND (t, 0);
6358   tree whole = cxx_eval_constant_expression (call, orig_whole,
6359                                              allow_non_constant, addr,
6360                                              non_constant_p);
6361   tree start, field, value;
6362   unsigned HOST_WIDE_INT i;
6363
6364   if (whole == orig_whole)
6365     return t;
6366   /* Don't VERIFY_CONSTANT here; we only want to check that we got a
6367      CONSTRUCTOR.  */
6368   if (!*non_constant_p && TREE_CODE (whole) != CONSTRUCTOR)
6369     {
6370       if (!allow_non_constant)
6371         error ("%qE is not a constant expression", orig_whole);
6372       *non_constant_p = true;
6373     }
6374   if (*non_constant_p)
6375     return t;
6376
6377   start = TREE_OPERAND (t, 2);
6378   FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
6379     {
6380       if (bit_position (field) == start)
6381         return value;
6382     }
6383   gcc_unreachable();
6384   return error_mark_node;
6385 }
6386
6387 /* Subroutine of cxx_eval_constant_expression.
6388    Evaluate a short-circuited logical expression T in the context
6389    of a given constexpr CALL.  BAILOUT_VALUE is the value for
6390    early return.  CONTINUE_VALUE is used here purely for
6391    sanity check purposes.  */
6392
6393 static tree
6394 cxx_eval_logical_expression (const constexpr_call *call, tree t,
6395                              tree bailout_value, tree continue_value,
6396                              bool allow_non_constant, bool addr,
6397                              bool *non_constant_p)
6398 {
6399   tree r;
6400   tree lhs = cxx_eval_constant_expression (call, TREE_OPERAND (t, 0),
6401                                            allow_non_constant, addr,
6402                                            non_constant_p);
6403   VERIFY_CONSTANT (lhs);
6404   if (lhs == bailout_value)
6405     return lhs;
6406   gcc_assert (lhs == continue_value);
6407   r = cxx_eval_constant_expression (call, TREE_OPERAND (t, 1),
6408                                     allow_non_constant, addr, non_constant_p);
6409   VERIFY_CONSTANT (r);
6410   return r;
6411 }
6412
6413 /* REF is a COMPONENT_REF designating a particular field.  V is a vector of
6414    CONSTRUCTOR elements to initialize (part of) an object containing that
6415    field.  Return a pointer to the constructor_elt corresponding to the
6416    initialization of the field.  */
6417
6418 static constructor_elt *
6419 base_field_constructor_elt (VEC(constructor_elt,gc) *v, tree ref)
6420 {
6421   tree aggr = TREE_OPERAND (ref, 0);
6422   tree field = TREE_OPERAND (ref, 1);
6423   HOST_WIDE_INT i;
6424   constructor_elt *ce;
6425
6426   gcc_assert (TREE_CODE (ref) == COMPONENT_REF);
6427
6428   if (TREE_CODE (aggr) == COMPONENT_REF)
6429     {
6430       constructor_elt *base_ce
6431         = base_field_constructor_elt (v, aggr);
6432       v = CONSTRUCTOR_ELTS (base_ce->value);
6433     }
6434
6435   for (i = 0; VEC_iterate (constructor_elt, v, i, ce); ++i)
6436     if (ce->index == field)
6437       return ce;
6438
6439   gcc_unreachable ();
6440   return NULL;
6441 }
6442
6443 /* Subroutine of cxx_eval_constant_expression.
6444    The expression tree T denotes a C-style array or a C-style
6445    aggregate.  Reduce it to a constant expression.  */
6446
6447 static tree
6448 cxx_eval_bare_aggregate (const constexpr_call *call, tree t,
6449                          bool allow_non_constant, bool addr,
6450                          bool *non_constant_p)
6451 {
6452   VEC(constructor_elt,gc) *v = CONSTRUCTOR_ELTS (t);
6453   VEC(constructor_elt,gc) *n = VEC_alloc (constructor_elt, gc,
6454                                           VEC_length (constructor_elt, v));
6455   constructor_elt *ce;
6456   HOST_WIDE_INT i;
6457   bool changed = false;
6458   gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (t));
6459   for (i = 0; VEC_iterate (constructor_elt, v, i, ce); ++i)
6460     {
6461       tree elt = cxx_eval_constant_expression (call, ce->value,
6462                                                allow_non_constant, addr,
6463                                                non_constant_p);
6464       /* Don't VERIFY_CONSTANT here.  */
6465       if (allow_non_constant && *non_constant_p)
6466         goto fail;
6467       if (elt != ce->value)
6468         changed = true;
6469       if (TREE_CODE (ce->index) == COMPONENT_REF)
6470         {
6471           /* This is an initialization of a vfield inside a base
6472              subaggregate that we already initialized; push this
6473              initialization into the previous initialization.  */
6474           constructor_elt *inner = base_field_constructor_elt (n, ce->index);
6475           inner->value = elt;
6476         }
6477       else
6478         CONSTRUCTOR_APPEND_ELT (n, ce->index, elt);
6479     }
6480   if (*non_constant_p || !changed)
6481     {
6482     fail:
6483       VEC_free (constructor_elt, gc, n);
6484       return t;
6485     }
6486   t = build_constructor (TREE_TYPE (t), n);
6487   TREE_CONSTANT (t) = true;
6488   return t;
6489 }
6490
6491 /* Subroutine of cxx_eval_constant_expression.
6492    The expression tree T is a VEC_INIT_EXPR which denotes the desired
6493    initialization of a non-static data member of array type.  Reduce it to a
6494    CONSTRUCTOR.
6495
6496    Note that apart from value-initialization (when VALUE_INIT is true),
6497    this is only intended to support value-initialization and the
6498    initializations done by defaulted constructors for classes with
6499    non-static data members of array type.  In this case, VEC_INIT_EXPR_INIT
6500    will either be NULL_TREE for the default constructor, or a COMPONENT_REF
6501    for the copy/move constructor.  */
6502
6503 static tree
6504 cxx_eval_vec_init_1 (const constexpr_call *call, tree atype, tree init,
6505                      bool value_init, bool allow_non_constant, bool addr,
6506                      bool *non_constant_p)
6507 {
6508   tree elttype = TREE_TYPE (atype);
6509   int max = tree_low_cst (array_type_nelts (atype), 0);
6510   VEC(constructor_elt,gc) *n = VEC_alloc (constructor_elt, gc, max + 1);
6511   int i;
6512
6513   /* For the default constructor, build up a call to the default
6514      constructor of the element type.  We only need to handle class types
6515      here, as for a constructor to be constexpr, all members must be
6516      initialized, which for a defaulted default constructor means they must
6517      be of a class type with a constexpr default constructor.  */
6518   if (value_init)
6519     gcc_assert (!init);
6520   else if (!init)
6521     {
6522       VEC(tree,gc) *argvec = make_tree_vector ();
6523       init = build_special_member_call (NULL_TREE, complete_ctor_identifier,
6524                                         &argvec, elttype, LOOKUP_NORMAL,
6525                                         tf_warning_or_error);
6526       release_tree_vector (argvec);
6527       init = cxx_eval_constant_expression (call, init, allow_non_constant,
6528                                            addr, non_constant_p);
6529     }
6530
6531   if (*non_constant_p && !allow_non_constant)
6532     goto fail;
6533
6534   for (i = 0; i <= max; ++i)
6535     {
6536       tree idx = build_int_cst (size_type_node, i);
6537       tree eltinit;
6538       if (TREE_CODE (elttype) == ARRAY_TYPE)
6539         {
6540           /* A multidimensional array; recurse.  */
6541           if (value_init)
6542             eltinit = NULL_TREE;
6543           else
6544             eltinit = cp_build_array_ref (input_location, init, idx,
6545                                           tf_warning_or_error);
6546           eltinit = cxx_eval_vec_init_1 (call, elttype, eltinit, value_init,
6547                                          allow_non_constant, addr,
6548                                          non_constant_p);
6549         }
6550       else if (value_init)
6551         {
6552           eltinit = build_value_init (elttype, tf_warning_or_error);
6553           eltinit = cxx_eval_constant_expression
6554             (call, eltinit, allow_non_constant, addr, non_constant_p);
6555         }
6556       else if (TREE_CODE (init) == CONSTRUCTOR)
6557         {
6558           /* Initializing an element using the call to the default
6559              constructor we just built above.  */
6560           eltinit = unshare_expr (init);
6561         }
6562       else
6563         {
6564           /* Copying an element.  */
6565           VEC(tree,gc) *argvec;
6566           gcc_assert (same_type_ignoring_top_level_qualifiers_p
6567                       (atype, TREE_TYPE (init)));
6568           eltinit = cp_build_array_ref (input_location, init, idx,
6569                                         tf_warning_or_error);
6570           if (!real_lvalue_p (init))
6571             eltinit = move (eltinit);
6572           argvec = make_tree_vector ();
6573           VEC_quick_push (tree, argvec, eltinit);
6574           eltinit = (build_special_member_call
6575                      (NULL_TREE, complete_ctor_identifier, &argvec,
6576                       elttype, LOOKUP_NORMAL, tf_warning_or_error));
6577           release_tree_vector (argvec);
6578           eltinit = cxx_eval_constant_expression
6579             (call, eltinit, allow_non_constant, addr, non_constant_p);
6580         }
6581       if (*non_constant_p && !allow_non_constant)
6582         goto fail;
6583       CONSTRUCTOR_APPEND_ELT (n, idx, eltinit);
6584     }
6585
6586   if (!*non_constant_p)
6587     {
6588       init = build_constructor (TREE_TYPE (atype), n);
6589       TREE_CONSTANT (init) = true;
6590       return init;
6591     }
6592
6593  fail:
6594   VEC_free (constructor_elt, gc, n);
6595   return init;
6596 }
6597
6598 static tree
6599 cxx_eval_vec_init (const constexpr_call *call, tree t,
6600                    bool allow_non_constant, bool addr,
6601                    bool *non_constant_p)
6602 {
6603   tree atype = TREE_TYPE (t);
6604   tree init = VEC_INIT_EXPR_INIT (t);
6605   tree r = cxx_eval_vec_init_1 (call, atype, init,
6606                                 VEC_INIT_EXPR_VALUE_INIT (t),
6607                                 allow_non_constant, addr, non_constant_p);
6608   if (*non_constant_p)
6609     return t;
6610   else
6611     return r;
6612 }
6613
6614 /* A less strict version of fold_indirect_ref_1, which requires cv-quals to
6615    match.  We want to be less strict for simple *& folding; if we have a
6616    non-const temporary that we access through a const pointer, that should
6617    work.  We handle this here rather than change fold_indirect_ref_1
6618    because we're dealing with things like ADDR_EXPR of INTEGER_CST which
6619    don't really make sense outside of constant expression evaluation.  Also
6620    we want to allow folding to COMPONENT_REF, which could cause trouble
6621    with TBAA in fold_indirect_ref_1.  */
6622
6623 static tree
6624 cxx_eval_indirect_ref (const constexpr_call *call, tree t,
6625                        bool allow_non_constant, bool addr,
6626                        bool *non_constant_p)
6627 {
6628   tree orig_op0 = TREE_OPERAND (t, 0);
6629   tree op0 = cxx_eval_constant_expression (call, orig_op0, allow_non_constant,
6630                                            /*addr*/false, non_constant_p);
6631   tree type, sub, subtype, r;
6632   bool empty_base;
6633
6634   /* Don't VERIFY_CONSTANT here.  */
6635   if (*non_constant_p)
6636     return t;
6637
6638   type = TREE_TYPE (t);
6639   sub = op0;
6640   r = NULL_TREE;
6641   empty_base = false;
6642
6643   STRIP_NOPS (sub);
6644   subtype = TREE_TYPE (sub);
6645   gcc_assert (POINTER_TYPE_P (subtype));
6646
6647   if (TREE_CODE (sub) == ADDR_EXPR)
6648     {
6649       tree op = TREE_OPERAND (sub, 0);
6650       tree optype = TREE_TYPE (op);
6651
6652       if (same_type_ignoring_top_level_qualifiers_p (optype, type))
6653         r = op;
6654       /* Also handle conversion to an empty base class, which
6655          is represented with a NOP_EXPR.  */
6656       else if (!addr && is_empty_class (type)
6657                && CLASS_TYPE_P (optype)
6658                && DERIVED_FROM_P (type, optype))
6659         {
6660           r = op;
6661           empty_base = true;
6662         }
6663       /* *(foo *)&struct_with_foo_field => COMPONENT_REF */
6664       else if (RECORD_OR_UNION_TYPE_P (optype))
6665         {
6666           tree field = TYPE_FIELDS (optype);
6667           for (; field; field = DECL_CHAIN (field))
6668             if (TREE_CODE (field) == FIELD_DECL
6669                 && integer_zerop (byte_position (field))
6670                 && (same_type_ignoring_top_level_qualifiers_p
6671                     (TREE_TYPE (field), type)))
6672               {
6673                 r = fold_build3 (COMPONENT_REF, type, op, field, NULL_TREE);
6674                 break;
6675               }
6676         }
6677     }
6678   else if (TREE_CODE (sub) == POINTER_PLUS_EXPR
6679            && TREE_CODE (TREE_OPERAND (sub, 1)) == INTEGER_CST)
6680     {
6681       tree op00 = TREE_OPERAND (sub, 0);
6682       tree op01 = TREE_OPERAND (sub, 1);
6683
6684       STRIP_NOPS (op00);
6685       if (TREE_CODE (op00) == ADDR_EXPR)
6686         {
6687           tree op00type;
6688           op00 = TREE_OPERAND (op00, 0);
6689           op00type = TREE_TYPE (op00);
6690
6691           /* ((foo *)&struct_with_foo_field)[1] => COMPONENT_REF */
6692           if (RECORD_OR_UNION_TYPE_P (op00type))
6693             {
6694               tree field = TYPE_FIELDS (op00type);
6695               for (; field; field = DECL_CHAIN (field))
6696                 if (TREE_CODE (field) == FIELD_DECL
6697                     && tree_int_cst_equal (byte_position (field), op01)
6698                     && (same_type_ignoring_top_level_qualifiers_p
6699                         (TREE_TYPE (field), type)))
6700                   {
6701                     r = fold_build3 (COMPONENT_REF, type, op00,
6702                                      field, NULL_TREE);
6703                     break;
6704                   }
6705             }
6706         }
6707     }
6708
6709   /* Let build_fold_indirect_ref handle the cases it does fine with.  */
6710   if (r == NULL_TREE)
6711     r = build_fold_indirect_ref (op0);
6712   if (TREE_CODE (r) != INDIRECT_REF)
6713     r = cxx_eval_constant_expression (call, r, allow_non_constant,
6714                                       addr, non_constant_p);
6715   else if (TREE_CODE (sub) == ADDR_EXPR
6716            || TREE_CODE (sub) == POINTER_PLUS_EXPR)
6717     {
6718       gcc_assert (!same_type_ignoring_top_level_qualifiers_p
6719                   (TREE_TYPE (TREE_TYPE (sub)), TREE_TYPE (t)));
6720       /* FIXME Mike Miller wants this to be OK.  */
6721       if (!allow_non_constant)
6722         error ("accessing value of %qE through a %qT glvalue in a "
6723                "constant expression", build_fold_indirect_ref (sub),
6724                TREE_TYPE (t));
6725       *non_constant_p = true;
6726       return t;
6727     }
6728
6729   /* If we're pulling out the value of an empty base, make sure
6730      that the whole object is constant and then return an empty
6731      CONSTRUCTOR.  */
6732   if (empty_base)
6733     {
6734       VERIFY_CONSTANT (r);
6735       r = build_constructor (TREE_TYPE (t), NULL);
6736       TREE_CONSTANT (r) = true;
6737     }
6738
6739   if (TREE_CODE (r) == INDIRECT_REF && TREE_OPERAND (r, 0) == orig_op0)
6740     return t;
6741   return r;
6742 }
6743
6744 /* Complain about R, a VAR_DECL, not being usable in a constant expression.
6745    Shared between potential_constant_expression and
6746    cxx_eval_constant_expression.  */
6747
6748 static void
6749 non_const_var_error (tree r)
6750 {
6751   tree type = TREE_TYPE (r);
6752   error ("the value of %qD is not usable in a constant "
6753          "expression", r);
6754   /* Avoid error cascade.  */
6755   if (DECL_INITIAL (r) == error_mark_node)
6756     return;
6757   if (DECL_DECLARED_CONSTEXPR_P (r))
6758     inform (DECL_SOURCE_LOCATION (r),
6759             "%qD used in its own initializer", r);
6760   else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
6761     {
6762       if (!CP_TYPE_CONST_P (type))
6763         inform (DECL_SOURCE_LOCATION (r),
6764                 "%q#D is not const", r);
6765       else if (CP_TYPE_VOLATILE_P (type))
6766         inform (DECL_SOURCE_LOCATION (r),
6767                 "%q#D is volatile", r);
6768       else if (!DECL_INITIAL (r))
6769         inform (DECL_SOURCE_LOCATION (r),
6770                 "%qD was not initialized with a constant "
6771                 "expression", r);
6772       else
6773         gcc_unreachable ();
6774     }
6775   else
6776     {
6777       if (cxx_dialect >= cxx0x && !DECL_DECLARED_CONSTEXPR_P (r))
6778         inform (DECL_SOURCE_LOCATION (r),
6779                 "%qD was not declared %<constexpr%>", r);
6780       else
6781         inform (DECL_SOURCE_LOCATION (r),
6782                 "%qD does not have integral or enumeration type",
6783                 r);
6784     }
6785 }
6786
6787 /* Attempt to reduce the expression T to a constant value.
6788    On failure, issue diagnostic and return error_mark_node.  */
6789 /* FIXME unify with c_fully_fold */
6790
6791 static tree
6792 cxx_eval_constant_expression (const constexpr_call *call, tree t,
6793                               bool allow_non_constant, bool addr,
6794                               bool *non_constant_p)
6795 {
6796   tree r = t;
6797
6798   if (t == error_mark_node)
6799     {
6800       *non_constant_p = true;
6801       return t;
6802     }
6803   if (CONSTANT_CLASS_P (t))
6804     {
6805       if (TREE_CODE (t) == PTRMEM_CST)
6806         t = cplus_expand_constant (t);
6807       return t;
6808     }
6809   if (TREE_CODE (t) != NOP_EXPR
6810       && reduced_constant_expression_p (t))
6811     return fold (t);
6812
6813   switch (TREE_CODE (t))
6814     {
6815     case VAR_DECL:
6816       if (addr)
6817         return t;
6818       /* else fall through. */
6819     case CONST_DECL:
6820       r = integral_constant_value (t);
6821       if (TREE_CODE (r) == TARGET_EXPR
6822           && TREE_CODE (TARGET_EXPR_INITIAL (r)) == CONSTRUCTOR)
6823         r = TARGET_EXPR_INITIAL (r);
6824       if (DECL_P (r))
6825         {
6826           if (!allow_non_constant)
6827             non_const_var_error (r);
6828           *non_constant_p = true;
6829         }
6830       break;
6831
6832     case FUNCTION_DECL:
6833     case LABEL_DECL:
6834       return t;
6835
6836     case PARM_DECL:
6837       if (call && DECL_CONTEXT (t) == call->fundef->decl)
6838         r = lookup_parameter_binding (call, t);
6839       else if (addr)
6840         /* Defer in case this is only used for its type.  */;
6841       else
6842         {
6843           if (!allow_non_constant)
6844             error ("%qE is not a constant expression", t);
6845           *non_constant_p = true;
6846         }
6847       break;
6848
6849     case CALL_EXPR:
6850     case AGGR_INIT_EXPR:
6851       r = cxx_eval_call_expression (call, t, allow_non_constant, addr,
6852                                     non_constant_p);
6853       break;
6854
6855     case TARGET_EXPR:
6856     case INIT_EXPR:
6857       /* Pass false for 'addr' because these codes indicate
6858          initialization of a temporary.  */
6859       r = cxx_eval_constant_expression (call, TREE_OPERAND (t, 1),
6860                                         allow_non_constant, false,
6861                                         non_constant_p);
6862       if (!*non_constant_p)
6863         /* Adjust the type of the result to the type of the temporary.  */
6864         r = adjust_temp_type (TREE_TYPE (t), r);
6865       break;
6866
6867     case SCOPE_REF:
6868       r = cxx_eval_constant_expression (call, TREE_OPERAND (t, 1),
6869                                         allow_non_constant, addr,
6870                                         non_constant_p);
6871       break;
6872
6873     case RETURN_EXPR:
6874     case NON_LVALUE_EXPR:
6875     case TRY_CATCH_EXPR:
6876     case CLEANUP_POINT_EXPR:
6877     case MUST_NOT_THROW_EXPR:
6878     case SAVE_EXPR:
6879       r = cxx_eval_constant_expression (call, TREE_OPERAND (t, 0),
6880                                         allow_non_constant, addr,
6881                                         non_constant_p);
6882       break;
6883
6884       /* These differ from cxx_eval_unary_expression in that this doesn't
6885          check for a constant operand or result; an address can be
6886          constant without its operand being, and vice versa.  */
6887     case INDIRECT_REF:
6888       r = cxx_eval_indirect_ref (call, t, allow_non_constant, addr,
6889                                  non_constant_p);
6890       break;
6891
6892     case ADDR_EXPR:
6893       {
6894         tree oldop = TREE_OPERAND (t, 0);
6895         tree op = cxx_eval_constant_expression (call, oldop,
6896                                                 allow_non_constant,
6897                                                 /*addr*/true,
6898                                                 non_constant_p);
6899         /* Don't VERIFY_CONSTANT here.  */
6900         if (*non_constant_p)
6901           return t;
6902         /* This function does more aggressive folding than fold itself.  */
6903         r = build_fold_addr_expr_with_type (op, TREE_TYPE (t));
6904         if (TREE_CODE (r) == ADDR_EXPR && TREE_OPERAND (r, 0) == oldop)
6905           return t;
6906         break;
6907       }
6908
6909     case REALPART_EXPR:
6910     case IMAGPART_EXPR:
6911     case CONJ_EXPR:
6912     case FIX_TRUNC_EXPR:
6913     case FLOAT_EXPR:
6914     case NEGATE_EXPR:
6915     case ABS_EXPR:
6916     case BIT_NOT_EXPR:
6917     case TRUTH_NOT_EXPR:
6918     case FIXED_CONVERT_EXPR:
6919       r = cxx_eval_unary_expression (call, t, allow_non_constant, addr,
6920                                      non_constant_p);
6921       break;
6922
6923     case COMPOUND_EXPR:
6924       {
6925         /* check_return_expr sometimes wraps a TARGET_EXPR in a
6926            COMPOUND_EXPR; don't get confused.  Also handle EMPTY_CLASS_EXPR
6927            introduced by build_call_a.  */
6928         tree op0 = TREE_OPERAND (t, 0);
6929         tree op1 = TREE_OPERAND (t, 1);
6930         STRIP_NOPS (op1);
6931         if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
6932             || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
6933           r = cxx_eval_constant_expression (call, op0, allow_non_constant,
6934                                             addr, non_constant_p);
6935         else
6936           {
6937             /* Check that the LHS is constant and then discard it.  */
6938             cxx_eval_constant_expression (call, op0, allow_non_constant,
6939                                           false, non_constant_p);
6940             r = cxx_eval_constant_expression (call, op1, allow_non_constant,
6941                                               addr, non_constant_p);
6942           }
6943       }
6944       break;
6945
6946     case POINTER_PLUS_EXPR:
6947     case PLUS_EXPR:
6948     case MINUS_EXPR:
6949     case MULT_EXPR:
6950     case TRUNC_DIV_EXPR:
6951     case CEIL_DIV_EXPR:
6952     case FLOOR_DIV_EXPR:
6953     case ROUND_DIV_EXPR:
6954     case TRUNC_MOD_EXPR:
6955     case CEIL_MOD_EXPR:
6956     case ROUND_MOD_EXPR:
6957     case RDIV_EXPR:
6958     case EXACT_DIV_EXPR:
6959     case MIN_EXPR:
6960     case MAX_EXPR:
6961     case LSHIFT_EXPR:
6962     case RSHIFT_EXPR:
6963     case LROTATE_EXPR:
6964     case RROTATE_EXPR:
6965     case BIT_IOR_EXPR:
6966     case BIT_XOR_EXPR:
6967     case BIT_AND_EXPR:
6968     case TRUTH_XOR_EXPR:
6969     case LT_EXPR:
6970     case LE_EXPR:
6971     case GT_EXPR:
6972     case GE_EXPR:
6973     case EQ_EXPR:
6974     case NE_EXPR:
6975     case UNORDERED_EXPR:
6976     case ORDERED_EXPR:
6977     case UNLT_EXPR:
6978     case UNLE_EXPR:
6979     case UNGT_EXPR:
6980     case UNGE_EXPR:
6981     case UNEQ_EXPR:
6982     case RANGE_EXPR:
6983     case COMPLEX_EXPR:
6984       r = cxx_eval_binary_expression (call, t, allow_non_constant, addr,
6985                                       non_constant_p);
6986       break;
6987
6988       /* fold can introduce non-IF versions of these; still treat them as
6989          short-circuiting.  */
6990     case TRUTH_AND_EXPR:
6991     case TRUTH_ANDIF_EXPR:
6992       r = cxx_eval_logical_expression (call, t, boolean_false_node,
6993                                        boolean_true_node,
6994                                        allow_non_constant, addr,
6995                                        non_constant_p);
6996       break;
6997
6998     case TRUTH_OR_EXPR:
6999     case TRUTH_ORIF_EXPR:
7000       r = cxx_eval_logical_expression (call, t, boolean_true_node,
7001                                        boolean_false_node,
7002                                        allow_non_constant, addr,
7003                                        non_constant_p);
7004       break;
7005
7006     case ARRAY_REF:
7007       r = cxx_eval_array_reference (call, t, allow_non_constant, addr,
7008                                     non_constant_p);
7009       break;
7010
7011     case COMPONENT_REF:
7012       r = cxx_eval_component_reference (call, t, allow_non_constant, addr,
7013                                         non_constant_p);
7014       break;
7015
7016     case BIT_FIELD_REF:
7017       r = cxx_eval_bit_field_ref (call, t, allow_non_constant, addr,
7018                                   non_constant_p);
7019       break;
7020
7021     case COND_EXPR:
7022     case VEC_COND_EXPR:
7023       r = cxx_eval_conditional_expression (call, t, allow_non_constant, addr,
7024                                            non_constant_p);
7025       break;
7026
7027     case CONSTRUCTOR:
7028       r = cxx_eval_bare_aggregate (call, t, allow_non_constant, addr,
7029                                    non_constant_p);
7030       break;
7031
7032     case VEC_INIT_EXPR:
7033       /* We can get this in a defaulted constructor for a class with a
7034          non-static data member of array type.  Either the initializer will
7035          be NULL, meaning default-initialization, or it will be an lvalue
7036          or xvalue of the same type, meaning direct-initialization from the
7037          corresponding member.  */
7038       r = cxx_eval_vec_init (call, t, allow_non_constant, addr,
7039                              non_constant_p);
7040       break;
7041
7042     case CONVERT_EXPR:
7043     case VIEW_CONVERT_EXPR:
7044     case NOP_EXPR:
7045       {
7046         tree oldop = TREE_OPERAND (t, 0);
7047         tree op = oldop;
7048         tree to = TREE_TYPE (t);
7049         tree source = TREE_TYPE (op);
7050         if (TYPE_PTR_P (source) && ARITHMETIC_TYPE_P (to)
7051             && !(TREE_CODE (op) == COMPONENT_REF
7052                  && TYPE_PTRMEMFUNC_P (TREE_TYPE (TREE_OPERAND (op, 0)))))
7053           {
7054             if (!allow_non_constant)
7055               error ("conversion of expression %qE of pointer type "
7056                      "cannot yield a constant expression", op);
7057             *non_constant_p = true;
7058             return t;
7059           }
7060         op = cxx_eval_constant_expression (call, TREE_OPERAND (t, 0),
7061                                            allow_non_constant, addr,
7062                                            non_constant_p);
7063         if (*non_constant_p)
7064           return t;
7065         if (op == oldop)
7066           /* We didn't fold at the top so we could check for ptr-int
7067              conversion.  */
7068           return fold (t);
7069         r = fold_build1 (TREE_CODE (t), to, op);
7070         /* Conversion of an out-of-range value has implementation-defined
7071            behavior; the language considers it different from arithmetic
7072            overflow, which is undefined.  */
7073         if (TREE_OVERFLOW_P (r) && !TREE_OVERFLOW_P (op))
7074           TREE_OVERFLOW (r) = false;
7075       }
7076       break;
7077
7078     case EMPTY_CLASS_EXPR:
7079       /* This is good enough for a function argument that might not get
7080          used, and they can't do anything with it, so just return it.  */
7081       return t;
7082
7083     case LAMBDA_EXPR:
7084     case DYNAMIC_CAST_EXPR:
7085     case PSEUDO_DTOR_EXPR:
7086     case PREINCREMENT_EXPR:
7087     case POSTINCREMENT_EXPR:
7088     case PREDECREMENT_EXPR:
7089     case POSTDECREMENT_EXPR:
7090     case NEW_EXPR:
7091     case VEC_NEW_EXPR:
7092     case DELETE_EXPR:
7093     case VEC_DELETE_EXPR:
7094     case THROW_EXPR:
7095     case MODIFY_EXPR:
7096     case MODOP_EXPR:
7097       /* GCC internal stuff.  */
7098     case VA_ARG_EXPR:
7099     case OBJ_TYPE_REF:
7100     case WITH_CLEANUP_EXPR:
7101     case STATEMENT_LIST:
7102     case BIND_EXPR:
7103     case NON_DEPENDENT_EXPR:
7104     case BASELINK:
7105     case EXPR_STMT:
7106     case OFFSET_REF:
7107       if (!allow_non_constant)
7108         error_at (EXPR_LOC_OR_HERE (t),
7109                   "expression %qE is not a constant-expression", t);
7110       *non_constant_p = true;
7111       break;
7112
7113     default:
7114       internal_error ("unexpected expression %qE of kind %s", t,
7115                       tree_code_name[TREE_CODE (t)]);
7116       *non_constant_p = true;
7117       break;
7118     }
7119
7120   if (r == error_mark_node)
7121     *non_constant_p = true;
7122
7123   if (*non_constant_p)
7124     return t;
7125   else
7126     return r;
7127 }
7128
7129 static tree
7130 cxx_eval_outermost_constant_expr (tree t, bool allow_non_constant)
7131 {
7132   bool non_constant_p = false;
7133   tree r = cxx_eval_constant_expression (NULL, t, allow_non_constant,
7134                                          false, &non_constant_p);
7135
7136   verify_constant (r, allow_non_constant, &non_constant_p);
7137
7138   if (non_constant_p && !allow_non_constant)
7139     return error_mark_node;
7140   else if (non_constant_p && TREE_CONSTANT (t))
7141     {
7142       /* This isn't actually constant, so unset TREE_CONSTANT.  */
7143       if (EXPR_P (t) || TREE_CODE (t) == CONSTRUCTOR)
7144         r = copy_node (t);
7145       else
7146         r = build_nop (TREE_TYPE (t), t);
7147       TREE_CONSTANT (r) = false;
7148       return r;
7149     }
7150   else if (non_constant_p || r == t)
7151     return t;
7152   else if (TREE_CODE (r) == CONSTRUCTOR && CLASS_TYPE_P (TREE_TYPE (r)))
7153     {
7154       if (TREE_CODE (t) == TARGET_EXPR
7155           && TARGET_EXPR_INITIAL (t) == r)
7156         return t;
7157       else
7158         {
7159           r = get_target_expr (r);
7160           TREE_CONSTANT (r) = true;
7161           return r;
7162         }
7163     }
7164   else
7165     return r;
7166 }
7167
7168 /* Returns true if T is a valid subexpression of a constant expression,
7169    even if it isn't itself a constant expression.  */
7170
7171 bool
7172 is_sub_constant_expr (tree t)
7173 {
7174   bool non_constant_p = false;
7175   cxx_eval_constant_expression (NULL, t, true, false, &non_constant_p);
7176   return !non_constant_p;
7177 }
7178
7179 /* If T represents a constant expression returns its reduced value.
7180    Otherwise return error_mark_node.  If T is dependent, then
7181    return NULL.  */
7182
7183 tree
7184 cxx_constant_value (tree t)
7185 {
7186   return cxx_eval_outermost_constant_expr (t, false);
7187 }
7188
7189 /* If T is a constant expression, returns its reduced value.
7190    Otherwise, if T does not have TREE_CONSTANT set, returns T.
7191    Otherwise, returns a version of T without TREE_CONSTANT.  */
7192
7193 tree
7194 maybe_constant_value (tree t)
7195 {
7196   tree r;
7197
7198   if (type_dependent_expression_p (t)
7199       || type_unknown_p (t)
7200       || !potential_constant_expression (t)
7201       || value_dependent_expression_p (t))
7202     return t;
7203
7204   r = cxx_eval_outermost_constant_expr (t, true);
7205 #ifdef ENABLE_CHECKING
7206   /* cp_tree_equal looks through NOPs, so allow them.  */
7207   gcc_assert (r == t
7208               || CONVERT_EXPR_P (t)
7209               || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
7210               || !cp_tree_equal (r, t));
7211 #endif
7212   return r;
7213 }
7214
7215 /* Like maybe_constant_value, but returns a CONSTRUCTOR directly, rather
7216    than wrapped in a TARGET_EXPR.  */
7217
7218 tree
7219 maybe_constant_init (tree t)
7220 {
7221   t = maybe_constant_value (t);
7222   if (TREE_CODE (t) == TARGET_EXPR)
7223     {
7224       tree init = TARGET_EXPR_INITIAL (t);
7225       if (TREE_CODE (init) == CONSTRUCTOR
7226           && TREE_CONSTANT (init))
7227         t = init;
7228     }
7229   return t;
7230 }
7231
7232 #if 0
7233 /* FIXME see ADDR_EXPR section in potential_constant_expression_1.  */
7234 /* Return true if the object referred to by REF has automatic or thread
7235    local storage.  */
7236
7237 enum { ck_ok, ck_bad, ck_unknown };
7238 static int
7239 check_automatic_or_tls (tree ref)
7240 {
7241   enum machine_mode mode;
7242   HOST_WIDE_INT bitsize, bitpos;
7243   tree offset;
7244   int volatilep = 0, unsignedp = 0;
7245   tree decl = get_inner_reference (ref, &bitsize, &bitpos, &offset,
7246                                    &mode, &unsignedp, &volatilep, false);
7247   duration_kind dk;
7248
7249   /* If there isn't a decl in the middle, we don't know the linkage here,
7250      and this isn't a constant expression anyway.  */
7251   if (!DECL_P (decl))
7252     return ck_unknown;
7253   dk = decl_storage_duration (decl);
7254   return (dk == dk_auto || dk == dk_thread) ? ck_bad : ck_ok;
7255 }
7256 #endif
7257
7258 /* Return true if the DECL designates a builtin function that is
7259    morally constexpr, in the sense that its parameter types and
7260    return type are literal types and the compiler is allowed to
7261    fold its invocations.  */
7262
7263 static bool
7264 morally_constexpr_builtin_function_p (tree decl)
7265 {
7266   tree funtype = TREE_TYPE (decl);
7267   tree t;
7268
7269   if (!is_builtin_fn (decl))
7270     return false;
7271   if (!literal_type_p (TREE_TYPE (funtype)))
7272     return false;
7273   for (t = TYPE_ARG_TYPES (funtype); t != NULL ; t = TREE_CHAIN (t))
7274     {
7275       if (t == void_list_node)
7276         return true;
7277       if (!literal_type_p (TREE_VALUE (t)))
7278         return false;
7279     }
7280   /* We assume no varargs builtins are suitable.  */
7281   return t != NULL;
7282 }
7283
7284 /* Return true if T denotes a potentially constant expression.  Issue
7285    diagnostic as appropriate under control of FLAGS.  If WANT_RVAL is true,
7286    an lvalue-rvalue conversion is implied.
7287
7288    C++0x [expr.const] used to say
7289
7290    6 An expression is a potential constant expression if it is
7291      a constant expression where all occurences of function
7292      parameters are replaced by arbitrary constant expressions
7293      of the appropriate type.
7294
7295    2  A conditional expression is a constant expression unless it
7296       involves one of the following as a potentially evaluated
7297       subexpression (3.2), but subexpressions of logical AND (5.14),
7298       logical OR (5.15), and conditional (5.16) operations that are
7299       not evaluated are not considered.   */
7300
7301 static bool
7302 potential_constant_expression_1 (tree t, bool want_rval, tsubst_flags_t flags)
7303 {
7304   enum { any = false, rval = true };
7305   int i;
7306   tree tmp;
7307
7308   /* C++98 has different rules for the form of a constant expression that
7309      are enforced in the parser, so we can assume that anything that gets
7310      this far is suitable.  */
7311   if (cxx_dialect < cxx0x)
7312     return true;
7313
7314   if (t == error_mark_node)
7315     return false;
7316   if (t == NULL_TREE)
7317     return true;
7318   if (TREE_THIS_VOLATILE (t))
7319     {
7320       if (flags & tf_error)
7321         error ("expression %qE has side-effects", t);
7322       return false;
7323     }
7324   if (CONSTANT_CLASS_P (t))
7325     {
7326       if (TREE_OVERFLOW (t))
7327         {
7328           if (flags & tf_error)
7329             {
7330               permerror (EXPR_LOC_OR_HERE (t),
7331                          "overflow in constant expression");
7332               if (flag_permissive)
7333                 return true;
7334             }
7335           return false;
7336         }
7337       return true;
7338     }
7339
7340   switch (TREE_CODE (t))
7341     {
7342     case FUNCTION_DECL:
7343     case BASELINK:
7344     case TEMPLATE_DECL:
7345     case OVERLOAD:
7346     case TEMPLATE_ID_EXPR:
7347     case LABEL_DECL:
7348     case CONST_DECL:
7349     case SIZEOF_EXPR:
7350     case ALIGNOF_EXPR:
7351     case OFFSETOF_EXPR:
7352     case NOEXCEPT_EXPR:
7353     case TEMPLATE_PARM_INDEX:
7354     case TRAIT_EXPR:
7355     case IDENTIFIER_NODE:
7356       return true;
7357
7358     case PARM_DECL:
7359       /* -- this (5.1) unless it appears as the postfix-expression in a
7360             class member access expression, including the result of the
7361             implicit transformation in the body of the non-static
7362             member function (9.3.1);  */
7363       /* FIXME this restriction seems pointless since the standard dropped
7364          "potential constant expression".  */
7365       if (is_this_parameter (t))
7366         {
7367           if (flags & tf_error)
7368             error ("%qE is not a potential constant expression", t);
7369           return false;
7370         }
7371       return true;
7372
7373     case AGGR_INIT_EXPR:
7374     case CALL_EXPR:
7375       /* -- an invocation of a function other than a constexpr function
7376             or a constexpr constructor.  */
7377       {
7378         tree fun = get_function_named_in_call (t);
7379         const int nargs = call_expr_nargs (t);
7380         i = 0;
7381
7382         if (is_overloaded_fn (fun))
7383           {
7384             if (TREE_CODE (fun) == FUNCTION_DECL)
7385               {
7386                 if (builtin_valid_in_constant_expr_p (fun))
7387                   return true;
7388                 if (!DECL_DECLARED_CONSTEXPR_P (fun)
7389                     && !morally_constexpr_builtin_function_p (fun))
7390                   {
7391                     if (flags & tf_error)
7392                       error ("%qD is not %<constexpr%>", fun);
7393                     return false;
7394                   }
7395                 /* A call to a non-static member function takes the address
7396                    of the object as the first argument.  But in a constant
7397                    expression the address will be folded away, so look
7398                    through it now.  */
7399                 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
7400                     && !DECL_CONSTRUCTOR_P (fun))
7401                   {
7402                     tree x = get_nth_callarg (t, 0);
7403                     if (is_this_parameter (x))
7404                       /* OK.  */;
7405                     else if (!potential_constant_expression_1 (x, rval, flags))
7406                       {
7407                         if (flags & tf_error)
7408                           error ("object argument is not a potential "
7409                                  "constant expression");
7410                         return false;
7411                       }
7412                     i = 1;
7413                   }
7414               }
7415             else
7416               fun = get_first_fn (fun);
7417             /* Skip initial arguments to base constructors.  */
7418             if (DECL_BASE_CONSTRUCTOR_P (fun))
7419               i = num_artificial_parms_for (fun);
7420             fun = DECL_ORIGIN (fun);
7421           }
7422         else
7423           {
7424             if (potential_constant_expression_1 (fun, rval, flags))
7425               /* Might end up being a constant function pointer.  */;
7426             else
7427               {
7428                 if (flags & tf_error)
7429                   error ("%qE is not a function name", fun);
7430                 return false;
7431               }
7432           }
7433         for (; i < nargs; ++i)
7434           {
7435             tree x = get_nth_callarg (t, i);
7436             if (!potential_constant_expression_1 (x, rval, flags))
7437               {
7438                 if (flags & tf_error)
7439                   error ("argument in position %qP is not a "
7440                          "potential constant expression", i);
7441                 return false;
7442               }
7443           }
7444         return true;
7445       }
7446
7447     case NON_LVALUE_EXPR:
7448       /* -- an lvalue-to-rvalue conversion (4.1) unless it is applied to
7449             -- an lvalue of integral type that refers to a non-volatile
7450                const variable or static data member initialized with
7451                constant expressions, or
7452
7453             -- an lvalue of literal type that refers to non-volatile
7454                object defined with constexpr, or that refers to a
7455                sub-object of such an object;  */
7456       return potential_constant_expression_1 (TREE_OPERAND (t, 0), rval, flags);
7457
7458     case VAR_DECL:
7459       if (want_rval && !decl_constant_var_p (t)
7460           && !dependent_type_p (TREE_TYPE (t)))
7461         {
7462           if (flags & tf_error)
7463             non_const_var_error (t);
7464           return false;
7465         }
7466       return true;
7467
7468     case NOP_EXPR:
7469     case CONVERT_EXPR:
7470     case VIEW_CONVERT_EXPR:
7471       /* -- an array-to-pointer conversion that is applied to an lvalue
7472             that designates an object with thread or automatic storage
7473             duration;  FIXME not implemented as it breaks constexpr arrays;
7474             need to fix the standard
7475          -- a type conversion from a pointer or pointer-to-member type
7476             to a literal type.  */
7477       {
7478         tree from = TREE_OPERAND (t, 0);
7479         tree source = TREE_TYPE (from);
7480         tree target = TREE_TYPE (t);
7481         if (TYPE_PTR_P (source) && ARITHMETIC_TYPE_P (target)
7482             && !(TREE_CODE (from) == COMPONENT_REF
7483                  && TYPE_PTRMEMFUNC_P (TREE_TYPE (TREE_OPERAND (from, 0)))))
7484           {
7485             if (flags & tf_error)
7486               error ("conversion of expression %qE of pointer type "
7487                      "cannot yield a constant expression", from);
7488             return false;
7489           }
7490         return (potential_constant_expression_1
7491                 (from, TREE_CODE (t) != VIEW_CONVERT_EXPR, flags));
7492       }
7493
7494     case ADDR_EXPR:
7495       /* -- a unary operator & that is applied to an lvalue that
7496             designates an object with thread or automatic storage
7497             duration;  */
7498       t = TREE_OPERAND (t, 0);
7499 #if 0
7500       /* FIXME adjust when issue 1197 is fully resolved.  For now don't do
7501          any checking here, as we might dereference the pointer later.  If
7502          we remove this code, also remove check_automatic_or_tls.  */
7503       i = check_automatic_or_tls (t);
7504       if (i == ck_ok)
7505         return true;
7506       if (i == ck_bad)
7507         {
7508           if (flags & tf_error)
7509             error ("address-of an object %qE with thread local or "
7510                    "automatic storage is not a constant expression", t);
7511           return false;
7512         }
7513 #endif
7514       return potential_constant_expression_1 (t, any, flags);
7515
7516     case COMPONENT_REF:
7517     case BIT_FIELD_REF:
7518     case ARROW_EXPR:
7519     case OFFSET_REF:
7520       /* -- a class member access unless its postfix-expression is
7521             of literal type or of pointer to literal type.  */
7522       /* This test would be redundant, as it follows from the
7523          postfix-expression being a potential constant expression.  */
7524       return potential_constant_expression_1 (TREE_OPERAND (t, 0),
7525                                               want_rval, flags);
7526
7527     case EXPR_PACK_EXPANSION:
7528       return potential_constant_expression_1 (PACK_EXPANSION_PATTERN (t),
7529                                               want_rval, flags);
7530
7531     case INDIRECT_REF:
7532       {
7533         tree x = TREE_OPERAND (t, 0);
7534         STRIP_NOPS (x);
7535         if (is_this_parameter (x))
7536           {
7537             if (DECL_CONSTRUCTOR_P (DECL_CONTEXT (x)) && want_rval)
7538               {
7539                 if (flags & tf_error)
7540                   sorry ("use of the value of the object being constructed "
7541                          "in a constant expression");
7542                 return false;
7543               }
7544             return true;
7545           }
7546         return potential_constant_expression_1 (x, rval, flags);
7547       }
7548
7549     case LAMBDA_EXPR:
7550     case DYNAMIC_CAST_EXPR:
7551     case PSEUDO_DTOR_EXPR:
7552     case PREINCREMENT_EXPR:
7553     case POSTINCREMENT_EXPR:
7554     case PREDECREMENT_EXPR:
7555     case POSTDECREMENT_EXPR:
7556     case NEW_EXPR:
7557     case VEC_NEW_EXPR:
7558     case DELETE_EXPR:
7559     case VEC_DELETE_EXPR:
7560     case THROW_EXPR:
7561     case MODIFY_EXPR:
7562     case MODOP_EXPR:
7563       /* GCC internal stuff.  */
7564     case VA_ARG_EXPR:
7565     case OBJ_TYPE_REF:
7566     case WITH_CLEANUP_EXPR:
7567     case CLEANUP_POINT_EXPR:
7568     case MUST_NOT_THROW_EXPR:
7569     case TRY_CATCH_EXPR:
7570     case STATEMENT_LIST:
7571       /* Don't bother trying to define a subset of statement-expressions to
7572          be constant-expressions, at least for now.  */
7573     case STMT_EXPR:
7574     case EXPR_STMT:
7575     case BIND_EXPR:
7576       if (flags & tf_error)
7577         error ("expression %qE is not a constant-expression", t);
7578       return false;
7579
7580     case TYPEID_EXPR:
7581       /* -- a typeid expression whose operand is of polymorphic
7582             class type;  */
7583       {
7584         tree e = TREE_OPERAND (t, 0);
7585         if (!TYPE_P (e) && !type_dependent_expression_p (e)
7586             && TYPE_POLYMORPHIC_P (TREE_TYPE (e)))
7587           {
7588             if (flags & tf_error)
7589               error ("typeid-expression is not a constant expression "
7590                      "because %qE is of polymorphic type", e);
7591             return false;
7592           }
7593         return true;
7594       }
7595
7596     case MINUS_EXPR:
7597       /* -- a subtraction where both operands are pointers.   */
7598       if (TYPE_PTR_P (TREE_OPERAND (t, 0))
7599           && TYPE_PTR_P (TREE_OPERAND (t, 1)))
7600         {
7601           if (flags & tf_error)
7602             error ("difference of two pointer expressions is not "
7603                    "a constant expression");
7604           return false;
7605         }
7606       want_rval = true;
7607       goto binary;
7608
7609     case LT_EXPR:
7610     case LE_EXPR:
7611     case GT_EXPR:
7612     case GE_EXPR:
7613     case EQ_EXPR:
7614     case NE_EXPR:
7615       /* -- a relational or equality operator where at least
7616             one of the operands is a pointer.  */
7617       if (TYPE_PTR_P (TREE_OPERAND (t, 0))
7618           || TYPE_PTR_P (TREE_OPERAND (t, 1)))
7619         {
7620           if (flags & tf_error)
7621             error ("pointer comparison expression is not a "
7622                    "constant expression");
7623           return false;
7624         }
7625       want_rval = true;
7626       goto binary;
7627
7628     case REALPART_EXPR:
7629     case IMAGPART_EXPR:
7630     case CONJ_EXPR:
7631     case SAVE_EXPR:
7632     case FIX_TRUNC_EXPR:
7633     case FLOAT_EXPR:
7634     case NEGATE_EXPR:
7635     case ABS_EXPR:
7636     case BIT_NOT_EXPR:
7637     case TRUTH_NOT_EXPR:
7638     case FIXED_CONVERT_EXPR:
7639     case UNARY_PLUS_EXPR:
7640       return potential_constant_expression_1 (TREE_OPERAND (t, 0), rval,
7641                                               flags);
7642
7643     case CAST_EXPR:
7644     case CONST_CAST_EXPR:
7645     case STATIC_CAST_EXPR:
7646     case REINTERPRET_CAST_EXPR:
7647       return (potential_constant_expression_1
7648               (TREE_OPERAND (t, 0),
7649                TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE, flags));
7650
7651     case PAREN_EXPR:
7652     case NON_DEPENDENT_EXPR:
7653       /* For convenience.  */
7654     case RETURN_EXPR:
7655       return potential_constant_expression_1 (TREE_OPERAND (t, 0),
7656                                               want_rval, flags);
7657
7658     case SCOPE_REF:
7659       return potential_constant_expression_1 (TREE_OPERAND (t, 1),
7660                                               want_rval, flags);
7661
7662     case INIT_EXPR:
7663     case TARGET_EXPR:
7664       return potential_constant_expression_1 (TREE_OPERAND (t, 1),
7665                                               rval, flags);
7666
7667     case CONSTRUCTOR:
7668       {
7669         VEC(constructor_elt, gc) *v = CONSTRUCTOR_ELTS (t);
7670         constructor_elt *ce;
7671         for (i = 0; VEC_iterate (constructor_elt, v, i, ce); ++i)
7672           if (!potential_constant_expression_1 (ce->value, want_rval, flags))
7673             return false;
7674         return true;
7675       }
7676
7677     case TREE_LIST:
7678       {
7679         gcc_assert (TREE_PURPOSE (t) == NULL_TREE
7680                     || DECL_P (TREE_PURPOSE (t)));
7681         if (!potential_constant_expression_1 (TREE_VALUE (t), want_rval,
7682                                               flags))
7683           return false;
7684         if (TREE_CHAIN (t) == NULL_TREE)
7685           return true;
7686         return potential_constant_expression_1 (TREE_CHAIN (t), want_rval,
7687                                                 flags);
7688       }
7689
7690     case TRUNC_DIV_EXPR:
7691     case CEIL_DIV_EXPR:
7692     case FLOOR_DIV_EXPR:
7693     case ROUND_DIV_EXPR:
7694     case TRUNC_MOD_EXPR:
7695     case CEIL_MOD_EXPR:
7696     case ROUND_MOD_EXPR:
7697       {
7698         tree denom = TREE_OPERAND (t, 1);
7699         /* We can't call maybe_constant_value on an expression
7700            that hasn't been through fold_non_dependent_expr yet.  */
7701         if (!processing_template_decl)
7702           denom = maybe_constant_value (denom);
7703         if (integer_zerop (denom))
7704           {
7705             if (flags & tf_error)
7706               error ("division by zero is not a constant-expression");
7707             return false;
7708           }
7709         else
7710           {
7711             want_rval = true;
7712             goto binary;
7713           }
7714       }
7715
7716     case COMPOUND_EXPR:
7717       {
7718         /* check_return_expr sometimes wraps a TARGET_EXPR in a
7719            COMPOUND_EXPR; don't get confused.  Also handle EMPTY_CLASS_EXPR
7720            introduced by build_call_a.  */
7721         tree op0 = TREE_OPERAND (t, 0);
7722         tree op1 = TREE_OPERAND (t, 1);
7723         STRIP_NOPS (op1);
7724         if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
7725             || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
7726           return potential_constant_expression_1 (op0, want_rval, flags);
7727         else
7728           goto binary;
7729       }
7730
7731       /* If the first operand is the non-short-circuit constant, look at
7732          the second operand; otherwise we only care about the first one for
7733          potentiality.  */
7734     case TRUTH_AND_EXPR:
7735     case TRUTH_ANDIF_EXPR:
7736       tmp = boolean_true_node;
7737       goto truth;
7738     case TRUTH_OR_EXPR:
7739     case TRUTH_ORIF_EXPR:
7740       tmp = boolean_false_node;
7741     truth:
7742       if (TREE_OPERAND (t, 0) == tmp)
7743         return potential_constant_expression_1 (TREE_OPERAND (t, 1), rval, flags);
7744       else
7745         return potential_constant_expression_1 (TREE_OPERAND (t, 0), rval, flags);
7746
7747     case PLUS_EXPR:
7748     case MULT_EXPR:
7749     case POINTER_PLUS_EXPR:
7750     case RDIV_EXPR:
7751     case EXACT_DIV_EXPR:
7752     case MIN_EXPR:
7753     case MAX_EXPR:
7754     case LSHIFT_EXPR:
7755     case RSHIFT_EXPR:
7756     case LROTATE_EXPR:
7757     case RROTATE_EXPR:
7758     case BIT_IOR_EXPR:
7759     case BIT_XOR_EXPR:
7760     case BIT_AND_EXPR:
7761     case TRUTH_XOR_EXPR:
7762     case UNORDERED_EXPR:
7763     case ORDERED_EXPR:
7764     case UNLT_EXPR:
7765     case UNLE_EXPR:
7766     case UNGT_EXPR:
7767     case UNGE_EXPR:
7768     case UNEQ_EXPR:
7769     case RANGE_EXPR:
7770     case COMPLEX_EXPR:
7771       want_rval = true;
7772       /* Fall through.  */
7773     case ARRAY_REF:
7774     case ARRAY_RANGE_REF:
7775     case MEMBER_REF:
7776     case DOTSTAR_EXPR:
7777     binary:
7778       for (i = 0; i < 2; ++i)
7779         if (!potential_constant_expression_1 (TREE_OPERAND (t, i),
7780                                               want_rval, flags))
7781           return false;
7782       return true;
7783
7784     case COND_EXPR:
7785     case VEC_COND_EXPR:
7786       /* If the condition is a known constant, we know which of the legs we
7787          care about; otherwise we only require that the condition and
7788          either of the legs be potentially constant.  */
7789       tmp = TREE_OPERAND (t, 0);
7790       if (!potential_constant_expression_1 (tmp, rval, flags))
7791         return false;
7792       else if (tmp == boolean_true_node)
7793         return potential_constant_expression_1 (TREE_OPERAND (t, 1),
7794                                                 want_rval, flags);
7795       else if (tmp == boolean_false_node)
7796         return potential_constant_expression_1 (TREE_OPERAND (t, 2),
7797                                                 want_rval, flags);
7798       for (i = 1; i < 3; ++i)
7799         if (potential_constant_expression_1 (TREE_OPERAND (t, i),
7800                                              want_rval, tf_none))
7801           return true;
7802       if (flags & tf_error)
7803         error ("expression %qE is not a constant-expression", t);
7804       return false;
7805
7806     case VEC_INIT_EXPR:
7807       if (VEC_INIT_EXPR_IS_CONSTEXPR (t))
7808         return true;
7809       if (flags & tf_error)
7810         {
7811           error ("non-constant array initialization");
7812           diagnose_non_constexpr_vec_init (t);
7813         }
7814       return false;
7815
7816     default:
7817       sorry ("unexpected ast of kind %s", tree_code_name[TREE_CODE (t)]);
7818       gcc_unreachable();
7819       return false;
7820     }
7821 }
7822
7823 /* The main entry point to the above.  */
7824
7825 bool
7826 potential_constant_expression (tree t)
7827 {
7828   return potential_constant_expression_1 (t, false, tf_none);
7829 }
7830
7831 /* As above, but require a constant rvalue.  */
7832
7833 bool
7834 potential_rvalue_constant_expression (tree t)
7835 {
7836   return potential_constant_expression_1 (t, true, tf_none);
7837 }
7838
7839 /* Like above, but complain about non-constant expressions.  */
7840
7841 bool
7842 require_potential_constant_expression (tree t)
7843 {
7844   return potential_constant_expression_1 (t, false, tf_warning_or_error);
7845 }
7846
7847 /* Cross product of the above.  */
7848
7849 bool
7850 require_potential_rvalue_constant_expression (tree t)
7851 {
7852   return potential_constant_expression_1 (t, true, tf_warning_or_error);
7853 }
7854 \f
7855 /* Constructor for a lambda expression.  */
7856
7857 tree
7858 build_lambda_expr (void)
7859 {
7860   tree lambda = make_node (LAMBDA_EXPR);
7861   LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (lambda) = CPLD_NONE;
7862   LAMBDA_EXPR_CAPTURE_LIST         (lambda) = NULL_TREE;
7863   LAMBDA_EXPR_THIS_CAPTURE         (lambda) = NULL_TREE;
7864   LAMBDA_EXPR_RETURN_TYPE          (lambda) = NULL_TREE;
7865   LAMBDA_EXPR_MUTABLE_P            (lambda) = false;
7866   return lambda;
7867 }
7868
7869 /* Create the closure object for a LAMBDA_EXPR.  */
7870
7871 tree
7872 build_lambda_object (tree lambda_expr)
7873 {
7874   /* Build aggregate constructor call.
7875      - cp_parser_braced_list
7876      - cp_parser_functional_cast  */
7877   VEC(constructor_elt,gc) *elts = NULL;
7878   tree node, expr, type;
7879   location_t saved_loc;
7880
7881   if (processing_template_decl)
7882     return lambda_expr;
7883
7884   /* Make sure any error messages refer to the lambda-introducer.  */
7885   saved_loc = input_location;
7886   input_location = LAMBDA_EXPR_LOCATION (lambda_expr);
7887
7888   for (node = LAMBDA_EXPR_CAPTURE_LIST (lambda_expr);
7889        node;
7890        node = TREE_CHAIN (node))
7891     {
7892       tree field = TREE_PURPOSE (node);
7893       tree val = TREE_VALUE (node);
7894
7895       if (field == error_mark_node)
7896         {
7897           expr = error_mark_node;
7898           goto out;
7899         }
7900
7901       if (DECL_P (val))
7902         mark_used (val);
7903
7904       /* Mere mortals can't copy arrays with aggregate initialization, so
7905          do some magic to make it work here.  */
7906       if (TREE_CODE (TREE_TYPE (field)) == ARRAY_TYPE)
7907         val = build_array_copy (val);
7908       else if (DECL_NORMAL_CAPTURE_P (field)
7909                && TREE_CODE (TREE_TYPE (field)) != REFERENCE_TYPE)
7910         {
7911           /* "the entities that are captured by copy are used to
7912              direct-initialize each corresponding non-static data
7913              member of the resulting closure object."
7914
7915              There's normally no way to express direct-initialization
7916              from an element of a CONSTRUCTOR, so we build up a special
7917              TARGET_EXPR to bypass the usual copy-initialization.  */
7918           val = force_rvalue (val);
7919           if (TREE_CODE (val) == TARGET_EXPR)
7920             TARGET_EXPR_DIRECT_INIT_P (val) = true;
7921         }
7922
7923       CONSTRUCTOR_APPEND_ELT (elts, DECL_NAME (field), val);
7924     }
7925
7926   expr = build_constructor (init_list_type_node, elts);
7927   CONSTRUCTOR_IS_DIRECT_INIT (expr) = 1;
7928
7929   /* N2927: "[The closure] class type is not an aggregate."
7930      But we briefly treat it as an aggregate to make this simpler.  */
7931   type = TREE_TYPE (lambda_expr);
7932   CLASSTYPE_NON_AGGREGATE (type) = 0;
7933   expr = finish_compound_literal (type, expr, tf_warning_or_error);
7934   CLASSTYPE_NON_AGGREGATE (type) = 1;
7935
7936  out:
7937   input_location = saved_loc;
7938   return expr;
7939 }
7940
7941 /* Return an initialized RECORD_TYPE for LAMBDA.
7942    LAMBDA must have its explicit captures already.  */
7943
7944 tree
7945 begin_lambda_type (tree lambda)
7946 {
7947   tree type;
7948
7949   {
7950     /* Unique name.  This is just like an unnamed class, but we cannot use
7951        make_anon_name because of certain checks against TYPE_ANONYMOUS_P.  */
7952     tree name;
7953     name = make_lambda_name ();
7954
7955     /* Create the new RECORD_TYPE for this lambda.  */
7956     type = xref_tag (/*tag_code=*/record_type,
7957                      name,
7958                      /*scope=*/ts_within_enclosing_non_class,
7959                      /*template_header_p=*/false);
7960   }
7961
7962   /* Designate it as a struct so that we can use aggregate initialization.  */
7963   CLASSTYPE_DECLARED_CLASS (type) = false;
7964
7965   /* Clear base types.  */
7966   xref_basetypes (type, /*bases=*/NULL_TREE);
7967
7968   /* Start the class.  */
7969   type = begin_class_definition (type, /*attributes=*/NULL_TREE);
7970
7971   /* Cross-reference the expression and the type.  */
7972   TREE_TYPE (lambda) = type;
7973   CLASSTYPE_LAMBDA_EXPR (type) = lambda;
7974
7975   return type;
7976 }
7977
7978 /* Returns the type to use for the return type of the operator() of a
7979    closure class.  */
7980
7981 tree
7982 lambda_return_type (tree expr)
7983 {
7984   tree type;
7985   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
7986     {
7987       warning (0, "cannot deduce lambda return type from a braced-init-list");
7988       return void_type_node;
7989     }
7990   if (type_dependent_expression_p (expr))
7991     {
7992       type = cxx_make_type (DECLTYPE_TYPE);
7993       DECLTYPE_TYPE_EXPR (type) = expr;
7994       DECLTYPE_FOR_LAMBDA_RETURN (type) = true;
7995       SET_TYPE_STRUCTURAL_EQUALITY (type);
7996     }
7997   else
7998     type = type_decays_to (unlowered_expr_type (expr));
7999   return type;
8000 }
8001
8002 /* Given a LAMBDA_EXPR or closure type LAMBDA, return the op() of the
8003    closure type.  */
8004
8005 tree
8006 lambda_function (tree lambda)
8007 {
8008   tree type;
8009   if (TREE_CODE (lambda) == LAMBDA_EXPR)
8010     type = TREE_TYPE (lambda);
8011   else
8012     type = lambda;
8013   gcc_assert (LAMBDA_TYPE_P (type));
8014   /* Don't let debug_tree cause instantiation.  */
8015   if (CLASSTYPE_TEMPLATE_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
8016     return NULL_TREE;
8017   lambda = lookup_member (type, ansi_opname (CALL_EXPR),
8018                           /*protect=*/0, /*want_type=*/false);
8019   if (lambda)
8020     lambda = BASELINK_FUNCTIONS (lambda);
8021   return lambda;
8022 }
8023
8024 /* Returns the type to use for the FIELD_DECL corresponding to the
8025    capture of EXPR.
8026    The caller should add REFERENCE_TYPE for capture by reference.  */
8027
8028 tree
8029 lambda_capture_field_type (tree expr)
8030 {
8031   tree type;
8032   if (type_dependent_expression_p (expr))
8033     {
8034       type = cxx_make_type (DECLTYPE_TYPE);
8035       DECLTYPE_TYPE_EXPR (type) = expr;
8036       DECLTYPE_FOR_LAMBDA_CAPTURE (type) = true;
8037       SET_TYPE_STRUCTURAL_EQUALITY (type);
8038     }
8039   else
8040     type = non_reference (unlowered_expr_type (expr));
8041   return type;
8042 }
8043
8044 /* Recompute the return type for LAMBDA with body of the form:
8045      { return EXPR ; }  */
8046
8047 void
8048 apply_lambda_return_type (tree lambda, tree return_type)
8049 {
8050   tree fco = lambda_function (lambda);
8051   tree result;
8052
8053   LAMBDA_EXPR_RETURN_TYPE (lambda) = return_type;
8054
8055   /* If we got a DECLTYPE_TYPE, don't stick it in the function yet,
8056      it would interfere with instantiating the closure type.  */
8057   if (dependent_type_p (return_type))
8058     return;
8059   if (return_type == error_mark_node)
8060     return;
8061
8062   /* TREE_TYPE (FUNCTION_DECL) == METHOD_TYPE
8063      TREE_TYPE (METHOD_TYPE)   == return-type  */
8064   TREE_TYPE (fco) = change_return_type (return_type, TREE_TYPE (fco));
8065
8066   result = DECL_RESULT (fco);
8067   if (result == NULL_TREE)
8068     return;
8069
8070   /* We already have a DECL_RESULT from start_preparsed_function.
8071      Now we need to redo the work it and allocate_struct_function
8072      did to reflect the new type.  */
8073   result = build_decl (input_location, RESULT_DECL, NULL_TREE,
8074                        TYPE_MAIN_VARIANT (return_type));
8075   DECL_ARTIFICIAL (result) = 1;
8076   DECL_IGNORED_P (result) = 1;
8077   cp_apply_type_quals_to_decl (cp_type_quals (return_type),
8078                                result);
8079
8080   DECL_RESULT (fco) = result;
8081
8082   if (!processing_template_decl && aggregate_value_p (result, fco))
8083     {
8084 #ifdef PCC_STATIC_STRUCT_RETURN
8085       cfun->returns_pcc_struct = 1;
8086 #endif
8087       cfun->returns_struct = 1;
8088     }
8089
8090 }
8091
8092 /* DECL is a local variable or parameter from the surrounding scope of a
8093    lambda-expression.  Returns the decltype for a use of the capture field
8094    for DECL even if it hasn't been captured yet.  */
8095
8096 static tree
8097 capture_decltype (tree decl)
8098 {
8099   tree lam = CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (current_function_decl));
8100   /* FIXME do lookup instead of list walk? */
8101   tree cap = value_member (decl, LAMBDA_EXPR_CAPTURE_LIST (lam));
8102   tree type;
8103
8104   if (cap)
8105     type = TREE_TYPE (TREE_PURPOSE (cap));
8106   else
8107     switch (LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (lam))
8108       {
8109       case CPLD_NONE:
8110         error ("%qD is not captured", decl);
8111         return error_mark_node;
8112
8113       case CPLD_COPY:
8114         type = TREE_TYPE (decl);
8115         if (TREE_CODE (type) == REFERENCE_TYPE
8116             && TREE_CODE (TREE_TYPE (type)) != FUNCTION_TYPE)
8117           type = TREE_TYPE (type);
8118         break;
8119
8120       case CPLD_REFERENCE:
8121         type = TREE_TYPE (decl);
8122         if (TREE_CODE (type) != REFERENCE_TYPE)
8123           type = build_reference_type (TREE_TYPE (decl));
8124         break;
8125
8126       default:
8127         gcc_unreachable ();
8128       }
8129
8130   if (TREE_CODE (type) != REFERENCE_TYPE)
8131     {
8132       if (!LAMBDA_EXPR_MUTABLE_P (lam))
8133         type = cp_build_qualified_type (type, (cp_type_quals (type)
8134                                                |TYPE_QUAL_CONST));
8135       type = build_reference_type (type);
8136     }
8137   return type;
8138 }
8139
8140 /* From an ID and INITIALIZER, create a capture (by reference if
8141    BY_REFERENCE_P is true), add it to the capture-list for LAMBDA,
8142    and return it.  */
8143
8144 tree
8145 add_capture (tree lambda, tree id, tree initializer, bool by_reference_p,
8146              bool explicit_init_p)
8147 {
8148   tree type;
8149   tree member;
8150
8151   type = lambda_capture_field_type (initializer);
8152   if (by_reference_p)
8153     {
8154       type = build_reference_type (type);
8155       if (!real_lvalue_p (initializer))
8156         error ("cannot capture %qE by reference", initializer);
8157     }
8158
8159   /* Make member variable.  */
8160   member = build_lang_decl (FIELD_DECL, id, type);
8161   if (!explicit_init_p)
8162     /* Normal captures are invisible to name lookup but uses are replaced
8163        with references to the capture field; we implement this by only
8164        really making them invisible in unevaluated context; see
8165        qualify_lookup.  For now, let's make explicitly initialized captures
8166        always visible.  */
8167     DECL_NORMAL_CAPTURE_P (member) = true;
8168
8169   /* Add it to the appropriate closure class if we've started it.  */
8170   if (current_class_type && current_class_type == TREE_TYPE (lambda))
8171     finish_member_declaration (member);
8172
8173   LAMBDA_EXPR_CAPTURE_LIST (lambda)
8174     = tree_cons (member, initializer, LAMBDA_EXPR_CAPTURE_LIST (lambda));
8175
8176   if (id == get_identifier ("__this"))
8177     {
8178       if (LAMBDA_EXPR_CAPTURES_THIS_P (lambda))
8179         error ("already captured %<this%> in lambda expression");
8180       LAMBDA_EXPR_THIS_CAPTURE (lambda) = member;
8181     }
8182
8183   return member;
8184 }
8185
8186 /* Register all the capture members on the list CAPTURES, which is the
8187    LAMBDA_EXPR_CAPTURE_LIST for the lambda after the introducer.  */
8188
8189 void register_capture_members (tree captures)
8190 {
8191   if (captures)
8192     {
8193       register_capture_members (TREE_CHAIN (captures));
8194       finish_member_declaration (TREE_PURPOSE (captures));
8195     }
8196 }
8197
8198 /* Given a FIELD_DECL decl belonging to a closure type, return a
8199    COMPONENT_REF of it relative to the 'this' parameter of the op() for
8200    that type.  */
8201
8202 static tree
8203 thisify_lambda_field (tree decl)
8204 {
8205   tree context = lambda_function (DECL_CONTEXT (decl));
8206   tree object = cp_build_indirect_ref (DECL_ARGUMENTS (context),
8207                                        RO_NULL,
8208                                        tf_warning_or_error);
8209   return finish_non_static_data_member (decl, object,
8210                                         /*qualifying_scope*/NULL_TREE);
8211 }
8212
8213 /* Similar to add_capture, except this works on a stack of nested lambdas.
8214    BY_REFERENCE_P in this case is derived from the default capture mode.
8215    Returns the capture for the lambda at the bottom of the stack.  */
8216
8217 tree
8218 add_default_capture (tree lambda_stack, tree id, tree initializer)
8219 {
8220   bool this_capture_p = (id == get_identifier ("__this"));
8221
8222   tree member = NULL_TREE;
8223
8224   tree saved_class_type = current_class_type;
8225
8226   tree node;
8227
8228   for (node = lambda_stack;
8229        node;
8230        node = TREE_CHAIN (node))
8231     {
8232       tree lambda = TREE_VALUE (node);
8233
8234       current_class_type = TREE_TYPE (lambda);
8235       member = add_capture (lambda,
8236                             id,
8237                             initializer,
8238                             /*by_reference_p=*/
8239                             (!this_capture_p
8240                              && (LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (lambda)
8241                                  == CPLD_REFERENCE)),
8242                             /*explicit_init_p=*/false);
8243       initializer = thisify_lambda_field (member);
8244     }
8245
8246   current_class_type = saved_class_type;
8247
8248   return member;
8249 }
8250
8251 /* Return the capture pertaining to a use of 'this' in LAMBDA, in the form of an
8252    INDIRECT_REF, possibly adding it through default capturing.  */
8253
8254 tree
8255 lambda_expr_this_capture (tree lambda)
8256 {
8257   tree result;
8258
8259   tree this_capture = LAMBDA_EXPR_THIS_CAPTURE (lambda);
8260
8261   /* Try to default capture 'this' if we can.  */
8262   if (!this_capture
8263       && LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (lambda) != CPLD_NONE)
8264     {
8265       tree containing_function = TYPE_CONTEXT (TREE_TYPE (lambda));
8266       tree lambda_stack = tree_cons (NULL_TREE, lambda, NULL_TREE);
8267       tree init = NULL_TREE;
8268
8269       /* If we are in a lambda function, we can move out until we hit:
8270            1. a non-lambda function,
8271            2. a lambda function capturing 'this', or
8272            3. a non-default capturing lambda function.  */
8273       while (LAMBDA_FUNCTION_P (containing_function))
8274         {
8275           tree lambda
8276             = CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (containing_function));
8277
8278           if (LAMBDA_EXPR_THIS_CAPTURE (lambda))
8279             {
8280               /* An outer lambda has already captured 'this'.  */
8281               tree cap = LAMBDA_EXPR_THIS_CAPTURE (lambda);
8282               init = thisify_lambda_field (cap);
8283               break;
8284             }
8285
8286           if (LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (lambda) == CPLD_NONE)
8287             /* An outer lambda won't let us capture 'this'.  */
8288             break;
8289
8290           lambda_stack = tree_cons (NULL_TREE,
8291                                     lambda,
8292                                     lambda_stack);
8293
8294           containing_function = decl_function_context (containing_function);
8295         }
8296
8297       if (!init && DECL_NONSTATIC_MEMBER_FUNCTION_P (containing_function)
8298           && !LAMBDA_FUNCTION_P (containing_function))
8299         /* First parameter is 'this'.  */
8300         init = DECL_ARGUMENTS (containing_function);
8301
8302       if (init)
8303         this_capture = add_default_capture (lambda_stack,
8304                                             /*id=*/get_identifier ("__this"),
8305                                             init);
8306     }
8307
8308   if (!this_capture)
8309     {
8310       error ("%<this%> was not captured for this lambda function");
8311       result = error_mark_node;
8312     }
8313   else
8314     {
8315       /* To make sure that current_class_ref is for the lambda.  */
8316       gcc_assert (TYPE_MAIN_VARIANT (TREE_TYPE (current_class_ref)) == TREE_TYPE (lambda));
8317
8318       result = finish_non_static_data_member (this_capture,
8319                                               NULL_TREE,
8320                                               /*qualifying_scope=*/NULL_TREE);
8321
8322       /* If 'this' is captured, each use of 'this' is transformed into an
8323          access to the corresponding unnamed data member of the closure
8324          type cast (_expr.cast_ 5.4) to the type of 'this'. [ The cast
8325          ensures that the transformed expression is an rvalue. ] */
8326       result = rvalue (result);
8327     }
8328
8329   return result;
8330 }
8331
8332 /* Returns the method basetype of the innermost non-lambda function, or
8333    NULL_TREE if none.  */
8334
8335 tree
8336 nonlambda_method_basetype (void)
8337 {
8338   tree fn, type;
8339   if (!current_class_ref)
8340     return NULL_TREE;
8341
8342   type = current_class_type;
8343   if (!LAMBDA_TYPE_P (type))
8344     return type;
8345
8346   /* Find the nearest enclosing non-lambda function.  */
8347   fn = TYPE_NAME (type);
8348   do
8349     fn = decl_function_context (fn);
8350   while (fn && LAMBDA_FUNCTION_P (fn));
8351
8352   if (!fn || !DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
8353     return NULL_TREE;
8354
8355   return TYPE_METHOD_BASETYPE (TREE_TYPE (fn));
8356 }
8357
8358 /* If the closure TYPE has a static op(), also add a conversion to function
8359    pointer.  */
8360
8361 void
8362 maybe_add_lambda_conv_op (tree type)
8363 {
8364   bool nested = (current_function_decl != NULL_TREE);
8365   tree callop = lambda_function (type);
8366   tree rettype, name, fntype, fn, body, compound_stmt;
8367   tree thistype, stattype, statfn, convfn, call, arg;
8368   VEC (tree, gc) *argvec;
8369
8370   if (LAMBDA_EXPR_CAPTURE_LIST (CLASSTYPE_LAMBDA_EXPR (type)) != NULL_TREE)
8371     return;
8372
8373   stattype = build_function_type (TREE_TYPE (TREE_TYPE (callop)),
8374                                   FUNCTION_ARG_CHAIN (callop));
8375
8376   /* First build up the conversion op.  */
8377
8378   rettype = build_pointer_type (stattype);
8379   name = mangle_conv_op_name_for_type (rettype);
8380   thistype = cp_build_qualified_type (type, TYPE_QUAL_CONST);
8381   fntype = build_method_type_directly (thistype, rettype, void_list_node);
8382   fn = convfn = build_lang_decl (FUNCTION_DECL, name, fntype);
8383   DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (callop);
8384
8385   if (TARGET_PTRMEMFUNC_VBIT_LOCATION == ptrmemfunc_vbit_in_pfn
8386       && DECL_ALIGN (fn) < 2 * BITS_PER_UNIT)
8387     DECL_ALIGN (fn) = 2 * BITS_PER_UNIT;
8388
8389   SET_OVERLOADED_OPERATOR_CODE (fn, TYPE_EXPR);
8390   grokclassfn (type, fn, NO_SPECIAL);
8391   set_linkage_according_to_type (type, fn);
8392   rest_of_decl_compilation (fn, toplevel_bindings_p (), at_eof);
8393   DECL_IN_AGGR_P (fn) = 1;
8394   DECL_ARTIFICIAL (fn) = 1;
8395   DECL_NOT_REALLY_EXTERN (fn) = 1;
8396   DECL_DECLARED_INLINE_P (fn) = 1;
8397   DECL_ARGUMENTS (fn) = build_this_parm (fntype, TYPE_QUAL_CONST);
8398   if (nested)
8399     DECL_INTERFACE_KNOWN (fn) = 1;
8400
8401   add_method (type, fn, NULL_TREE);
8402
8403   /* Generic thunk code fails for varargs; we'll complain in mark_used if
8404      the conversion op is used.  */
8405   if (varargs_function_p (callop))
8406     {
8407       DECL_DELETED_FN (fn) = 1;
8408       return;
8409     }
8410
8411   /* Now build up the thunk to be returned.  */
8412
8413   name = get_identifier ("_FUN");
8414   fn = statfn = build_lang_decl (FUNCTION_DECL, name, stattype);
8415   DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (callop);
8416   if (TARGET_PTRMEMFUNC_VBIT_LOCATION == ptrmemfunc_vbit_in_pfn
8417       && DECL_ALIGN (fn) < 2 * BITS_PER_UNIT)
8418     DECL_ALIGN (fn) = 2 * BITS_PER_UNIT;
8419   grokclassfn (type, fn, NO_SPECIAL);
8420   set_linkage_according_to_type (type, fn);
8421   rest_of_decl_compilation (fn, toplevel_bindings_p (), at_eof);
8422   DECL_IN_AGGR_P (fn) = 1;
8423   DECL_ARTIFICIAL (fn) = 1;
8424   DECL_NOT_REALLY_EXTERN (fn) = 1;
8425   DECL_DECLARED_INLINE_P (fn) = 1;
8426   DECL_STATIC_FUNCTION_P (fn) = 1;
8427   DECL_ARGUMENTS (fn) = copy_list (DECL_CHAIN (DECL_ARGUMENTS (callop)));
8428   for (arg = DECL_ARGUMENTS (fn); arg; arg = DECL_CHAIN (arg))
8429     DECL_CONTEXT (arg) = fn;
8430   if (nested)
8431     DECL_INTERFACE_KNOWN (fn) = 1;
8432
8433   add_method (type, fn, NULL_TREE);
8434
8435   if (nested)
8436     push_function_context ();
8437
8438   /* Generate the body of the thunk.  */
8439
8440   start_preparsed_function (statfn, NULL_TREE,
8441                             SF_PRE_PARSED | SF_INCLASS_INLINE);
8442   if (DECL_ONE_ONLY (statfn))
8443     {
8444       /* Put the thunk in the same comdat group as the call op.  */
8445       struct cgraph_node *callop_node, *thunk_node;
8446       DECL_COMDAT_GROUP (statfn) = DECL_COMDAT_GROUP (callop);
8447       callop_node = cgraph_node (callop);
8448       thunk_node = cgraph_node (statfn);
8449       gcc_assert (callop_node->same_comdat_group == NULL);
8450       gcc_assert (thunk_node->same_comdat_group == NULL);
8451       callop_node->same_comdat_group = thunk_node;
8452       thunk_node->same_comdat_group = callop_node;
8453     }
8454   body = begin_function_body ();
8455   compound_stmt = begin_compound_stmt (0);
8456
8457   arg = build1 (NOP_EXPR, TREE_TYPE (DECL_ARGUMENTS (callop)),
8458                 null_pointer_node);
8459   argvec = make_tree_vector ();
8460   VEC_quick_push (tree, argvec, arg);
8461   for (arg = DECL_ARGUMENTS (statfn); arg; arg = DECL_CHAIN (arg))
8462     VEC_safe_push (tree, gc, argvec, arg);
8463   call = build_call_a (callop, VEC_length (tree, argvec),
8464                        VEC_address (tree, argvec));
8465   CALL_FROM_THUNK_P (call) = 1;
8466   if (MAYBE_CLASS_TYPE_P (TREE_TYPE (call)))
8467     call = build_cplus_new (TREE_TYPE (call), call, tf_warning_or_error);
8468   call = convert_from_reference (call);
8469   finish_return_stmt (call);
8470
8471   finish_compound_stmt (compound_stmt);
8472   finish_function_body (body);
8473
8474   expand_or_defer_fn (finish_function (2));
8475
8476   /* Generate the body of the conversion op.  */
8477
8478   start_preparsed_function (convfn, NULL_TREE,
8479                             SF_PRE_PARSED | SF_INCLASS_INLINE);
8480   body = begin_function_body ();
8481   compound_stmt = begin_compound_stmt (0);
8482
8483   finish_return_stmt (decay_conversion (statfn));
8484
8485   finish_compound_stmt (compound_stmt);
8486   finish_function_body (body);
8487
8488   expand_or_defer_fn (finish_function (2));
8489
8490   if (nested)
8491     pop_function_context ();
8492 }
8493 #include "gt-cp-semantics.h"