OSDN Git Service

PR c++/51662
[pf3gnuchains/gcc-fork.git] / gcc / go / gofrontend / statements.cc
1 // statements.cc -- Go frontend statements.
2
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
6
7 #include "go-system.h"
8
9 #include <gmp.h>
10
11 #ifndef ENABLE_BUILD_WITH_CXX
12 extern "C"
13 {
14 #endif
15
16 #include "intl.h"
17 #include "tree.h"
18 #include "gimple.h"
19 #include "convert.h"
20 #include "tree-iterator.h"
21 #include "tree-flow.h"
22 #include "real.h"
23
24 #ifndef ENABLE_BUILD_WITH_CXX
25 }
26 #endif
27
28 #include "go-c.h"
29 #include "types.h"
30 #include "expressions.h"
31 #include "gogo.h"
32 #include "statements.h"
33
34 // Class Statement.
35
36 Statement::Statement(Statement_classification classification,
37                      source_location location)
38   : classification_(classification), location_(location)
39 {
40 }
41
42 Statement::~Statement()
43 {
44 }
45
46 // Traverse the tree.  The work of walking the components is handled
47 // by the subclasses.
48
49 int
50 Statement::traverse(Block* block, size_t* pindex, Traverse* traverse)
51 {
52   if (this->classification_ == STATEMENT_ERROR)
53     return TRAVERSE_CONTINUE;
54
55   unsigned int traverse_mask = traverse->traverse_mask();
56
57   if ((traverse_mask & Traverse::traverse_statements) != 0)
58     {
59       int t = traverse->statement(block, pindex, this);
60       if (t == TRAVERSE_EXIT)
61         return TRAVERSE_EXIT;
62       else if (t == TRAVERSE_SKIP_COMPONENTS)
63         return TRAVERSE_CONTINUE;
64     }
65
66   // No point in checking traverse_mask here--a statement may contain
67   // other blocks or statements, and if we got here we always want to
68   // walk them.
69   return this->do_traverse(traverse);
70 }
71
72 // Traverse the contents of a statement.
73
74 int
75 Statement::traverse_contents(Traverse* traverse)
76 {
77   return this->do_traverse(traverse);
78 }
79
80 // Traverse assignments.
81
82 bool
83 Statement::traverse_assignments(Traverse_assignments* tassign)
84 {
85   if (this->classification_ == STATEMENT_ERROR)
86     return false;
87   return this->do_traverse_assignments(tassign);
88 }
89
90 // Traverse an expression in a statement.  This is a helper function
91 // for child classes.
92
93 int
94 Statement::traverse_expression(Traverse* traverse, Expression** expr)
95 {
96   if ((traverse->traverse_mask()
97        & (Traverse::traverse_types | Traverse::traverse_expressions)) == 0)
98     return TRAVERSE_CONTINUE;
99   return Expression::traverse(expr, traverse);
100 }
101
102 // Traverse an expression list in a statement.  This is a helper
103 // function for child classes.
104
105 int
106 Statement::traverse_expression_list(Traverse* traverse,
107                                     Expression_list* expr_list)
108 {
109   if (expr_list == NULL)
110     return TRAVERSE_CONTINUE;
111   if ((traverse->traverse_mask()
112        & (Traverse::traverse_types | Traverse::traverse_expressions)) == 0)
113     return TRAVERSE_CONTINUE;
114   return expr_list->traverse(traverse);
115 }
116
117 // Traverse a type in a statement.  This is a helper function for
118 // child classes.
119
120 int
121 Statement::traverse_type(Traverse* traverse, Type* type)
122 {
123   if ((traverse->traverse_mask()
124        & (Traverse::traverse_types | Traverse::traverse_expressions)) == 0)
125     return TRAVERSE_CONTINUE;
126   return Type::traverse(type, traverse);
127 }
128
129 // Set type information for unnamed constants.  This is really done by
130 // the child class.
131
132 void
133 Statement::determine_types()
134 {
135   this->do_determine_types();
136 }
137
138 // If this is a thunk statement, return it.
139
140 Thunk_statement*
141 Statement::thunk_statement()
142 {
143   Thunk_statement* ret = this->convert<Thunk_statement, STATEMENT_GO>();
144   if (ret == NULL)
145     ret = this->convert<Thunk_statement, STATEMENT_DEFER>();
146   return ret;
147 }
148
149 // Get a tree for a Statement.  This is really done by the child
150 // class.
151
152 tree
153 Statement::get_tree(Translate_context* context)
154 {
155   if (this->classification_ == STATEMENT_ERROR)
156     return error_mark_node;
157
158   return this->do_get_tree(context);
159 }
160
161 // Build tree nodes and set locations.
162
163 tree
164 Statement::build_stmt_1(int tree_code_value, tree node)
165 {
166   tree ret = build1(static_cast<tree_code>(tree_code_value),
167                     void_type_node, node);
168   SET_EXPR_LOCATION(ret, this->location_);
169   return ret;
170 }
171
172 // Note that this statement is erroneous.  This is called by children
173 // when they discover an error.
174
175 void
176 Statement::set_is_error()
177 {
178   this->classification_ = STATEMENT_ERROR;
179 }
180
181 // For children to call to report an error conveniently.
182
183 void
184 Statement::report_error(const char* msg)
185 {
186   error_at(this->location_, "%s", msg);
187   this->set_is_error();
188 }
189
190 // An error statement, used to avoid crashing after we report an
191 // error.
192
193 class Error_statement : public Statement
194 {
195  public:
196   Error_statement(source_location location)
197     : Statement(STATEMENT_ERROR, location)
198   { }
199
200  protected:
201   int
202   do_traverse(Traverse*)
203   { return TRAVERSE_CONTINUE; }
204
205   tree
206   do_get_tree(Translate_context*)
207   { gcc_unreachable(); }
208 };
209
210 // Make an error statement.
211
212 Statement*
213 Statement::make_error_statement(source_location location)
214 {
215   return new Error_statement(location);
216 }
217
218 // Class Variable_declaration_statement.
219
220 Variable_declaration_statement::Variable_declaration_statement(
221     Named_object* var)
222   : Statement(STATEMENT_VARIABLE_DECLARATION, var->var_value()->location()),
223     var_(var)
224 {
225 }
226
227 // We don't actually traverse the variable here; it was traversed
228 // while traversing the Block.
229
230 int
231 Variable_declaration_statement::do_traverse(Traverse*)
232 {
233   return TRAVERSE_CONTINUE;
234 }
235
236 // Traverse the assignments in a variable declaration.  Note that this
237 // traversal is different from the usual traversal.
238
239 bool
240 Variable_declaration_statement::do_traverse_assignments(
241     Traverse_assignments* tassign)
242 {
243   tassign->initialize_variable(this->var_);
244   return true;
245 }
246
247 // Return the tree for a variable declaration.
248
249 tree
250 Variable_declaration_statement::do_get_tree(Translate_context* context)
251 {
252   tree val = this->var_->get_tree(context->gogo(), context->function());
253   if (val == error_mark_node || TREE_TYPE(val) == error_mark_node)
254     return error_mark_node;
255   Variable* variable = this->var_->var_value();
256
257   tree init = variable->get_init_tree(context->gogo(), context->function());
258   if (init == error_mark_node)
259     return error_mark_node;
260
261   // If this variable lives on the heap, we need to allocate it now.
262   if (!variable->is_in_heap())
263     {
264       DECL_INITIAL(val) = init;
265       return this->build_stmt_1(DECL_EXPR, val);
266     }
267   else
268     {
269       gcc_assert(TREE_CODE(val) == INDIRECT_REF);
270       tree decl = TREE_OPERAND(val, 0);
271       gcc_assert(TREE_CODE(decl) == VAR_DECL);
272       tree type = TREE_TYPE(decl);
273       gcc_assert(POINTER_TYPE_P(type));
274       tree size = TYPE_SIZE_UNIT(TREE_TYPE(type));
275       tree space = context->gogo()->allocate_memory(variable->type(), size,
276                                                     this->location());
277       space = fold_convert(TREE_TYPE(decl), space);
278       DECL_INITIAL(decl) = space;
279       return build2(COMPOUND_EXPR, void_type_node,
280                     this->build_stmt_1(DECL_EXPR, decl),
281                     build2(MODIFY_EXPR, void_type_node, val, init));
282     }
283 }
284
285 // Make a variable declaration.
286
287 Statement*
288 Statement::make_variable_declaration(Named_object* var)
289 {
290   return new Variable_declaration_statement(var);
291 }
292
293 // Class Temporary_statement.
294
295 // Return the type of the temporary variable.
296
297 Type*
298 Temporary_statement::type() const
299 {
300   return this->type_ != NULL ? this->type_ : this->init_->type();
301 }
302
303 // Return the tree for the temporary variable.
304
305 tree
306 Temporary_statement::get_decl() const
307 {
308   if (this->decl_ == NULL)
309     {
310       gcc_assert(saw_errors());
311       return error_mark_node;
312     }
313   return this->decl_;
314 }
315
316 // Traversal.
317
318 int
319 Temporary_statement::do_traverse(Traverse* traverse)
320 {
321   if (this->type_ != NULL
322       && this->traverse_type(traverse, this->type_) == TRAVERSE_EXIT)
323     return TRAVERSE_EXIT;
324   if (this->init_ == NULL)
325     return TRAVERSE_CONTINUE;
326   else
327     return this->traverse_expression(traverse, &this->init_);
328 }
329
330 // Traverse assignments.
331
332 bool
333 Temporary_statement::do_traverse_assignments(Traverse_assignments* tassign)
334 {
335   if (this->init_ == NULL)
336     return false;
337   tassign->value(&this->init_, true, true);
338   return true;
339 }
340
341 // Determine types.
342
343 void
344 Temporary_statement::do_determine_types()
345 {
346   if (this->type_ != NULL && this->type_->is_abstract())
347     this->type_ = this->type_->make_non_abstract_type();
348
349   if (this->init_ != NULL)
350     {
351       if (this->type_ == NULL)
352         this->init_->determine_type_no_context();
353       else
354         {
355           Type_context context(this->type_, false);
356           this->init_->determine_type(&context);
357         }
358     }
359
360   if (this->type_ == NULL)
361     {
362       this->type_ = this->init_->type();
363       gcc_assert(!this->type_->is_abstract());
364     }
365 }
366
367 // Check types.
368
369 void
370 Temporary_statement::do_check_types(Gogo*)
371 {
372   if (this->type_ != NULL && this->init_ != NULL)
373     {
374       std::string reason;
375       if (!Type::are_assignable(this->type_, this->init_->type(), &reason))
376         {
377           if (reason.empty())
378             error_at(this->location(), "incompatible types in assignment");
379           else
380             error_at(this->location(), "incompatible types in assignment (%s)",
381                      reason.c_str());
382           this->set_is_error();
383         }
384     }
385 }
386
387 // Return a tree.
388
389 tree
390 Temporary_statement::do_get_tree(Translate_context* context)
391 {
392   gcc_assert(this->decl_ == NULL_TREE);
393   tree type_tree = this->type()->get_tree(context->gogo());
394   tree init_tree = (this->init_ == NULL
395                     ? NULL_TREE
396                     : this->init_->get_tree(context));
397   if (type_tree == error_mark_node || init_tree == error_mark_node)
398     {
399       this->decl_ = error_mark_node;
400       return error_mark_node;
401     }
402   // We can only use create_tmp_var if the type is not addressable.
403   if (!TREE_ADDRESSABLE(type_tree))
404     {
405       this->decl_ = create_tmp_var(type_tree, "GOTMP");
406       DECL_SOURCE_LOCATION(this->decl_) = this->location();
407     }
408   else
409     {
410       gcc_assert(context->function() != NULL && context->block() != NULL);
411       tree decl = build_decl(this->location(), VAR_DECL,
412                              create_tmp_var_name("GOTMP"),
413                              type_tree);
414       DECL_ARTIFICIAL(decl) = 1;
415       DECL_IGNORED_P(decl) = 1;
416       TREE_USED(decl) = 1;
417       gcc_assert(current_function_decl != NULL_TREE);
418       DECL_CONTEXT(decl) = current_function_decl;
419
420       // We have to add this variable to the block so that it winds up
421       // in a BIND_EXPR.
422       tree block_tree = context->block_tree();
423       gcc_assert(block_tree != NULL_TREE);
424       DECL_CHAIN(decl) = BLOCK_VARS(block_tree);
425       BLOCK_VARS(block_tree) = decl;
426
427       this->decl_ = decl;
428     }
429   if (init_tree != NULL_TREE)
430     DECL_INITIAL(this->decl_) =
431       Expression::convert_for_assignment(context, this->type(),
432                                          this->init_->type(), init_tree,
433                                          this->location());
434   if (this->is_address_taken_)
435     TREE_ADDRESSABLE(this->decl_) = 1;
436   return this->build_stmt_1(DECL_EXPR, this->decl_);
437 }
438
439 // Make and initialize a temporary variable in BLOCK.
440
441 Temporary_statement*
442 Statement::make_temporary(Type* type, Expression* init,
443                           source_location location)
444 {
445   return new Temporary_statement(type, init, location);
446 }
447
448 // An assignment statement.
449
450 class Assignment_statement : public Statement
451 {
452  public:
453   Assignment_statement(Expression* lhs, Expression* rhs,
454                        source_location location)
455     : Statement(STATEMENT_ASSIGNMENT, location),
456       lhs_(lhs), rhs_(rhs)
457   { }
458
459  protected:
460   int
461   do_traverse(Traverse* traverse);
462
463   bool
464   do_traverse_assignments(Traverse_assignments*);
465
466   void
467   do_determine_types();
468
469   void
470   do_check_types(Gogo*);
471
472   tree
473   do_get_tree(Translate_context*);
474
475  private:
476   // Left hand side--the lvalue.
477   Expression* lhs_;
478   // Right hand side--the rvalue.
479   Expression* rhs_;
480 };
481
482 // Traversal.
483
484 int
485 Assignment_statement::do_traverse(Traverse* traverse)
486 {
487   if (this->traverse_expression(traverse, &this->lhs_) == TRAVERSE_EXIT)
488     return TRAVERSE_EXIT;
489   return this->traverse_expression(traverse, &this->rhs_);
490 }
491
492 bool
493 Assignment_statement::do_traverse_assignments(Traverse_assignments* tassign)
494 {
495   tassign->assignment(&this->lhs_, &this->rhs_);
496   return true;
497 }
498
499 // Set types for the assignment.
500
501 void
502 Assignment_statement::do_determine_types()
503 {
504   this->lhs_->determine_type_no_context();
505   Type_context context(this->lhs_->type(), false);
506   this->rhs_->determine_type(&context);
507 }
508
509 // Check types for an assignment.
510
511 void
512 Assignment_statement::do_check_types(Gogo*)
513 {
514   // The left hand side must be either addressable, a map index
515   // expression, or the blank identifier.
516   if (!this->lhs_->is_addressable()
517       && this->lhs_->map_index_expression() == NULL
518       && !this->lhs_->is_sink_expression())
519     {
520       if (!this->lhs_->type()->is_error_type())
521         this->report_error(_("invalid left hand side of assignment"));
522       return;
523     }
524
525   Type* lhs_type = this->lhs_->type();
526   Type* rhs_type = this->rhs_->type();
527   std::string reason;
528   if (!Type::are_assignable(lhs_type, rhs_type, &reason))
529     {
530       if (reason.empty())
531         error_at(this->location(), "incompatible types in assignment");
532       else
533         error_at(this->location(), "incompatible types in assignment (%s)",
534                  reason.c_str());
535       this->set_is_error();
536     }
537
538   if (lhs_type->is_error_type()
539       || rhs_type->is_error_type()
540       || lhs_type->is_undefined()
541       || rhs_type->is_undefined())
542     {
543       // Make sure we get the error for an undefined type.
544       lhs_type->base();
545       rhs_type->base();
546       this->set_is_error();
547     }
548 }
549
550 // Build a tree for an assignment statement.
551
552 tree
553 Assignment_statement::do_get_tree(Translate_context* context)
554 {
555   tree rhs_tree = this->rhs_->get_tree(context);
556
557   if (this->lhs_->is_sink_expression())
558     return rhs_tree;
559
560   tree lhs_tree = this->lhs_->get_tree(context);
561
562   if (lhs_tree == error_mark_node || rhs_tree == error_mark_node)
563     return error_mark_node;
564
565   rhs_tree = Expression::convert_for_assignment(context, this->lhs_->type(),
566                                                 this->rhs_->type(), rhs_tree,
567                                                 this->location());
568   if (rhs_tree == error_mark_node)
569     return error_mark_node;
570
571   return fold_build2_loc(this->location(), MODIFY_EXPR, void_type_node,
572                          lhs_tree, rhs_tree);
573 }
574
575 // Make an assignment statement.
576
577 Statement*
578 Statement::make_assignment(Expression* lhs, Expression* rhs,
579                            source_location location)
580 {
581   return new Assignment_statement(lhs, rhs, location);
582 }
583
584 // The Move_ordered_evals class is used to find any subexpressions of
585 // an expression that have an evaluation order dependency.  It creates
586 // temporary variables to hold them.
587
588 class Move_ordered_evals : public Traverse
589 {
590  public:
591   Move_ordered_evals(Block* block)
592     : Traverse(traverse_expressions),
593       block_(block)
594   { }
595
596  protected:
597   int
598   expression(Expression**);
599
600  private:
601   // The block where new temporary variables should be added.
602   Block* block_;
603 };
604
605 int
606 Move_ordered_evals::expression(Expression** pexpr)
607 {
608   // We have to look at subexpressions first.
609   if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
610     return TRAVERSE_EXIT;
611   if ((*pexpr)->must_eval_in_order())
612     {
613       source_location loc = (*pexpr)->location();
614       Temporary_statement* temp = Statement::make_temporary(NULL, *pexpr, loc);
615       this->block_->add_statement(temp);
616       *pexpr = Expression::make_temporary_reference(temp, loc);
617     }
618   return TRAVERSE_SKIP_COMPONENTS;
619 }
620
621 // An assignment operation statement.
622
623 class Assignment_operation_statement : public Statement
624 {
625  public:
626   Assignment_operation_statement(Operator op, Expression* lhs, Expression* rhs,
627                                  source_location location)
628     : Statement(STATEMENT_ASSIGNMENT_OPERATION, location),
629       op_(op), lhs_(lhs), rhs_(rhs)
630   { }
631
632  protected:
633   int
634   do_traverse(Traverse*);
635
636   bool
637   do_traverse_assignments(Traverse_assignments*)
638   { gcc_unreachable(); }
639
640   Statement*
641   do_lower(Gogo*, Block*);
642
643   tree
644   do_get_tree(Translate_context*)
645   { gcc_unreachable(); }
646
647  private:
648   // The operator (OPERATOR_PLUSEQ, etc.).
649   Operator op_;
650   // Left hand side.
651   Expression* lhs_;
652   // Right hand side.
653   Expression* rhs_;
654 };
655
656 // Traversal.
657
658 int
659 Assignment_operation_statement::do_traverse(Traverse* traverse)
660 {
661   if (this->traverse_expression(traverse, &this->lhs_) == TRAVERSE_EXIT)
662     return TRAVERSE_EXIT;
663   return this->traverse_expression(traverse, &this->rhs_);
664 }
665
666 // Lower an assignment operation statement to a regular assignment
667 // statement.
668
669 Statement*
670 Assignment_operation_statement::do_lower(Gogo*, Block* enclosing)
671 {
672   source_location loc = this->location();
673
674   // We have to evaluate the left hand side expression only once.  We
675   // do this by moving out any expression with side effects.
676   Block* b = new Block(enclosing, loc);
677   Move_ordered_evals moe(b);
678   this->lhs_->traverse_subexpressions(&moe);
679
680   Expression* lval = this->lhs_->copy();
681
682   Operator op;
683   switch (this->op_)
684     {
685     case OPERATOR_PLUSEQ:
686       op = OPERATOR_PLUS;
687       break;
688     case OPERATOR_MINUSEQ:
689       op = OPERATOR_MINUS;
690       break;
691     case OPERATOR_OREQ:
692       op = OPERATOR_OR;
693       break;
694     case OPERATOR_XOREQ:
695       op = OPERATOR_XOR;
696       break;
697     case OPERATOR_MULTEQ:
698       op = OPERATOR_MULT;
699       break;
700     case OPERATOR_DIVEQ:
701       op = OPERATOR_DIV;
702       break;
703     case OPERATOR_MODEQ:
704       op = OPERATOR_MOD;
705       break;
706     case OPERATOR_LSHIFTEQ:
707       op = OPERATOR_LSHIFT;
708       break;
709     case OPERATOR_RSHIFTEQ:
710       op = OPERATOR_RSHIFT;
711       break;
712     case OPERATOR_ANDEQ:
713       op = OPERATOR_AND;
714       break;
715     case OPERATOR_BITCLEAREQ:
716       op = OPERATOR_BITCLEAR;
717       break;
718     default:
719       gcc_unreachable();
720     }
721
722   Expression* binop = Expression::make_binary(op, lval, this->rhs_, loc);
723   Statement* s = Statement::make_assignment(this->lhs_, binop, loc);
724   if (b->statements()->empty())
725     {
726       delete b;
727       return s;
728     }
729   else
730     {
731       b->add_statement(s);
732       return Statement::make_block_statement(b, loc);
733     }
734 }
735
736 // Make an assignment operation statement.
737
738 Statement*
739 Statement::make_assignment_operation(Operator op, Expression* lhs,
740                                      Expression* rhs, source_location location)
741 {
742   return new Assignment_operation_statement(op, lhs, rhs, location);
743 }
744
745 // A tuple assignment statement.  This differs from an assignment
746 // statement in that the right-hand-side expressions are evaluated in
747 // parallel.
748
749 class Tuple_assignment_statement : public Statement
750 {
751  public:
752   Tuple_assignment_statement(Expression_list* lhs, Expression_list* rhs,
753                              source_location location)
754     : Statement(STATEMENT_TUPLE_ASSIGNMENT, location),
755       lhs_(lhs), rhs_(rhs)
756   { }
757
758  protected:
759   int
760   do_traverse(Traverse* traverse);
761
762   bool
763   do_traverse_assignments(Traverse_assignments*)
764   { gcc_unreachable(); }
765
766   Statement*
767   do_lower(Gogo*, Block*);
768
769   tree
770   do_get_tree(Translate_context*)
771   { gcc_unreachable(); }
772
773  private:
774   // Left hand side--a list of lvalues.
775   Expression_list* lhs_;
776   // Right hand side--a list of rvalues.
777   Expression_list* rhs_;
778 };
779
780 // Traversal.
781
782 int
783 Tuple_assignment_statement::do_traverse(Traverse* traverse)
784 {
785   if (this->traverse_expression_list(traverse, this->lhs_) == TRAVERSE_EXIT)
786     return TRAVERSE_EXIT;
787   return this->traverse_expression_list(traverse, this->rhs_);
788 }
789
790 // Lower a tuple assignment.  We use temporary variables to split it
791 // up into a set of single assignments.
792
793 Statement*
794 Tuple_assignment_statement::do_lower(Gogo*, Block* enclosing)
795 {
796   source_location loc = this->location();
797
798   Block* b = new Block(enclosing, loc);
799   
800   // First move out any subexpressions on the left hand side.  The
801   // right hand side will be evaluated in the required order anyhow.
802   Move_ordered_evals moe(b);
803   for (Expression_list::const_iterator plhs = this->lhs_->begin();
804        plhs != this->lhs_->end();
805        ++plhs)
806     (*plhs)->traverse_subexpressions(&moe);
807
808   std::vector<Temporary_statement*> temps;
809   temps.reserve(this->lhs_->size());
810
811   Expression_list::const_iterator prhs = this->rhs_->begin();
812   for (Expression_list::const_iterator plhs = this->lhs_->begin();
813        plhs != this->lhs_->end();
814        ++plhs, ++prhs)
815     {
816       gcc_assert(prhs != this->rhs_->end());
817
818       if ((*plhs)->is_error_expression()
819           || (*plhs)->type()->is_error_type()
820           || (*prhs)->is_error_expression()
821           || (*prhs)->type()->is_error_type())
822         continue;
823
824       if ((*plhs)->is_sink_expression())
825         {
826           b->add_statement(Statement::make_statement(*prhs));
827           continue;
828         }
829
830       Temporary_statement* temp = Statement::make_temporary((*plhs)->type(),
831                                                             *prhs, loc);
832       b->add_statement(temp);
833       temps.push_back(temp);
834
835     }
836   gcc_assert(prhs == this->rhs_->end());
837
838   prhs = this->rhs_->begin();
839   std::vector<Temporary_statement*>::const_iterator ptemp = temps.begin();
840   for (Expression_list::const_iterator plhs = this->lhs_->begin();
841        plhs != this->lhs_->end();
842        ++plhs, ++prhs)
843     {
844       if ((*plhs)->is_error_expression()
845           || (*plhs)->type()->is_error_type()
846           || (*prhs)->is_error_expression()
847           || (*prhs)->type()->is_error_type())
848         continue;
849
850       if ((*plhs)->is_sink_expression())
851         continue;
852
853       Expression* ref = Expression::make_temporary_reference(*ptemp, loc);
854       Statement* s = Statement::make_assignment(*plhs, ref, loc);
855       b->add_statement(s);
856       ++ptemp;
857     }
858   gcc_assert(ptemp == temps.end());
859
860   return Statement::make_block_statement(b, loc);
861 }
862
863 // Make a tuple assignment statement.
864
865 Statement*
866 Statement::make_tuple_assignment(Expression_list* lhs, Expression_list* rhs,
867                                  source_location location)
868 {
869   return new Tuple_assignment_statement(lhs, rhs, location);
870 }
871
872 // A tuple assignment from a map index expression.
873 //   v, ok = m[k]
874
875 class Tuple_map_assignment_statement : public Statement
876 {
877 public:
878   Tuple_map_assignment_statement(Expression* val, Expression* present,
879                                  Expression* map_index,
880                                  source_location location)
881     : Statement(STATEMENT_TUPLE_MAP_ASSIGNMENT, location),
882       val_(val), present_(present), map_index_(map_index)
883   { }
884
885  protected:
886   int
887   do_traverse(Traverse* traverse);
888
889   bool
890   do_traverse_assignments(Traverse_assignments*)
891   { gcc_unreachable(); }
892
893   Statement*
894   do_lower(Gogo*, Block*);
895
896   tree
897   do_get_tree(Translate_context*)
898   { gcc_unreachable(); }
899
900  private:
901   // Lvalue which receives the value from the map.
902   Expression* val_;
903   // Lvalue which receives whether the key value was present.
904   Expression* present_;
905   // The map index expression.
906   Expression* map_index_;
907 };
908
909 // Traversal.
910
911 int
912 Tuple_map_assignment_statement::do_traverse(Traverse* traverse)
913 {
914   if (this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT
915       || this->traverse_expression(traverse, &this->present_) == TRAVERSE_EXIT)
916     return TRAVERSE_EXIT;
917   return this->traverse_expression(traverse, &this->map_index_);
918 }
919
920 // Lower a tuple map assignment.
921
922 Statement*
923 Tuple_map_assignment_statement::do_lower(Gogo*, Block* enclosing)
924 {
925   source_location loc = this->location();
926
927   Map_index_expression* map_index = this->map_index_->map_index_expression();
928   if (map_index == NULL)
929     {
930       this->report_error(_("expected map index on right hand side"));
931       return Statement::make_error_statement(loc);
932     }
933   Map_type* map_type = map_index->get_map_type();
934   if (map_type == NULL)
935     return Statement::make_error_statement(loc);
936
937   Block* b = new Block(enclosing, loc);
938
939   // Move out any subexpressions to make sure that functions are
940   // called in the required order.
941   Move_ordered_evals moe(b);
942   this->val_->traverse_subexpressions(&moe);
943   this->present_->traverse_subexpressions(&moe);
944
945   // Copy the key value into a temporary so that we can take its
946   // address without pushing the value onto the heap.
947
948   // var key_temp KEY_TYPE = MAP_INDEX
949   Temporary_statement* key_temp =
950     Statement::make_temporary(map_type->key_type(), map_index->index(), loc);
951   b->add_statement(key_temp);
952
953   // var val_temp VAL_TYPE
954   Temporary_statement* val_temp =
955     Statement::make_temporary(map_type->val_type(), NULL, loc);
956   b->add_statement(val_temp);
957
958   // var present_temp bool
959   Temporary_statement* present_temp =
960     Statement::make_temporary(Type::lookup_bool_type(), NULL, loc);
961   b->add_statement(present_temp);
962
963   // func mapaccess2(hmap map[k]v, key *k, val *v) bool
964   source_location bloc = BUILTINS_LOCATION;
965   Typed_identifier_list* param_types = new Typed_identifier_list();
966   param_types->push_back(Typed_identifier("hmap", map_type, bloc));
967   Type* pkey_type = Type::make_pointer_type(map_type->key_type());
968   param_types->push_back(Typed_identifier("key", pkey_type, bloc));
969   Type* pval_type = Type::make_pointer_type(map_type->val_type());
970   param_types->push_back(Typed_identifier("val", pval_type, bloc));
971
972   Typed_identifier_list* ret_types = new Typed_identifier_list();
973   ret_types->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
974
975   Function_type* fntype = Type::make_function_type(NULL, param_types,
976                                                    ret_types, bloc);
977   Named_object* mapaccess2 =
978     Named_object::make_function_declaration("mapaccess2", NULL, fntype, bloc);
979   mapaccess2->func_declaration_value()->set_asm_name("runtime.mapaccess2");
980
981   // present_temp = mapaccess2(MAP, &key_temp, &val_temp)
982   Expression* func = Expression::make_func_reference(mapaccess2, NULL, loc);
983   Expression_list* params = new Expression_list();
984   params->push_back(map_index->map());
985   Expression* ref = Expression::make_temporary_reference(key_temp, loc);
986   params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc));
987   ref = Expression::make_temporary_reference(val_temp, loc);
988   params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc));
989   Expression* call = Expression::make_call(func, params, false, loc);
990
991   ref = Expression::make_temporary_reference(present_temp, loc);
992   Statement* s = Statement::make_assignment(ref, call, loc);
993   b->add_statement(s);
994
995   // val = val_temp
996   ref = Expression::make_temporary_reference(val_temp, loc);
997   s = Statement::make_assignment(this->val_, ref, loc);
998   b->add_statement(s);
999
1000   // present = present_temp
1001   ref = Expression::make_temporary_reference(present_temp, loc);
1002   s = Statement::make_assignment(this->present_, ref, loc);
1003   b->add_statement(s);
1004
1005   return Statement::make_block_statement(b, loc);
1006 }
1007
1008 // Make a map assignment statement which returns a pair of values.
1009
1010 Statement*
1011 Statement::make_tuple_map_assignment(Expression* val, Expression* present,
1012                                      Expression* map_index,
1013                                      source_location location)
1014 {
1015   return new Tuple_map_assignment_statement(val, present, map_index, location);
1016 }
1017
1018 // Assign a pair of entries to a map.
1019 //   m[k] = v, p
1020
1021 class Map_assignment_statement : public Statement
1022 {
1023  public:
1024   Map_assignment_statement(Expression* map_index,
1025                            Expression* val, Expression* should_set,
1026                            source_location location)
1027     : Statement(STATEMENT_MAP_ASSIGNMENT, location),
1028       map_index_(map_index), val_(val), should_set_(should_set)
1029   { }
1030
1031  protected:
1032   int
1033   do_traverse(Traverse* traverse);
1034
1035   bool
1036   do_traverse_assignments(Traverse_assignments*)
1037   { gcc_unreachable(); }
1038
1039   Statement*
1040   do_lower(Gogo*, Block*);
1041
1042   tree
1043   do_get_tree(Translate_context*)
1044   { gcc_unreachable(); }
1045
1046  private:
1047   // A reference to the map index which should be set or deleted.
1048   Expression* map_index_;
1049   // The value to add to the map.
1050   Expression* val_;
1051   // Whether or not to add the value.
1052   Expression* should_set_;
1053 };
1054
1055 // Traverse a map assignment.
1056
1057 int
1058 Map_assignment_statement::do_traverse(Traverse* traverse)
1059 {
1060   if (this->traverse_expression(traverse, &this->map_index_) == TRAVERSE_EXIT
1061       || this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT)
1062     return TRAVERSE_EXIT;
1063   return this->traverse_expression(traverse, &this->should_set_);
1064 }
1065
1066 // Lower a map assignment to a function call.
1067
1068 Statement*
1069 Map_assignment_statement::do_lower(Gogo*, Block* enclosing)
1070 {
1071   source_location loc = this->location();
1072
1073   Map_index_expression* map_index = this->map_index_->map_index_expression();
1074   if (map_index == NULL)
1075     {
1076       this->report_error(_("expected map index on left hand side"));
1077       return Statement::make_error_statement(loc);
1078     }
1079   Map_type* map_type = map_index->get_map_type();
1080   if (map_type == NULL)
1081     return Statement::make_error_statement(loc);
1082
1083   Block* b = new Block(enclosing, loc);
1084
1085   // Evaluate the map first to get order of evaluation right.
1086   // map_temp := m // we are evaluating m[k] = v, p
1087   Temporary_statement* map_temp = Statement::make_temporary(map_type,
1088                                                             map_index->map(),
1089                                                             loc);
1090   b->add_statement(map_temp);
1091
1092   // var key_temp MAP_KEY_TYPE = k
1093   Temporary_statement* key_temp =
1094     Statement::make_temporary(map_type->key_type(), map_index->index(), loc);
1095   b->add_statement(key_temp);
1096
1097   // var val_temp MAP_VAL_TYPE = v
1098   Temporary_statement* val_temp =
1099     Statement::make_temporary(map_type->val_type(), this->val_, loc);
1100   b->add_statement(val_temp);
1101
1102   // func mapassign2(hmap map[k]v, key *k, val *v, p)
1103   source_location bloc = BUILTINS_LOCATION;
1104   Typed_identifier_list* param_types = new Typed_identifier_list();
1105   param_types->push_back(Typed_identifier("hmap", map_type, bloc));
1106   Type* pkey_type = Type::make_pointer_type(map_type->key_type());
1107   param_types->push_back(Typed_identifier("key", pkey_type, bloc));
1108   Type* pval_type = Type::make_pointer_type(map_type->val_type());
1109   param_types->push_back(Typed_identifier("val", pval_type, bloc));
1110   param_types->push_back(Typed_identifier("p", Type::lookup_bool_type(), bloc));
1111   Function_type* fntype = Type::make_function_type(NULL, param_types,
1112                                                    NULL, bloc);
1113   Named_object* mapassign2 =
1114     Named_object::make_function_declaration("mapassign2", NULL, fntype, bloc);
1115   mapassign2->func_declaration_value()->set_asm_name("runtime.mapassign2");
1116
1117   // mapassign2(map_temp, &key_temp, &val_temp, p)
1118   Expression* func = Expression::make_func_reference(mapassign2, NULL, loc);
1119   Expression_list* params = new Expression_list();
1120   params->push_back(Expression::make_temporary_reference(map_temp, loc));
1121   Expression* ref = Expression::make_temporary_reference(key_temp, loc);
1122   params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc));
1123   ref = Expression::make_temporary_reference(val_temp, loc);
1124   params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc));
1125   params->push_back(this->should_set_);
1126   Expression* call = Expression::make_call(func, params, false, loc);
1127   Statement* s = Statement::make_statement(call);
1128   b->add_statement(s);
1129
1130   return Statement::make_block_statement(b, loc);
1131 }
1132
1133 // Make a statement which assigns a pair of entries to a map.
1134
1135 Statement*
1136 Statement::make_map_assignment(Expression* map_index,
1137                                Expression* val, Expression* should_set,
1138                                source_location location)
1139 {
1140   return new Map_assignment_statement(map_index, val, should_set, location);
1141 }
1142
1143 // A tuple assignment from a receive statement.
1144
1145 class Tuple_receive_assignment_statement : public Statement
1146 {
1147  public:
1148   Tuple_receive_assignment_statement(Expression* val, Expression* success,
1149                                      Expression* channel,
1150                                      source_location location)
1151     : Statement(STATEMENT_TUPLE_RECEIVE_ASSIGNMENT, location),
1152       val_(val), success_(success), channel_(channel)
1153   { }
1154
1155  protected:
1156   int
1157   do_traverse(Traverse* traverse);
1158
1159   bool
1160   do_traverse_assignments(Traverse_assignments*)
1161   { gcc_unreachable(); }
1162
1163   Statement*
1164   do_lower(Gogo*, Block*);
1165
1166   tree
1167   do_get_tree(Translate_context*)
1168   { gcc_unreachable(); }
1169
1170  private:
1171   // Lvalue which receives the value from the channel.
1172   Expression* val_;
1173   // Lvalue which receives whether the read succeeded or failed.
1174   Expression* success_;
1175   // The channel on which we receive the value.
1176   Expression* channel_;
1177 };
1178
1179 // Traversal.
1180
1181 int
1182 Tuple_receive_assignment_statement::do_traverse(Traverse* traverse)
1183 {
1184   if (this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT
1185       || this->traverse_expression(traverse, &this->success_) == TRAVERSE_EXIT)
1186     return TRAVERSE_EXIT;
1187   return this->traverse_expression(traverse, &this->channel_);
1188 }
1189
1190 // Lower to a function call.
1191
1192 Statement*
1193 Tuple_receive_assignment_statement::do_lower(Gogo*, Block* enclosing)
1194 {
1195   source_location loc = this->location();
1196
1197   Channel_type* channel_type = this->channel_->type()->channel_type();
1198   if (channel_type == NULL)
1199     {
1200       this->report_error(_("expected channel"));
1201       return Statement::make_error_statement(loc);
1202     }
1203   if (!channel_type->may_receive())
1204     {
1205       this->report_error(_("invalid receive on send-only channel"));
1206       return Statement::make_error_statement(loc);
1207     }
1208
1209   Block* b = new Block(enclosing, loc);
1210
1211   // Make sure that any subexpressions on the left hand side are
1212   // evaluated in the right order.
1213   Move_ordered_evals moe(b);
1214   this->val_->traverse_subexpressions(&moe);
1215   this->success_->traverse_subexpressions(&moe);
1216
1217   // var val_temp ELEMENT_TYPE
1218   Temporary_statement* val_temp =
1219     Statement::make_temporary(channel_type->element_type(), NULL, loc);
1220   b->add_statement(val_temp);
1221
1222   // var success_temp bool
1223   Temporary_statement* success_temp =
1224     Statement::make_temporary(Type::lookup_bool_type(), NULL, loc);
1225   b->add_statement(success_temp);
1226
1227   // func chanrecv2(c chan T, val *T) bool
1228   source_location bloc = BUILTINS_LOCATION;
1229   Typed_identifier_list* param_types = new Typed_identifier_list();
1230   param_types->push_back(Typed_identifier("c", channel_type, bloc));
1231   Type* pelement_type = Type::make_pointer_type(channel_type->element_type());
1232   param_types->push_back(Typed_identifier("val", pelement_type, bloc));
1233
1234   Typed_identifier_list* ret_types = new Typed_identifier_list();
1235   ret_types->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1236
1237   Function_type* fntype = Type::make_function_type(NULL, param_types,
1238                                                    ret_types, bloc);
1239   Named_object* chanrecv2 =
1240     Named_object::make_function_declaration("chanrecv2", NULL, fntype, bloc);
1241   chanrecv2->func_declaration_value()->set_asm_name("runtime.chanrecv2");
1242
1243   // success_temp = chanrecv2(channel, &val_temp)
1244   Expression* func = Expression::make_func_reference(chanrecv2, NULL, loc);
1245   Expression_list* params = new Expression_list();
1246   params->push_back(this->channel_);
1247   Expression* ref = Expression::make_temporary_reference(val_temp, loc);
1248   params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc));
1249   Expression* call = Expression::make_call(func, params, false, loc);
1250   ref = Expression::make_temporary_reference(success_temp, loc);
1251   Statement* s = Statement::make_assignment(ref, call, loc);
1252   b->add_statement(s);
1253
1254   // val = val_temp
1255   ref = Expression::make_temporary_reference(val_temp, loc);
1256   s = Statement::make_assignment(this->val_, ref, loc);
1257   b->add_statement(s);
1258
1259   // success = success_temp
1260   ref = Expression::make_temporary_reference(success_temp, loc);
1261   s = Statement::make_assignment(this->success_, ref, loc);
1262   b->add_statement(s);
1263
1264   return Statement::make_block_statement(b, loc);
1265 }
1266
1267 // Make a nonblocking receive statement.
1268
1269 Statement*
1270 Statement::make_tuple_receive_assignment(Expression* val, Expression* success,
1271                                          Expression* channel,
1272                                          source_location location)
1273 {
1274   return new Tuple_receive_assignment_statement(val, success, channel,
1275                                                 location);
1276 }
1277
1278 // An assignment to a pair of values from a type guard.  This is a
1279 // conditional type guard.  v, ok = i.(type).
1280
1281 class Tuple_type_guard_assignment_statement : public Statement
1282 {
1283  public:
1284   Tuple_type_guard_assignment_statement(Expression* val, Expression* ok,
1285                                         Expression* expr, Type* type,
1286                                         source_location location)
1287     : Statement(STATEMENT_TUPLE_TYPE_GUARD_ASSIGNMENT, location),
1288       val_(val), ok_(ok), expr_(expr), type_(type)
1289   { }
1290
1291  protected:
1292   int
1293   do_traverse(Traverse*);
1294
1295   bool
1296   do_traverse_assignments(Traverse_assignments*)
1297   { gcc_unreachable(); }
1298
1299   Statement*
1300   do_lower(Gogo*, Block*);
1301
1302   tree
1303   do_get_tree(Translate_context*)
1304   { gcc_unreachable(); }
1305
1306  private:
1307   Call_expression*
1308   lower_to_empty_interface(const char*);
1309
1310   Call_expression*
1311   lower_to_type(const char*);
1312
1313   void
1314   lower_to_object_type(Block*, const char*);
1315
1316   // The variable which recieves the converted value.
1317   Expression* val_;
1318   // The variable which receives the indication of success.
1319   Expression* ok_;
1320   // The expression being converted.
1321   Expression* expr_;
1322   // The type to which the expression is being converted.
1323   Type* type_;
1324 };
1325
1326 // Traverse a type guard tuple assignment.
1327
1328 int
1329 Tuple_type_guard_assignment_statement::do_traverse(Traverse* traverse)
1330 {
1331   if (this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT
1332       || this->traverse_expression(traverse, &this->ok_) == TRAVERSE_EXIT
1333       || this->traverse_type(traverse, this->type_) == TRAVERSE_EXIT)
1334     return TRAVERSE_EXIT;
1335   return this->traverse_expression(traverse, &this->expr_);
1336 }
1337
1338 // Lower to a function call.
1339
1340 Statement*
1341 Tuple_type_guard_assignment_statement::do_lower(Gogo*, Block* enclosing)
1342 {
1343   source_location loc = this->location();
1344
1345   Type* expr_type = this->expr_->type();
1346   if (expr_type->interface_type() == NULL)
1347     {
1348       if (!expr_type->is_error_type() && !this->type_->is_error_type())
1349         this->report_error(_("type assertion only valid for interface types"));
1350       return Statement::make_error_statement(loc);
1351     }
1352
1353   Block* b = new Block(enclosing, loc);
1354
1355   // Make sure that any subexpressions on the left hand side are
1356   // evaluated in the right order.
1357   Move_ordered_evals moe(b);
1358   this->val_->traverse_subexpressions(&moe);
1359   this->ok_->traverse_subexpressions(&moe);
1360
1361   bool expr_is_empty = expr_type->interface_type()->is_empty();
1362   Call_expression* call;
1363   if (this->type_->interface_type() != NULL)
1364     {
1365       if (this->type_->interface_type()->is_empty())
1366         call = this->lower_to_empty_interface(expr_is_empty
1367                                               ? "ifaceE2E2"
1368                                               : "ifaceI2E2");
1369       else
1370         call = this->lower_to_type(expr_is_empty ? "ifaceE2I2" : "ifaceI2I2");
1371     }
1372   else if (this->type_->points_to() != NULL)
1373     call = this->lower_to_type(expr_is_empty ? "ifaceE2T2P" : "ifaceI2T2P");
1374   else
1375     {
1376       this->lower_to_object_type(b, expr_is_empty ? "ifaceE2T2" : "ifaceI2T2");
1377       call = NULL;
1378     }
1379
1380   if (call != NULL)
1381     {
1382       Expression* res = Expression::make_call_result(call, 0);
1383       Statement* s = Statement::make_assignment(this->val_, res, loc);
1384       b->add_statement(s);
1385
1386       res = Expression::make_call_result(call, 1);
1387       s = Statement::make_assignment(this->ok_, res, loc);
1388       b->add_statement(s);
1389     }
1390
1391   return Statement::make_block_statement(b, loc);
1392 }
1393
1394 // Lower a conversion to an empty interface type.
1395
1396 Call_expression*
1397 Tuple_type_guard_assignment_statement::lower_to_empty_interface(
1398     const char *fnname)
1399 {
1400   source_location loc = this->location();
1401
1402   // func FNNAME(interface) (empty, bool)
1403   source_location bloc = BUILTINS_LOCATION;
1404   Typed_identifier_list* param_types = new Typed_identifier_list();
1405   param_types->push_back(Typed_identifier("i", this->expr_->type(), bloc));
1406   Typed_identifier_list* ret_types = new Typed_identifier_list();
1407   ret_types->push_back(Typed_identifier("ret", this->type_, bloc));
1408   ret_types->push_back(Typed_identifier("ok", Type::lookup_bool_type(), bloc));
1409   Function_type* fntype = Type::make_function_type(NULL, param_types,
1410                                                    ret_types, bloc);
1411   Named_object* fn =
1412     Named_object::make_function_declaration(fnname, NULL, fntype, bloc);
1413   std::string asm_name = "runtime.";
1414   asm_name += fnname;
1415   fn->func_declaration_value()->set_asm_name(asm_name);
1416
1417   // val, ok = FNNAME(expr)
1418   Expression* func = Expression::make_func_reference(fn, NULL, loc);
1419   Expression_list* params = new Expression_list();
1420   params->push_back(this->expr_);
1421   return Expression::make_call(func, params, false, loc);
1422 }
1423
1424 // Lower a conversion to a non-empty interface type or a pointer type.
1425
1426 Call_expression*
1427 Tuple_type_guard_assignment_statement::lower_to_type(const char* fnname)
1428 {
1429   source_location loc = this->location();
1430
1431   // func FNNAME(*descriptor, interface) (interface, bool)
1432   source_location bloc = BUILTINS_LOCATION;
1433   Typed_identifier_list* param_types = new Typed_identifier_list();
1434   param_types->push_back(Typed_identifier("inter",
1435                                           Type::make_type_descriptor_ptr_type(),
1436                                           bloc));
1437   param_types->push_back(Typed_identifier("i", this->expr_->type(), bloc));
1438   Typed_identifier_list* ret_types = new Typed_identifier_list();
1439   ret_types->push_back(Typed_identifier("ret", this->type_, bloc));
1440   ret_types->push_back(Typed_identifier("ok", Type::lookup_bool_type(), bloc));
1441   Function_type* fntype = Type::make_function_type(NULL, param_types,
1442                                                    ret_types, bloc);
1443   Named_object* fn =
1444     Named_object::make_function_declaration(fnname, NULL, fntype, bloc);
1445   std::string asm_name = "runtime.";
1446   asm_name += fnname;
1447   fn->func_declaration_value()->set_asm_name(asm_name);
1448
1449   // val, ok = FNNAME(type_descriptor, expr)
1450   Expression* func = Expression::make_func_reference(fn, NULL, loc);
1451   Expression_list* params = new Expression_list();
1452   params->push_back(Expression::make_type_descriptor(this->type_, loc));
1453   params->push_back(this->expr_);
1454   return Expression::make_call(func, params, false, loc);
1455 }
1456
1457 // Lower a conversion to a non-interface non-pointer type.
1458
1459 void
1460 Tuple_type_guard_assignment_statement::lower_to_object_type(Block* b,
1461                                                             const char *fnname)
1462 {
1463   source_location loc = this->location();
1464
1465   // var val_temp TYPE
1466   Temporary_statement* val_temp = Statement::make_temporary(this->type_,
1467                                                             NULL, loc);
1468   b->add_statement(val_temp);
1469
1470   // func FNNAME(*descriptor, interface, *T) bool
1471   source_location bloc = BUILTINS_LOCATION;
1472   Typed_identifier_list* param_types = new Typed_identifier_list();
1473   param_types->push_back(Typed_identifier("inter",
1474                                           Type::make_type_descriptor_ptr_type(),
1475                                           bloc));
1476   param_types->push_back(Typed_identifier("i", this->expr_->type(), bloc));
1477   Type* ptype = Type::make_pointer_type(this->type_);
1478   param_types->push_back(Typed_identifier("v", ptype, bloc));
1479   Typed_identifier_list* ret_types = new Typed_identifier_list();
1480   ret_types->push_back(Typed_identifier("ok", Type::lookup_bool_type(), bloc));
1481   Function_type* fntype = Type::make_function_type(NULL, param_types,
1482                                                    ret_types, bloc);
1483   Named_object* fn =
1484     Named_object::make_function_declaration(fnname, NULL, fntype, bloc);
1485   std::string asm_name = "runtime.";
1486   asm_name += fnname;
1487   fn->func_declaration_value()->set_asm_name(asm_name);
1488
1489   // ok = FNNAME(type_descriptor, expr, &val_temp)
1490   Expression* func = Expression::make_func_reference(fn, NULL, loc);
1491   Expression_list* params = new Expression_list();
1492   params->push_back(Expression::make_type_descriptor(this->type_, loc));
1493   params->push_back(this->expr_);
1494   Expression* ref = Expression::make_temporary_reference(val_temp, loc);
1495   params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc));
1496   Expression* call = Expression::make_call(func, params, false, loc);
1497   Statement* s = Statement::make_assignment(this->ok_, call, loc);
1498   b->add_statement(s);
1499
1500   // val = val_temp
1501   ref = Expression::make_temporary_reference(val_temp, loc);
1502   s = Statement::make_assignment(this->val_, ref, loc);
1503   b->add_statement(s);
1504 }
1505
1506 // Make an assignment from a type guard to a pair of variables.
1507
1508 Statement*
1509 Statement::make_tuple_type_guard_assignment(Expression* val, Expression* ok,
1510                                             Expression* expr, Type* type,
1511                                             source_location location)
1512 {
1513   return new Tuple_type_guard_assignment_statement(val, ok, expr, type,
1514                                                    location);
1515 }
1516
1517 // An expression statement.
1518
1519 class Expression_statement : public Statement
1520 {
1521  public:
1522   Expression_statement(Expression* expr)
1523     : Statement(STATEMENT_EXPRESSION, expr->location()),
1524       expr_(expr)
1525   { }
1526
1527  protected:
1528   int
1529   do_traverse(Traverse* traverse)
1530   { return this->traverse_expression(traverse, &this->expr_); }
1531
1532   void
1533   do_determine_types()
1534   { this->expr_->determine_type_no_context(); }
1535
1536   bool
1537   do_may_fall_through() const;
1538
1539   tree
1540   do_get_tree(Translate_context* context)
1541   { return this->expr_->get_tree(context); }
1542
1543  private:
1544   Expression* expr_;
1545 };
1546
1547 // An expression statement may fall through unless it is a call to a
1548 // function which does not return.
1549
1550 bool
1551 Expression_statement::do_may_fall_through() const
1552 {
1553   const Call_expression* call = this->expr_->call_expression();
1554   if (call != NULL)
1555     {
1556       const Expression* fn = call->fn();
1557       const Func_expression* fe = fn->func_expression();
1558       if (fe != NULL)
1559         {
1560           const Named_object* no = fe->named_object();
1561
1562           Function_type* fntype;
1563           if (no->is_function())
1564             fntype = no->func_value()->type();
1565           else if (no->is_function_declaration())
1566             fntype = no->func_declaration_value()->type();
1567           else
1568             fntype = NULL;
1569
1570           // The builtin function panic does not return.
1571           if (fntype != NULL && fntype->is_builtin() && no->name() == "panic")
1572             return false;
1573         }
1574     }
1575   return true;
1576 }
1577
1578 // Make an expression statement from an Expression.
1579
1580 Statement*
1581 Statement::make_statement(Expression* expr)
1582 {
1583   return new Expression_statement(expr);
1584 }
1585
1586 // A block statement--a list of statements which may include variable
1587 // definitions.
1588
1589 class Block_statement : public Statement
1590 {
1591  public:
1592   Block_statement(Block* block, source_location location)
1593     : Statement(STATEMENT_BLOCK, location),
1594       block_(block)
1595   { }
1596
1597  protected:
1598   int
1599   do_traverse(Traverse* traverse)
1600   { return this->block_->traverse(traverse); }
1601
1602   void
1603   do_determine_types()
1604   { this->block_->determine_types(); }
1605
1606   bool
1607   do_may_fall_through() const
1608   { return this->block_->may_fall_through(); }
1609
1610   tree
1611   do_get_tree(Translate_context* context)
1612   { return this->block_->get_tree(context); }
1613
1614  private:
1615   Block* block_;
1616 };
1617
1618 // Make a block statement.
1619
1620 Statement*
1621 Statement::make_block_statement(Block* block, source_location location)
1622 {
1623   return new Block_statement(block, location);
1624 }
1625
1626 // An increment or decrement statement.
1627
1628 class Inc_dec_statement : public Statement
1629 {
1630  public:
1631   Inc_dec_statement(bool is_inc, Expression* expr)
1632     : Statement(STATEMENT_INCDEC, expr->location()),
1633       expr_(expr), is_inc_(is_inc)
1634   { }
1635
1636  protected:
1637   int
1638   do_traverse(Traverse* traverse)
1639   { return this->traverse_expression(traverse, &this->expr_); }
1640
1641   bool
1642   do_traverse_assignments(Traverse_assignments*)
1643   { gcc_unreachable(); }
1644
1645   Statement*
1646   do_lower(Gogo*, Block*);
1647
1648   tree
1649   do_get_tree(Translate_context*)
1650   { gcc_unreachable(); }
1651
1652  private:
1653   // The l-value to increment or decrement.
1654   Expression* expr_;
1655   // Whether to increment or decrement.
1656   bool is_inc_;
1657 };
1658
1659 // Lower to += or -=.
1660
1661 Statement*
1662 Inc_dec_statement::do_lower(Gogo*, Block*)
1663 {
1664   source_location loc = this->location();
1665
1666   mpz_t oval;
1667   mpz_init_set_ui(oval, 1UL);
1668   Expression* oexpr = Expression::make_integer(&oval, NULL, loc);
1669   mpz_clear(oval);
1670
1671   Operator op = this->is_inc_ ? OPERATOR_PLUSEQ : OPERATOR_MINUSEQ;
1672   return Statement::make_assignment_operation(op, this->expr_, oexpr, loc);
1673 }
1674
1675 // Make an increment statement.
1676
1677 Statement*
1678 Statement::make_inc_statement(Expression* expr)
1679 {
1680   return new Inc_dec_statement(true, expr);
1681 }
1682
1683 // Make a decrement statement.
1684
1685 Statement*
1686 Statement::make_dec_statement(Expression* expr)
1687 {
1688   return new Inc_dec_statement(false, expr);
1689 }
1690
1691 // Class Thunk_statement.  This is the base class for go and defer
1692 // statements.
1693
1694 const char* const Thunk_statement::thunk_field_fn = "fn";
1695
1696 const char* const Thunk_statement::thunk_field_receiver = "receiver";
1697
1698 // Constructor.
1699
1700 Thunk_statement::Thunk_statement(Statement_classification classification,
1701                                  Call_expression* call,
1702                                  source_location location)
1703     : Statement(classification, location),
1704       call_(call), struct_type_(NULL)
1705 {
1706 }
1707
1708 // Return whether this is a simple statement which does not require a
1709 // thunk.
1710
1711 bool
1712 Thunk_statement::is_simple(Function_type* fntype) const
1713 {
1714   // We need a thunk to call a method, or to pass a variable number of
1715   // arguments.
1716   if (fntype->is_method() || fntype->is_varargs())
1717     return false;
1718
1719   // A defer statement requires a thunk to set up for whether the
1720   // function can call recover.
1721   if (this->classification() == STATEMENT_DEFER)
1722     return false;
1723
1724   // We can only permit a single parameter of pointer type.
1725   const Typed_identifier_list* parameters = fntype->parameters();
1726   if (parameters != NULL
1727       && (parameters->size() > 1
1728           || (parameters->size() == 1
1729               && parameters->begin()->type()->points_to() == NULL)))
1730     return false;
1731
1732   // If the function returns multiple values, or returns a type other
1733   // than integer, floating point, or pointer, then it may get a
1734   // hidden first parameter, in which case we need the more
1735   // complicated approach.  This is true even though we are going to
1736   // ignore the return value.
1737   const Typed_identifier_list* results = fntype->results();
1738   if (results != NULL
1739       && (results->size() > 1
1740           || (results->size() == 1
1741               && !results->begin()->type()->is_basic_type()
1742               && results->begin()->type()->points_to() == NULL)))
1743     return false;
1744
1745   // If this calls something which is not a simple function, then we
1746   // need a thunk.
1747   Expression* fn = this->call_->call_expression()->fn();
1748   if (fn->bound_method_expression() != NULL
1749       || fn->interface_field_reference_expression() != NULL)
1750     return false;
1751
1752   return true;
1753 }
1754
1755 // Traverse a thunk statement.
1756
1757 int
1758 Thunk_statement::do_traverse(Traverse* traverse)
1759 {
1760   return this->traverse_expression(traverse, &this->call_);
1761 }
1762
1763 // We implement traverse_assignment for a thunk statement because it
1764 // effectively copies the function call.
1765
1766 bool
1767 Thunk_statement::do_traverse_assignments(Traverse_assignments* tassign)
1768 {
1769   Expression* fn = this->call_->call_expression()->fn();
1770   Expression* fn2 = fn;
1771   tassign->value(&fn2, true, false);
1772   return true;
1773 }
1774
1775 // Determine types in a thunk statement.
1776
1777 void
1778 Thunk_statement::do_determine_types()
1779 {
1780   this->call_->determine_type_no_context();
1781
1782   // Now that we know the types of the call, build the struct used to
1783   // pass parameters.
1784   Call_expression* ce = this->call_->call_expression();
1785   if (ce == NULL)
1786     return;
1787   Function_type* fntype = ce->get_function_type();
1788   if (fntype != NULL && !this->is_simple(fntype))
1789     this->struct_type_ = this->build_struct(fntype);
1790 }
1791
1792 // Check types in a thunk statement.
1793
1794 void
1795 Thunk_statement::do_check_types(Gogo*)
1796 {
1797   Call_expression* ce = this->call_->call_expression();
1798   if (ce == NULL)
1799     {
1800       if (!this->call_->is_error_expression())
1801         this->report_error("expected call expression");
1802       return;
1803     }
1804   Function_type* fntype = ce->get_function_type();
1805   if (fntype != NULL && fntype->is_method())
1806     {
1807       Expression* fn = ce->fn();
1808       if (fn->bound_method_expression() == NULL
1809           && fn->interface_field_reference_expression() == NULL)
1810         this->report_error(_("no object for method call"));
1811     }
1812 }
1813
1814 // The Traverse class used to find and simplify thunk statements.
1815
1816 class Simplify_thunk_traverse : public Traverse
1817 {
1818  public:
1819   Simplify_thunk_traverse(Gogo* gogo)
1820     : Traverse(traverse_blocks),
1821       gogo_(gogo)
1822   { }
1823
1824   int
1825   block(Block*);
1826
1827  private:
1828   Gogo* gogo_;
1829 };
1830
1831 int
1832 Simplify_thunk_traverse::block(Block* b)
1833 {
1834   // The parser ensures that thunk statements always appear at the end
1835   // of a block.
1836   if (b->statements()->size() < 1)
1837     return TRAVERSE_CONTINUE;
1838   Thunk_statement* stat = b->statements()->back()->thunk_statement();
1839   if (stat == NULL)
1840     return TRAVERSE_CONTINUE;
1841   if (stat->simplify_statement(this->gogo_, b))
1842     return TRAVERSE_SKIP_COMPONENTS;
1843   return TRAVERSE_CONTINUE;
1844 }
1845
1846 // Simplify all thunk statements.
1847
1848 void
1849 Gogo::simplify_thunk_statements()
1850 {
1851   Simplify_thunk_traverse thunk_traverse(this);
1852   this->traverse(&thunk_traverse);
1853 }
1854
1855 // Simplify complex thunk statements into simple ones.  A complicated
1856 // thunk statement is one which takes anything other than zero
1857 // parameters or a single pointer parameter.  We rewrite it into code
1858 // which allocates a struct, stores the parameter values into the
1859 // struct, and does a simple go or defer statement which passes the
1860 // struct to a thunk.  The thunk does the real call.
1861
1862 bool
1863 Thunk_statement::simplify_statement(Gogo* gogo, Block* block)
1864 {
1865   if (this->classification() == STATEMENT_ERROR)
1866     return false;
1867   if (this->call_->is_error_expression())
1868     return false;
1869
1870   Call_expression* ce = this->call_->call_expression();
1871   Function_type* fntype = ce->get_function_type();
1872   if (fntype == NULL)
1873     {
1874       gcc_assert(saw_errors());
1875       this->set_is_error();
1876       return false;
1877     }
1878   if (this->is_simple(fntype))
1879     return false;
1880
1881   Expression* fn = ce->fn();
1882   Bound_method_expression* bound_method = fn->bound_method_expression();
1883   Interface_field_reference_expression* interface_method =
1884     fn->interface_field_reference_expression();
1885   const bool is_method = bound_method != NULL || interface_method != NULL;
1886
1887   source_location location = this->location();
1888
1889   std::string thunk_name = Gogo::thunk_name();
1890
1891   // Build the thunk.
1892   this->build_thunk(gogo, thunk_name, fntype);
1893
1894   // Generate code to call the thunk.
1895
1896   // Get the values to store into the struct which is the single
1897   // argument to the thunk.
1898
1899   Expression_list* vals = new Expression_list();
1900   if (fntype->is_builtin())
1901     ;
1902   else if (!is_method)
1903     vals->push_back(fn);
1904   else if (interface_method != NULL)
1905     vals->push_back(interface_method->expr());
1906   else if (bound_method != NULL)
1907     {
1908       vals->push_back(bound_method->method());
1909       Expression* first_arg = bound_method->first_argument();
1910
1911       // We always pass a pointer when calling a method.
1912       if (first_arg->type()->points_to() == NULL)
1913         first_arg = Expression::make_unary(OPERATOR_AND, first_arg, location);
1914
1915       // If we are calling a method which was inherited from an
1916       // embedded struct, and the method did not get a stub, then the
1917       // first type may be wrong.
1918       Type* fatype = bound_method->first_argument_type();
1919       if (fatype != NULL)
1920         {
1921           if (fatype->points_to() == NULL)
1922             fatype = Type::make_pointer_type(fatype);
1923           Type* unsafe = Type::make_pointer_type(Type::make_void_type());
1924           first_arg = Expression::make_cast(unsafe, first_arg, location);
1925           first_arg = Expression::make_cast(fatype, first_arg, location);
1926         }
1927
1928       vals->push_back(first_arg);
1929     }
1930   else
1931     gcc_unreachable();
1932
1933   if (ce->args() != NULL)
1934     {
1935       for (Expression_list::const_iterator p = ce->args()->begin();
1936            p != ce->args()->end();
1937            ++p)
1938         vals->push_back(*p);
1939     }
1940
1941   // Build the struct.
1942   Expression* constructor =
1943     Expression::make_struct_composite_literal(this->struct_type_, vals,
1944                                               location);
1945
1946   // Allocate the initialized struct on the heap.
1947   constructor = Expression::make_heap_composite(constructor, location);
1948
1949   // Look up the thunk.
1950   Named_object* named_thunk = gogo->lookup(thunk_name, NULL);
1951   gcc_assert(named_thunk != NULL && named_thunk->is_function());
1952
1953   // Build the call.
1954   Expression* func = Expression::make_func_reference(named_thunk, NULL,
1955                                                      location);
1956   Expression_list* params = new Expression_list();
1957   params->push_back(constructor);
1958   Call_expression* call = Expression::make_call(func, params, false, location);
1959
1960   // Build the simple go or defer statement.
1961   Statement* s;
1962   if (this->classification() == STATEMENT_GO)
1963     s = Statement::make_go_statement(call, location);
1964   else if (this->classification() == STATEMENT_DEFER)
1965     s = Statement::make_defer_statement(call, location);
1966   else
1967     gcc_unreachable();
1968
1969   // The current block should end with the go statement.
1970   gcc_assert(block->statements()->size() >= 1);
1971   gcc_assert(block->statements()->back() == this);
1972   block->replace_statement(block->statements()->size() - 1, s);
1973
1974   // We already ran the determine_types pass, so we need to run it now
1975   // for the new statement.
1976   s->determine_types();
1977
1978   // Sanity check.
1979   gogo->check_types_in_block(block);
1980
1981   // Return true to tell the block not to keep looking at statements.
1982   return true;
1983 }
1984
1985 // Set the name to use for thunk parameter N.
1986
1987 void
1988 Thunk_statement::thunk_field_param(int n, char* buf, size_t buflen)
1989 {
1990   snprintf(buf, buflen, "a%d", n);
1991 }
1992
1993 // Build a new struct type to hold the parameters for a complicated
1994 // thunk statement.  FNTYPE is the type of the function call.
1995
1996 Struct_type*
1997 Thunk_statement::build_struct(Function_type* fntype)
1998 {
1999   source_location location = this->location();
2000
2001   Struct_field_list* fields = new Struct_field_list();
2002
2003   Call_expression* ce = this->call_->call_expression();
2004   Expression* fn = ce->fn();
2005
2006   Interface_field_reference_expression* interface_method =
2007     fn->interface_field_reference_expression();
2008   if (interface_method != NULL)
2009     {
2010       // If this thunk statement calls a method on an interface, we
2011       // pass the interface object to the thunk.
2012       Typed_identifier tid(Thunk_statement::thunk_field_fn,
2013                            interface_method->expr()->type(),
2014                            location);
2015       fields->push_back(Struct_field(tid));
2016     }
2017   else if (!fntype->is_builtin())
2018     {
2019       // The function to call.
2020       Typed_identifier tid(Go_statement::thunk_field_fn, fntype, location);
2021       fields->push_back(Struct_field(tid));
2022     }
2023   else if (ce->is_recover_call())
2024     {
2025       // The predeclared recover function has no argument.  However,
2026       // we add an argument when building recover thunks.  Handle that
2027       // here.
2028       fields->push_back(Struct_field(Typed_identifier("can_recover",
2029                                                       Type::lookup_bool_type(),
2030                                                       location)));
2031     }
2032
2033   if (fn->bound_method_expression() != NULL)
2034     {
2035       gcc_assert(fntype->is_method());
2036       Type* rtype = fntype->receiver()->type();
2037       // We always pass the receiver as a pointer.
2038       if (rtype->points_to() == NULL)
2039         rtype = Type::make_pointer_type(rtype);
2040       Typed_identifier tid(Thunk_statement::thunk_field_receiver, rtype,
2041                            location);
2042       fields->push_back(Struct_field(tid));
2043     }
2044
2045   const Expression_list* args = ce->args();
2046   if (args != NULL)
2047     {
2048       int i = 0;
2049       for (Expression_list::const_iterator p = args->begin();
2050            p != args->end();
2051            ++p, ++i)
2052         {
2053           char buf[50];
2054           this->thunk_field_param(i, buf, sizeof buf);
2055           fields->push_back(Struct_field(Typed_identifier(buf, (*p)->type(),
2056                                                           location)));
2057         }
2058     }
2059
2060   return Type::make_struct_type(fields, location);
2061 }
2062
2063 // Build the thunk we are going to call.  This is a brand new, albeit
2064 // artificial, function.
2065
2066 void
2067 Thunk_statement::build_thunk(Gogo* gogo, const std::string& thunk_name,
2068                              Function_type* fntype)
2069 {
2070   source_location location = this->location();
2071
2072   Call_expression* ce = this->call_->call_expression();
2073
2074   bool may_call_recover = false;
2075   if (this->classification() == STATEMENT_DEFER)
2076     {
2077       Func_expression* fn = ce->fn()->func_expression();
2078       if (fn == NULL)
2079         may_call_recover = true;
2080       else
2081         {
2082           const Named_object* no = fn->named_object();
2083           if (!no->is_function())
2084             may_call_recover = true;
2085           else
2086             may_call_recover = no->func_value()->calls_recover();
2087         }
2088     }
2089
2090   // Build the type of the thunk.  The thunk takes a single parameter,
2091   // which is a pointer to the special structure we build.
2092   const char* const parameter_name = "__go_thunk_parameter";
2093   Typed_identifier_list* thunk_parameters = new Typed_identifier_list();
2094   Type* pointer_to_struct_type = Type::make_pointer_type(this->struct_type_);
2095   thunk_parameters->push_back(Typed_identifier(parameter_name,
2096                                                pointer_to_struct_type,
2097                                                location));
2098
2099   Typed_identifier_list* thunk_results = NULL;
2100   if (may_call_recover)
2101     {
2102       // When deferring a function which may call recover, add a
2103       // return value, to disable tail call optimizations which will
2104       // break the way we check whether recover is permitted.
2105       thunk_results = new Typed_identifier_list();
2106       thunk_results->push_back(Typed_identifier("", Type::lookup_bool_type(),
2107                                                 location));
2108     }
2109
2110   Function_type* thunk_type = Type::make_function_type(NULL, thunk_parameters,
2111                                                        thunk_results,
2112                                                        location);
2113
2114   // Start building the thunk.
2115   Named_object* function = gogo->start_function(thunk_name, thunk_type, true,
2116                                                 location);
2117
2118   // For a defer statement, start with a call to
2119   // __go_set_defer_retaddr.  */
2120   Label* retaddr_label = NULL; 
2121   if (may_call_recover)
2122     {
2123       retaddr_label = gogo->add_label_reference("retaddr");
2124       Expression* arg = Expression::make_label_addr(retaddr_label, location);
2125       Expression_list* args = new Expression_list();
2126       args->push_back(arg);
2127
2128       static Named_object* set_defer_retaddr;
2129       if (set_defer_retaddr == NULL)
2130         {
2131           const source_location bloc = BUILTINS_LOCATION;
2132           Typed_identifier_list* param_types = new Typed_identifier_list();
2133           Type *voidptr_type = Type::make_pointer_type(Type::make_void_type());
2134           param_types->push_back(Typed_identifier("r", voidptr_type, bloc));
2135
2136           Typed_identifier_list* result_types = new Typed_identifier_list();
2137           result_types->push_back(Typed_identifier("",
2138                                                    Type::lookup_bool_type(),
2139                                                    bloc));
2140
2141           Function_type* t = Type::make_function_type(NULL, param_types,
2142                                                       result_types, bloc);
2143           set_defer_retaddr =
2144             Named_object::make_function_declaration("__go_set_defer_retaddr",
2145                                                     NULL, t, bloc);
2146           const char* n = "__go_set_defer_retaddr";
2147           set_defer_retaddr->func_declaration_value()->set_asm_name(n);
2148         }
2149
2150       Expression* fn = Expression::make_func_reference(set_defer_retaddr,
2151                                                        NULL, location);
2152       Expression* call = Expression::make_call(fn, args, false, location);
2153
2154       // This is a hack to prevent the middle-end from deleting the
2155       // label.
2156       gogo->start_block(location);
2157       gogo->add_statement(Statement::make_goto_statement(retaddr_label,
2158                                                          location));
2159       Block* then_block = gogo->finish_block(location);
2160       then_block->determine_types();
2161
2162       Statement* s = Statement::make_if_statement(call, then_block, NULL,
2163                                                   location);
2164       s->determine_types();
2165       gogo->add_statement(s);
2166     }
2167
2168   // Get a reference to the parameter.
2169   Named_object* named_parameter = gogo->lookup(parameter_name, NULL);
2170   gcc_assert(named_parameter != NULL && named_parameter->is_variable());
2171
2172   // Build the call.  Note that the field names are the same as the
2173   // ones used in build_struct.
2174   Expression* thunk_parameter = Expression::make_var_reference(named_parameter,
2175                                                                location);
2176   thunk_parameter = Expression::make_unary(OPERATOR_MULT, thunk_parameter,
2177                                            location);
2178
2179   Bound_method_expression* bound_method = ce->fn()->bound_method_expression();
2180   Interface_field_reference_expression* interface_method =
2181     ce->fn()->interface_field_reference_expression();
2182
2183   Expression* func_to_call;
2184   unsigned int next_index;
2185   if (!fntype->is_builtin())
2186     {
2187       func_to_call = Expression::make_field_reference(thunk_parameter,
2188                                                       0, location);
2189       next_index = 1;
2190     }
2191   else
2192     {
2193       gcc_assert(bound_method == NULL && interface_method == NULL);
2194       func_to_call = ce->fn();
2195       next_index = 0;
2196     }
2197
2198   if (bound_method != NULL)
2199     {
2200       Expression* r = Expression::make_field_reference(thunk_parameter, 1,
2201                                                        location);
2202       // The main program passes in a function pointer from the
2203       // interface expression, so here we can make a bound method in
2204       // all cases.
2205       func_to_call = Expression::make_bound_method(r, func_to_call,
2206                                                    location);
2207       next_index = 2;
2208     }
2209   else if (interface_method != NULL)
2210     {
2211       // The main program passes the interface object.
2212       const std::string& name(interface_method->name());
2213       func_to_call = Expression::make_interface_field_reference(func_to_call,
2214                                                                 name,
2215                                                                 location);
2216     }
2217
2218   Expression_list* call_params = new Expression_list();
2219   const Struct_field_list* fields = this->struct_type_->fields();
2220   Struct_field_list::const_iterator p = fields->begin();
2221   for (unsigned int i = 0; i < next_index; ++i)
2222     ++p;
2223   bool is_recover_call = ce->is_recover_call();
2224   Expression* recover_arg = NULL;
2225   for (; p != fields->end(); ++p, ++next_index)
2226     {
2227       Expression* thunk_param = Expression::make_var_reference(named_parameter,
2228                                                                location);
2229       thunk_param = Expression::make_unary(OPERATOR_MULT, thunk_param,
2230                                            location);
2231       Expression* param = Expression::make_field_reference(thunk_param,
2232                                                            next_index,
2233                                                            location);
2234       if (!is_recover_call)
2235         call_params->push_back(param);
2236       else
2237         {
2238           gcc_assert(call_params->empty());
2239           recover_arg = param;
2240         }
2241     }
2242
2243   if (call_params->empty())
2244     {
2245       delete call_params;
2246       call_params = NULL;
2247     }
2248
2249   Expression* call = Expression::make_call(func_to_call, call_params, false,
2250                                            location);
2251   // We need to lower in case this is a builtin function.
2252   call = call->lower(gogo, function, -1);
2253   Call_expression* call_ce = call->call_expression();
2254   if (call_ce != NULL && may_call_recover)
2255     call_ce->set_is_deferred();
2256
2257   Statement* call_statement = Statement::make_statement(call);
2258
2259   // We already ran the determine_types pass, so we need to run it
2260   // just for this statement now.
2261   call_statement->determine_types();
2262
2263   // Sanity check.
2264   call->check_types(gogo);
2265
2266   if (call_ce != NULL && recover_arg != NULL)
2267     call_ce->set_recover_arg(recover_arg);
2268
2269   gogo->add_statement(call_statement);
2270
2271   // If this is a defer statement, the label comes immediately after
2272   // the call.
2273   if (may_call_recover)
2274     {
2275       gogo->add_label_definition("retaddr", location);
2276
2277       Expression_list* vals = new Expression_list();
2278       vals->push_back(Expression::make_boolean(false, location));
2279       const Typed_identifier_list* results =
2280         function->func_value()->type()->results();
2281       gogo->add_statement(Statement::make_return_statement(results, vals,
2282                                                           location));
2283     }
2284
2285   // That is all the thunk has to do.
2286   gogo->finish_function(location);
2287 }
2288
2289 // Get the function and argument trees.
2290
2291 void
2292 Thunk_statement::get_fn_and_arg(Translate_context* context, tree* pfn,
2293                                 tree* parg)
2294 {
2295   if (this->call_->is_error_expression())
2296     {
2297       *pfn = error_mark_node;
2298       *parg = error_mark_node;
2299       return;
2300     }
2301
2302   Call_expression* ce = this->call_->call_expression();
2303
2304   Expression* fn = ce->fn();
2305   *pfn = fn->get_tree(context);
2306
2307   const Expression_list* args = ce->args();
2308   if (args == NULL || args->empty())
2309     *parg = null_pointer_node;
2310   else
2311     {
2312       gcc_assert(args->size() == 1);
2313       *parg = args->front()->get_tree(context);
2314     }
2315 }
2316
2317 // Class Go_statement.
2318
2319 tree
2320 Go_statement::do_get_tree(Translate_context* context)
2321 {
2322   tree fn_tree;
2323   tree arg_tree;
2324   this->get_fn_and_arg(context, &fn_tree, &arg_tree);
2325
2326   static tree go_fndecl;
2327
2328   tree fn_arg_type = NULL_TREE;
2329   if (go_fndecl == NULL_TREE)
2330     {
2331       // Only build FN_ARG_TYPE if we need it.
2332       tree subargtypes = tree_cons(NULL_TREE, ptr_type_node, void_list_node);
2333       tree subfntype = build_function_type(ptr_type_node, subargtypes);
2334       fn_arg_type = build_pointer_type(subfntype);
2335     }
2336
2337   return Gogo::call_builtin(&go_fndecl,
2338                             this->location(),
2339                             "__go_go",
2340                             2,
2341                             void_type_node,
2342                             fn_arg_type,
2343                             fn_tree,
2344                             ptr_type_node,
2345                             arg_tree);
2346 }
2347
2348 // Make a go statement.
2349
2350 Statement*
2351 Statement::make_go_statement(Call_expression* call, source_location location)
2352 {
2353   return new Go_statement(call, location);
2354 }
2355
2356 // Class Defer_statement.
2357
2358 tree
2359 Defer_statement::do_get_tree(Translate_context* context)
2360 {
2361   source_location loc = this->location();
2362
2363   tree fn_tree;
2364   tree arg_tree;
2365   this->get_fn_and_arg(context, &fn_tree, &arg_tree);
2366   if (fn_tree == error_mark_node || arg_tree == error_mark_node)
2367     return error_mark_node;
2368
2369   static tree defer_fndecl;
2370
2371   tree fn_arg_type = NULL_TREE;
2372   if (defer_fndecl == NULL_TREE)
2373     {
2374       // Only build FN_ARG_TYPE if we need it.
2375       tree subargtypes = tree_cons(NULL_TREE, ptr_type_node, void_list_node);
2376       tree subfntype = build_function_type(ptr_type_node, subargtypes);
2377       fn_arg_type = build_pointer_type(subfntype);
2378     }
2379
2380   tree defer_stack = context->function()->func_value()->defer_stack(loc);
2381
2382   return Gogo::call_builtin(&defer_fndecl,
2383                             loc,
2384                             "__go_defer",
2385                             3,
2386                             void_type_node,
2387                             ptr_type_node,
2388                             defer_stack,
2389                             fn_arg_type,
2390                             fn_tree,
2391                             ptr_type_node,
2392                             arg_tree);
2393 }
2394
2395 // Make a defer statement.
2396
2397 Statement*
2398 Statement::make_defer_statement(Call_expression* call,
2399                                 source_location location)
2400 {
2401   return new Defer_statement(call, location);
2402 }
2403
2404 // Class Return_statement.
2405
2406 // Traverse assignments.  We treat each return value as a top level
2407 // RHS in an expression.
2408
2409 bool
2410 Return_statement::do_traverse_assignments(Traverse_assignments* tassign)
2411 {
2412   Expression_list* vals = this->vals_;
2413   if (vals != NULL)
2414     {
2415       for (Expression_list::iterator p = vals->begin();
2416            p != vals->end();
2417            ++p)
2418         tassign->value(&*p, true, true);
2419     }
2420   return true;
2421 }
2422
2423 // Lower a return statement.  If we are returning a function call
2424 // which returns multiple values which match the current function,
2425 // split up the call's results.  If the function has named result
2426 // variables, and the return statement lists explicit values, then
2427 // implement it by assigning the values to the result variables and
2428 // changing the statement to not list any values.  This lets
2429 // panic/recover work correctly.
2430
2431 Statement*
2432 Return_statement::do_lower(Gogo*, Block* enclosing)
2433 {
2434   if (this->vals_ == NULL)
2435     return this;
2436
2437   const Typed_identifier_list* results = this->results_;
2438   if (results == NULL || results->empty())
2439     return this;
2440
2441   // If the current function has multiple return values, and we are
2442   // returning a single call expression, split up the call expression.
2443   size_t results_count = results->size();
2444   if (results_count > 1
2445       && this->vals_->size() == 1
2446       && this->vals_->front()->call_expression() != NULL)
2447     {
2448       Call_expression* call = this->vals_->front()->call_expression();
2449       size_t count = results->size();
2450       Expression_list* vals = new Expression_list;
2451       for (size_t i = 0; i < count; ++i)
2452         vals->push_back(Expression::make_call_result(call, i));
2453       delete this->vals_;
2454       this->vals_ = vals;
2455     }
2456
2457   if (results->front().name().empty())
2458     return this;
2459
2460   if (results_count != this->vals_->size())
2461     {
2462       // Presumably an error which will be reported in check_types.
2463       return this;
2464     }
2465
2466   // Assign to named return values and then return them.
2467
2468   source_location loc = this->location();
2469   const Block* top = enclosing;
2470   while (top->enclosing() != NULL)
2471     top = top->enclosing();
2472
2473   const Bindings *bindings = top->bindings();
2474   Block* b = new Block(enclosing, loc);
2475
2476   Expression_list* lhs = new Expression_list();
2477   Expression_list* rhs = new Expression_list();
2478
2479   Expression_list::const_iterator pe = this->vals_->begin();
2480   int i = 1;
2481   for (Typed_identifier_list::const_iterator pr = results->begin();
2482        pr != results->end();
2483        ++pr, ++pe, ++i)
2484     {
2485       Named_object* rv = bindings->lookup_local(pr->name());
2486       if (rv == NULL || !rv->is_result_variable())
2487         {
2488           // Presumably an error.
2489           delete b;
2490           delete lhs;
2491           delete rhs;
2492           return this;
2493         }
2494
2495       Expression* e = *pe;
2496
2497       // Check types now so that we give a good error message.  The
2498       // result type is known.  We determine the expression type
2499       // early.
2500
2501       Type *rvtype = rv->result_var_value()->type();
2502       Type_context type_context(rvtype, false);
2503       e->determine_type(&type_context);
2504
2505       std::string reason;
2506       if (Type::are_assignable(rvtype, e->type(), &reason))
2507         {
2508           Expression* ve = Expression::make_var_reference(rv, e->location());
2509           lhs->push_back(ve);
2510           rhs->push_back(e);
2511         }
2512       else
2513         {
2514           if (reason.empty())
2515             error_at(e->location(), "incompatible type for return value %d", i);
2516           else
2517             error_at(e->location(),
2518                      "incompatible type for return value %d (%s)",
2519                      i, reason.c_str());
2520         }
2521     }
2522   gcc_assert(lhs->size() == rhs->size());
2523
2524   if (lhs->empty())
2525     ;
2526   else if (lhs->size() == 1)
2527     {
2528       b->add_statement(Statement::make_assignment(lhs->front(), rhs->front(),
2529                                                   loc));
2530       delete lhs;
2531       delete rhs;
2532     }
2533   else
2534     b->add_statement(Statement::make_tuple_assignment(lhs, rhs, loc));
2535
2536   b->add_statement(Statement::make_return_statement(this->results_, NULL,
2537                                                     loc));
2538
2539   return Statement::make_block_statement(b, loc);
2540 }
2541
2542 // Determine types.
2543
2544 void
2545 Return_statement::do_determine_types()
2546 {
2547   if (this->vals_ == NULL)
2548     return;
2549   const Typed_identifier_list* results = this->results_;
2550
2551   Typed_identifier_list::const_iterator pt;
2552   if (results != NULL)
2553     pt = results->begin();
2554   for (Expression_list::iterator pe = this->vals_->begin();
2555        pe != this->vals_->end();
2556        ++pe)
2557     {
2558       if (results == NULL || pt == results->end())
2559         (*pe)->determine_type_no_context();
2560       else
2561         {
2562           Type_context context(pt->type(), false);
2563           (*pe)->determine_type(&context);
2564           ++pt;
2565         }
2566     }
2567 }
2568
2569 // Check types.
2570
2571 void
2572 Return_statement::do_check_types(Gogo*)
2573 {
2574   if (this->vals_ == NULL)
2575     return;
2576
2577   const Typed_identifier_list* results = this->results_;
2578   if (results == NULL)
2579     {
2580       this->report_error(_("return with value in function "
2581                            "with no return type"));
2582       return;
2583     }
2584
2585   int i = 1;
2586   Typed_identifier_list::const_iterator pt = results->begin();
2587   for (Expression_list::const_iterator pe = this->vals_->begin();
2588        pe != this->vals_->end();
2589        ++pe, ++pt, ++i)
2590     {
2591       if (pt == results->end())
2592         {
2593           this->report_error(_("too many values in return statement"));
2594           return;
2595         }
2596       std::string reason;
2597       if (!Type::are_assignable(pt->type(), (*pe)->type(), &reason))
2598         {
2599           if (reason.empty())
2600             error_at(this->location(),
2601                      "incompatible type for return value %d",
2602                      i);
2603           else
2604             error_at(this->location(),
2605                      "incompatible type for return value %d (%s)",
2606                      i, reason.c_str());
2607           this->set_is_error();
2608         }
2609       else if (pt->type()->is_error_type()
2610                || (*pe)->type()->is_error_type()
2611                || pt->type()->is_undefined()
2612                || (*pe)->type()->is_undefined())
2613         {
2614           // Make sure we get the error for an undefined type.
2615           pt->type()->base();
2616           (*pe)->type()->base();
2617           this->set_is_error();
2618         }
2619     }
2620
2621   if (pt != results->end())
2622     this->report_error(_("not enough values in return statement"));
2623 }
2624
2625 // Build a RETURN_EXPR tree.
2626
2627 tree
2628 Return_statement::do_get_tree(Translate_context* context)
2629 {
2630   Function* function = context->function()->func_value();
2631   tree fndecl = function->get_decl();
2632   if (fndecl == error_mark_node || DECL_RESULT(fndecl) == error_mark_node)
2633     return error_mark_node;
2634
2635   const Typed_identifier_list* results = this->results_;
2636
2637   if (this->vals_ == NULL)
2638     {
2639       tree stmt_list = NULL_TREE;
2640       tree retval = function->return_value(context->gogo(),
2641                                            context->function(),
2642                                            this->location(),
2643                                            &stmt_list);
2644       tree set;
2645       if (retval == NULL_TREE)
2646         set = NULL_TREE;
2647       else if (retval == error_mark_node)
2648         return error_mark_node;
2649       else
2650         set = fold_build2_loc(this->location(), MODIFY_EXPR, void_type_node,
2651                               DECL_RESULT(fndecl), retval);
2652       append_to_statement_list(this->build_stmt_1(RETURN_EXPR, set),
2653                                &stmt_list);
2654       return stmt_list;
2655     }
2656   else if (this->vals_->size() == 1)
2657     {
2658       gcc_assert(!VOID_TYPE_P(TREE_TYPE(TREE_TYPE(fndecl))));
2659       tree val = (*this->vals_->begin())->get_tree(context);
2660       gcc_assert(results != NULL && results->size() == 1);
2661       val = Expression::convert_for_assignment(context,
2662                                                results->begin()->type(),
2663                                                (*this->vals_->begin())->type(),
2664                                                val, this->location());
2665       if (val == error_mark_node)
2666         return error_mark_node;
2667       tree set = build2(MODIFY_EXPR, void_type_node,
2668                         DECL_RESULT(fndecl), val);
2669       SET_EXPR_LOCATION(set, this->location());
2670       return this->build_stmt_1(RETURN_EXPR, set);
2671     }
2672   else
2673     {
2674       gcc_assert(!VOID_TYPE_P(TREE_TYPE(TREE_TYPE(fndecl))));
2675       tree stmt_list = NULL_TREE;
2676       tree rettype = TREE_TYPE(DECL_RESULT(fndecl));
2677       tree retvar = create_tmp_var(rettype, "RESULT");
2678       gcc_assert(results != NULL && results->size() == this->vals_->size());
2679       Expression_list::const_iterator pv = this->vals_->begin();
2680       Typed_identifier_list::const_iterator pr = results->begin();
2681       for (tree field = TYPE_FIELDS(rettype);
2682            field != NULL_TREE;
2683            ++pv, ++pr, field = DECL_CHAIN(field))
2684         {
2685           gcc_assert(pv != this->vals_->end());
2686           tree val = (*pv)->get_tree(context);
2687           val = Expression::convert_for_assignment(context, pr->type(),
2688                                                    (*pv)->type(), val,
2689                                                    this->location());
2690           if (val == error_mark_node)
2691             return error_mark_node;
2692           tree set = build2(MODIFY_EXPR, void_type_node,
2693                             build3(COMPONENT_REF, TREE_TYPE(field),
2694                                    retvar, field, NULL_TREE),
2695                             val);
2696           SET_EXPR_LOCATION(set, this->location());
2697           append_to_statement_list(set, &stmt_list);
2698         }
2699       tree set = build2(MODIFY_EXPR, void_type_node, DECL_RESULT(fndecl),
2700                         retvar);
2701       append_to_statement_list(this->build_stmt_1(RETURN_EXPR, set),
2702                                &stmt_list);
2703       return stmt_list;
2704     }
2705 }
2706
2707 // Make a return statement.
2708
2709 Statement*
2710 Statement::make_return_statement(const Typed_identifier_list* results,
2711                                  Expression_list* vals,
2712                                  source_location location)
2713 {
2714   return new Return_statement(results, vals, location);
2715 }
2716
2717 // A break or continue statement.
2718
2719 class Bc_statement : public Statement
2720 {
2721  public:
2722   Bc_statement(bool is_break, Unnamed_label* label, source_location location)
2723     : Statement(STATEMENT_BREAK_OR_CONTINUE, location),
2724       label_(label), is_break_(is_break)
2725   { }
2726
2727   bool
2728   is_break() const
2729   { return this->is_break_; }
2730
2731  protected:
2732   int
2733   do_traverse(Traverse*)
2734   { return TRAVERSE_CONTINUE; }
2735
2736   bool
2737   do_may_fall_through() const
2738   { return false; }
2739
2740   tree
2741   do_get_tree(Translate_context*)
2742   { return this->label_->get_goto(this->location()); }
2743
2744  private:
2745   // The label that this branches to.
2746   Unnamed_label* label_;
2747   // True if this is "break", false if it is "continue".
2748   bool is_break_;
2749 };
2750
2751 // Make a break statement.
2752
2753 Statement*
2754 Statement::make_break_statement(Unnamed_label* label, source_location location)
2755 {
2756   return new Bc_statement(true, label, location);
2757 }
2758
2759 // Make a continue statement.
2760
2761 Statement*
2762 Statement::make_continue_statement(Unnamed_label* label,
2763                                    source_location location)
2764 {
2765   return new Bc_statement(false, label, location);
2766 }
2767
2768 // A goto statement.
2769
2770 class Goto_statement : public Statement
2771 {
2772  public:
2773   Goto_statement(Label* label, source_location location)
2774     : Statement(STATEMENT_GOTO, location),
2775       label_(label)
2776   { }
2777
2778  protected:
2779   int
2780   do_traverse(Traverse*)
2781   { return TRAVERSE_CONTINUE; }
2782
2783   void
2784   do_check_types(Gogo*);
2785
2786   bool
2787   do_may_fall_through() const
2788   { return false; }
2789
2790   tree
2791   do_get_tree(Translate_context*);
2792
2793  private:
2794   Label* label_;
2795 };
2796
2797 // Check types for a label.  There aren't any types per se, but we use
2798 // this to give an error if the label was never defined.
2799
2800 void
2801 Goto_statement::do_check_types(Gogo*)
2802 {
2803   if (!this->label_->is_defined())
2804     {
2805       error_at(this->location(), "reference to undefined label %qs",
2806                Gogo::message_name(this->label_->name()).c_str());
2807       this->set_is_error();
2808     }
2809 }
2810
2811 // Return the tree for the goto statement.
2812
2813 tree
2814 Goto_statement::do_get_tree(Translate_context*)
2815 {
2816   return this->build_stmt_1(GOTO_EXPR, this->label_->get_decl());
2817 }
2818
2819 // Make a goto statement.
2820
2821 Statement*
2822 Statement::make_goto_statement(Label* label, source_location location)
2823 {
2824   return new Goto_statement(label, location);
2825 }
2826
2827 // A goto statement to an unnamed label.
2828
2829 class Goto_unnamed_statement : public Statement
2830 {
2831  public:
2832   Goto_unnamed_statement(Unnamed_label* label, source_location location)
2833     : Statement(STATEMENT_GOTO_UNNAMED, location),
2834       label_(label)
2835   { }
2836
2837  protected:
2838   int
2839   do_traverse(Traverse*)
2840   { return TRAVERSE_CONTINUE; }
2841
2842   bool
2843   do_may_fall_through() const
2844   { return false; }
2845
2846   tree
2847   do_get_tree(Translate_context*)
2848   { return this->label_->get_goto(this->location()); }
2849
2850  private:
2851   Unnamed_label* label_;
2852 };
2853
2854 // Make a goto statement to an unnamed label.
2855
2856 Statement*
2857 Statement::make_goto_unnamed_statement(Unnamed_label* label,
2858                                        source_location location)
2859 {
2860   return new Goto_unnamed_statement(label, location);
2861 }
2862
2863 // Class Label_statement.
2864
2865 // Traversal.
2866
2867 int
2868 Label_statement::do_traverse(Traverse*)
2869 {
2870   return TRAVERSE_CONTINUE;
2871 }
2872
2873 // Return a tree defining this label.
2874
2875 tree
2876 Label_statement::do_get_tree(Translate_context*)
2877 {
2878   return this->build_stmt_1(LABEL_EXPR, this->label_->get_decl());
2879 }
2880
2881 // Make a label statement.
2882
2883 Statement*
2884 Statement::make_label_statement(Label* label, source_location location)
2885 {
2886   return new Label_statement(label, location);
2887 }
2888
2889 // An unnamed label statement.
2890
2891 class Unnamed_label_statement : public Statement
2892 {
2893  public:
2894   Unnamed_label_statement(Unnamed_label* label)
2895     : Statement(STATEMENT_UNNAMED_LABEL, label->location()),
2896       label_(label)
2897   { }
2898
2899  protected:
2900   int
2901   do_traverse(Traverse*)
2902   { return TRAVERSE_CONTINUE; }
2903
2904   tree
2905   do_get_tree(Translate_context*)
2906   { return this->label_->get_definition(); }
2907
2908  private:
2909   // The label.
2910   Unnamed_label* label_;
2911 };
2912
2913 // Make an unnamed label statement.
2914
2915 Statement*
2916 Statement::make_unnamed_label_statement(Unnamed_label* label)
2917 {
2918   return new Unnamed_label_statement(label);
2919 }
2920
2921 // An if statement.
2922
2923 class If_statement : public Statement
2924 {
2925  public:
2926   If_statement(Expression* cond, Block* then_block, Block* else_block,
2927                source_location location)
2928     : Statement(STATEMENT_IF, location),
2929       cond_(cond), then_block_(then_block), else_block_(else_block)
2930   { }
2931
2932  protected:
2933   int
2934   do_traverse(Traverse*);
2935
2936   void
2937   do_determine_types();
2938
2939   void
2940   do_check_types(Gogo*);
2941
2942   bool
2943   do_may_fall_through() const;
2944
2945   tree
2946   do_get_tree(Translate_context*);
2947
2948  private:
2949   Expression* cond_;
2950   Block* then_block_;
2951   Block* else_block_;
2952 };
2953
2954 // Traversal.
2955
2956 int
2957 If_statement::do_traverse(Traverse* traverse)
2958 {
2959   if (this->cond_ != NULL)
2960     {
2961       if (this->traverse_expression(traverse, &this->cond_) == TRAVERSE_EXIT)
2962         return TRAVERSE_EXIT;
2963     }
2964   if (this->then_block_->traverse(traverse) == TRAVERSE_EXIT)
2965     return TRAVERSE_EXIT;
2966   if (this->else_block_ != NULL)
2967     {
2968       if (this->else_block_->traverse(traverse) == TRAVERSE_EXIT)
2969         return TRAVERSE_EXIT;
2970     }
2971   return TRAVERSE_CONTINUE;
2972 }
2973
2974 void
2975 If_statement::do_determine_types()
2976 {
2977   if (this->cond_ != NULL)
2978     {
2979       Type_context context(Type::lookup_bool_type(), false);
2980       this->cond_->determine_type(&context);
2981     }
2982   this->then_block_->determine_types();
2983   if (this->else_block_ != NULL)
2984     this->else_block_->determine_types();
2985 }
2986
2987 // Check types.
2988
2989 void
2990 If_statement::do_check_types(Gogo*)
2991 {
2992   if (this->cond_ != NULL)
2993     {
2994       Type* type = this->cond_->type();
2995       if (type->is_error_type())
2996         this->set_is_error();
2997       else if (!type->is_boolean_type())
2998         this->report_error(_("expected boolean expression"));
2999     }
3000 }
3001
3002 // Whether the overall statement may fall through.
3003
3004 bool
3005 If_statement::do_may_fall_through() const
3006 {
3007   return (this->else_block_ == NULL
3008           || this->then_block_->may_fall_through()
3009           || this->else_block_->may_fall_through());
3010 }
3011
3012 // Get tree.
3013
3014 tree
3015 If_statement::do_get_tree(Translate_context* context)
3016 {
3017   gcc_assert(this->cond_ == NULL
3018              || this->cond_->type()->is_boolean_type()
3019              || this->cond_->type()->is_error_type());
3020   tree cond_tree = (this->cond_ == NULL
3021                     ? boolean_true_node
3022                     : this->cond_->get_tree(context));
3023   tree then_tree = this->then_block_->get_tree(context);
3024   tree else_tree = (this->else_block_ == NULL
3025                     ? NULL_TREE
3026                     : this->else_block_->get_tree(context));
3027   if (cond_tree == error_mark_node
3028       || then_tree == error_mark_node
3029       || else_tree == error_mark_node)
3030     return error_mark_node;
3031   tree ret = build3(COND_EXPR, void_type_node, cond_tree, then_tree,
3032                     else_tree);
3033   SET_EXPR_LOCATION(ret, this->location());
3034   return ret;
3035 }
3036
3037 // Make an if statement.
3038
3039 Statement*
3040 Statement::make_if_statement(Expression* cond, Block* then_block,
3041                              Block* else_block, source_location location)
3042 {
3043   return new If_statement(cond, then_block, else_block, location);
3044 }
3045
3046 // Class Case_clauses::Case_clause.
3047
3048 // Traversal.
3049
3050 int
3051 Case_clauses::Case_clause::traverse(Traverse* traverse)
3052 {
3053   if (this->cases_ != NULL
3054       && (traverse->traverse_mask()
3055           & (Traverse::traverse_types | Traverse::traverse_expressions)) != 0)
3056     {
3057       if (this->cases_->traverse(traverse) == TRAVERSE_EXIT)
3058         return TRAVERSE_EXIT;
3059     }
3060   if (this->statements_ != NULL)
3061     {
3062       if (this->statements_->traverse(traverse) == TRAVERSE_EXIT)
3063         return TRAVERSE_EXIT;
3064     }
3065   return TRAVERSE_CONTINUE;
3066 }
3067
3068 // Check whether all the case expressions are integer constants.
3069
3070 bool
3071 Case_clauses::Case_clause::is_constant() const
3072 {
3073   if (this->cases_ != NULL)
3074     {
3075       for (Expression_list::const_iterator p = this->cases_->begin();
3076            p != this->cases_->end();
3077            ++p)
3078         if (!(*p)->is_constant() || (*p)->type()->integer_type() == NULL)
3079           return false;
3080     }
3081   return true;
3082 }
3083
3084 // Lower a case clause for a nonconstant switch.  VAL_TEMP is the
3085 // value we are switching on; it may be NULL.  If START_LABEL is not
3086 // NULL, it goes at the start of the statements, after the condition
3087 // test.  We branch to FINISH_LABEL at the end of the statements.
3088
3089 void
3090 Case_clauses::Case_clause::lower(Block* b, Temporary_statement* val_temp,
3091                                  Unnamed_label* start_label,
3092                                  Unnamed_label* finish_label) const
3093 {
3094   source_location loc = this->location_;
3095   Unnamed_label* next_case_label;
3096   if (this->cases_ == NULL || this->cases_->empty())
3097     {
3098       gcc_assert(this->is_default_);
3099       next_case_label = NULL;
3100     }
3101   else
3102     {
3103       Expression* cond = NULL;
3104
3105       for (Expression_list::const_iterator p = this->cases_->begin();
3106            p != this->cases_->end();
3107            ++p)
3108         {
3109           Expression* this_cond;
3110           if (val_temp == NULL)
3111             this_cond = *p;
3112           else
3113             {
3114               Expression* ref = Expression::make_temporary_reference(val_temp,
3115                                                                      loc);
3116               this_cond = Expression::make_binary(OPERATOR_EQEQ, ref, *p, loc);
3117             }
3118
3119           if (cond == NULL)
3120             cond = this_cond;
3121           else
3122             cond = Expression::make_binary(OPERATOR_OROR, cond, this_cond, loc);
3123         }
3124
3125       Block* then_block = new Block(b, loc);
3126       next_case_label = new Unnamed_label(UNKNOWN_LOCATION);
3127       Statement* s = Statement::make_goto_unnamed_statement(next_case_label,
3128                                                             loc);
3129       then_block->add_statement(s);
3130
3131       // if !COND { goto NEXT_CASE_LABEL }
3132       cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
3133       s = Statement::make_if_statement(cond, then_block, NULL, loc);
3134       b->add_statement(s);
3135     }
3136
3137   if (start_label != NULL)
3138     b->add_statement(Statement::make_unnamed_label_statement(start_label));
3139
3140   if (this->statements_ != NULL)
3141     b->add_statement(Statement::make_block_statement(this->statements_, loc));
3142
3143   Statement* s = Statement::make_goto_unnamed_statement(finish_label, loc);
3144   b->add_statement(s);
3145
3146   if (next_case_label != NULL)
3147     b->add_statement(Statement::make_unnamed_label_statement(next_case_label));
3148 }
3149
3150 // Determine types.
3151
3152 void
3153 Case_clauses::Case_clause::determine_types(Type* type)
3154 {
3155   if (this->cases_ != NULL)
3156     {
3157       Type_context case_context(type, false);
3158       for (Expression_list::iterator p = this->cases_->begin();
3159            p != this->cases_->end();
3160            ++p)
3161         (*p)->determine_type(&case_context);
3162     }
3163   if (this->statements_ != NULL)
3164     this->statements_->determine_types();
3165 }
3166
3167 // Check types.  Returns false if there was an error.
3168
3169 bool
3170 Case_clauses::Case_clause::check_types(Type* type)
3171 {
3172   if (this->cases_ != NULL)
3173     {
3174       for (Expression_list::iterator p = this->cases_->begin();
3175            p != this->cases_->end();
3176            ++p)
3177         {
3178           if (!Type::are_assignable(type, (*p)->type(), NULL)
3179               && !Type::are_assignable((*p)->type(), type, NULL))
3180             {
3181               error_at((*p)->location(),
3182                        "type mismatch between switch value and case clause");
3183               return false;
3184             }
3185         }
3186     }
3187   return true;
3188 }
3189
3190 // Return true if this clause may fall through to the following
3191 // statements.  Note that this is not the same as whether the case
3192 // uses the "fallthrough" keyword.
3193
3194 bool
3195 Case_clauses::Case_clause::may_fall_through() const
3196 {
3197   if (this->statements_ == NULL)
3198     return true;
3199   return this->statements_->may_fall_through();
3200 }
3201
3202 // Build up the body of a SWITCH_EXPR.
3203
3204 void
3205 Case_clauses::Case_clause::get_constant_tree(Translate_context* context,
3206                                              Unnamed_label* break_label,
3207                                              Case_constants* case_constants,
3208                                              tree* stmt_list) const
3209 {
3210   if (this->cases_ != NULL)
3211     {
3212       for (Expression_list::const_iterator p = this->cases_->begin();
3213            p != this->cases_->end();
3214            ++p)
3215         {
3216           Type* itype;
3217           mpz_t ival;
3218           mpz_init(ival);
3219           if (!(*p)->integer_constant_value(true, ival, &itype))
3220             {
3221               // Something went wrong.  This can happen with a
3222               // negative constant and an unsigned switch value.
3223               gcc_assert(saw_errors());
3224               continue;
3225             }
3226           gcc_assert(itype != NULL);
3227           tree type_tree = itype->get_tree(context->gogo());
3228           tree val = Expression::integer_constant_tree(ival, type_tree);
3229           mpz_clear(ival);
3230
3231           if (val != error_mark_node)
3232             {
3233               gcc_assert(TREE_CODE(val) == INTEGER_CST);
3234
3235               std::pair<Case_constants::iterator, bool> ins =
3236                 case_constants->insert(val);
3237               if (!ins.second)
3238                 {
3239                   // Value was already present.
3240                   warning_at(this->location_, 0,
3241                              "duplicate case value will never match");
3242                   continue;
3243                 }
3244
3245               tree label = create_artificial_label(this->location_);
3246               append_to_statement_list(build3(CASE_LABEL_EXPR, void_type_node,
3247                                               val, NULL_TREE, label),
3248                                        stmt_list);
3249             }
3250         }
3251     }
3252
3253   if (this->is_default_)
3254     {
3255       tree label = create_artificial_label(this->location_);
3256       append_to_statement_list(build3(CASE_LABEL_EXPR, void_type_node,
3257                                       NULL_TREE, NULL_TREE, label),
3258                                stmt_list);
3259     }
3260
3261   if (this->statements_ != NULL)
3262     {
3263       tree block_tree = this->statements_->get_tree(context);
3264       if (block_tree != error_mark_node)
3265         append_to_statement_list(block_tree, stmt_list);
3266     }
3267
3268   if (!this->is_fallthrough_)
3269     append_to_statement_list(break_label->get_goto(this->location_), stmt_list);
3270 }
3271
3272 // Class Case_clauses.
3273
3274 // Traversal.
3275
3276 int
3277 Case_clauses::traverse(Traverse* traverse)
3278 {
3279   for (Clauses::iterator p = this->clauses_.begin();
3280        p != this->clauses_.end();
3281        ++p)
3282     {
3283       if (p->traverse(traverse) == TRAVERSE_EXIT)
3284         return TRAVERSE_EXIT;
3285     }
3286   return TRAVERSE_CONTINUE;
3287 }
3288
3289 // Check whether all the case expressions are constant.
3290
3291 bool
3292 Case_clauses::is_constant() const
3293 {
3294   for (Clauses::const_iterator p = this->clauses_.begin();
3295        p != this->clauses_.end();
3296        ++p)
3297     if (!p->is_constant())
3298       return false;
3299   return true;
3300 }
3301
3302 // Lower case clauses for a nonconstant switch.
3303
3304 void
3305 Case_clauses::lower(Block* b, Temporary_statement* val_temp,
3306                     Unnamed_label* break_label) const
3307 {
3308   // The default case.
3309   const Case_clause* default_case = NULL;
3310
3311   // The label for the fallthrough of the previous case.
3312   Unnamed_label* last_fallthrough_label = NULL;
3313
3314   // The label for the start of the default case.  This is used if the
3315   // case before the default case falls through.
3316   Unnamed_label* default_start_label = NULL;
3317
3318   // The label for the end of the default case.  This normally winds
3319   // up as BREAK_LABEL, but it will be different if the default case
3320   // falls through.
3321   Unnamed_label* default_finish_label = NULL;
3322
3323   for (Clauses::const_iterator p = this->clauses_.begin();
3324        p != this->clauses_.end();
3325        ++p)
3326     {
3327       // The label to use for the start of the statements for this
3328       // case.  This is NULL unless the previous case falls through.
3329       Unnamed_label* start_label = last_fallthrough_label;
3330
3331       // The label to jump to after the end of the statements for this
3332       // case.
3333       Unnamed_label* finish_label = break_label;
3334
3335       last_fallthrough_label = NULL;
3336       if (p->is_fallthrough() && p + 1 != this->clauses_.end())
3337         {
3338           finish_label = new Unnamed_label(p->location());
3339           last_fallthrough_label = finish_label;
3340         }
3341
3342       if (!p->is_default())
3343         p->lower(b, val_temp, start_label, finish_label);
3344       else
3345         {
3346           // We have to move the default case to the end, so that we
3347           // only use it if all the other tests fail.
3348           default_case = &*p;
3349           default_start_label = start_label;
3350           default_finish_label = finish_label;
3351         }
3352     }
3353
3354   if (default_case != NULL)
3355     default_case->lower(b, val_temp, default_start_label,
3356                         default_finish_label);
3357       
3358 }
3359
3360 // Determine types.
3361
3362 void
3363 Case_clauses::determine_types(Type* type)
3364 {
3365   for (Clauses::iterator p = this->clauses_.begin();
3366        p != this->clauses_.end();
3367        ++p)
3368     p->determine_types(type);
3369 }
3370
3371 // Check types.  Returns false if there was an error.
3372
3373 bool
3374 Case_clauses::check_types(Type* type)
3375 {
3376   bool ret = true;
3377   for (Clauses::iterator p = this->clauses_.begin();
3378        p != this->clauses_.end();
3379        ++p)
3380     {
3381       if (!p->check_types(type))
3382         ret = false;
3383     }
3384   return ret;
3385 }
3386
3387 // Return true if these clauses may fall through to the statements
3388 // following the switch statement.
3389
3390 bool
3391 Case_clauses::may_fall_through() const
3392 {
3393   bool found_default = false;
3394   for (Clauses::const_iterator p = this->clauses_.begin();
3395        p != this->clauses_.end();
3396        ++p)
3397     {
3398       if (p->may_fall_through() && !p->is_fallthrough())
3399         return true;
3400       if (p->is_default())
3401         found_default = true;
3402     }
3403   return !found_default;
3404 }
3405
3406 // Return a tree when all case expressions are constants.
3407
3408 tree
3409 Case_clauses::get_constant_tree(Translate_context* context,
3410                                 Unnamed_label* break_label) const
3411 {
3412   Case_constants case_constants;
3413   tree stmt_list = NULL_TREE;
3414   for (Clauses::const_iterator p = this->clauses_.begin();
3415        p != this->clauses_.end();
3416        ++p)
3417     p->get_constant_tree(context, break_label, &case_constants,
3418                          &stmt_list);
3419   return stmt_list;
3420 }
3421
3422 // A constant switch statement.  A Switch_statement is lowered to this
3423 // when all the cases are constants.
3424
3425 class Constant_switch_statement : public Statement
3426 {
3427  public:
3428   Constant_switch_statement(Expression* val, Case_clauses* clauses,
3429                             Unnamed_label* break_label,
3430                             source_location location)
3431     : Statement(STATEMENT_CONSTANT_SWITCH, location),
3432       val_(val), clauses_(clauses), break_label_(break_label)
3433   { }
3434
3435  protected:
3436   int
3437   do_traverse(Traverse*);
3438
3439   void
3440   do_determine_types();
3441
3442   void
3443   do_check_types(Gogo*);
3444
3445   bool
3446   do_may_fall_through() const;
3447
3448   tree
3449   do_get_tree(Translate_context*);
3450
3451  private:
3452   // The value to switch on.
3453   Expression* val_;
3454   // The case clauses.
3455   Case_clauses* clauses_;
3456   // The break label, if needed.
3457   Unnamed_label* break_label_;
3458 };
3459
3460 // Traversal.
3461
3462 int
3463 Constant_switch_statement::do_traverse(Traverse* traverse)
3464 {
3465   if (this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT)
3466     return TRAVERSE_EXIT;
3467   return this->clauses_->traverse(traverse);
3468 }
3469
3470 // Determine types.
3471
3472 void
3473 Constant_switch_statement::do_determine_types()
3474 {
3475   this->val_->determine_type_no_context();
3476   this->clauses_->determine_types(this->val_->type());
3477 }
3478
3479 // Check types.
3480
3481 void
3482 Constant_switch_statement::do_check_types(Gogo*)
3483 {
3484   if (!this->clauses_->check_types(this->val_->type()))
3485     this->set_is_error();
3486 }
3487
3488 // Return whether this switch may fall through.
3489
3490 bool
3491 Constant_switch_statement::do_may_fall_through() const
3492 {
3493   if (this->clauses_ == NULL)
3494     return true;
3495
3496   // If we have a break label, then some case needed it.  That implies
3497   // that the switch statement as a whole can fall through.
3498   if (this->break_label_ != NULL)
3499     return true;
3500
3501   return this->clauses_->may_fall_through();
3502 }
3503
3504 // Convert to GENERIC.
3505
3506 tree
3507 Constant_switch_statement::do_get_tree(Translate_context* context)
3508 {
3509   tree switch_val_tree = this->val_->get_tree(context);
3510
3511   Unnamed_label* break_label = this->break_label_;
3512   if (break_label == NULL)
3513     break_label = new Unnamed_label(this->location());
3514
3515   tree stmt_list = NULL_TREE;
3516   tree s = build3(SWITCH_EXPR, void_type_node, switch_val_tree,
3517                   this->clauses_->get_constant_tree(context, break_label),
3518                   NULL_TREE);
3519   SET_EXPR_LOCATION(s, this->location());
3520   append_to_statement_list(s, &stmt_list);
3521
3522   append_to_statement_list(break_label->get_definition(), &stmt_list);
3523
3524   return stmt_list;
3525 }
3526
3527 // Class Switch_statement.
3528
3529 // Traversal.
3530
3531 int
3532 Switch_statement::do_traverse(Traverse* traverse)
3533 {
3534   if (this->val_ != NULL)
3535     {
3536       if (this->traverse_expression(traverse, &this->val_) == TRAVERSE_EXIT)
3537         return TRAVERSE_EXIT;
3538     }
3539   return this->clauses_->traverse(traverse);
3540 }
3541
3542 // Lower a Switch_statement to a Constant_switch_statement or a series
3543 // of if statements.
3544
3545 Statement*
3546 Switch_statement::do_lower(Gogo*, Block* enclosing)
3547 {
3548   source_location loc = this->location();
3549
3550   if (this->val_ != NULL
3551       && (this->val_->is_error_expression()
3552           || this->val_->type()->is_error_type()))
3553     return Statement::make_error_statement(loc);
3554
3555   if (this->val_ != NULL
3556       && this->val_->type()->integer_type() != NULL
3557       && !this->clauses_->empty()
3558       && this->clauses_->is_constant())
3559     return new Constant_switch_statement(this->val_, this->clauses_,
3560                                          this->break_label_, loc);
3561
3562   Block* b = new Block(enclosing, loc);
3563
3564   if (this->clauses_->empty())
3565     {
3566       Expression* val = this->val_;
3567       if (val == NULL)
3568         val = Expression::make_boolean(true, loc);
3569       return Statement::make_statement(val);
3570     }
3571
3572   Temporary_statement* val_temp;
3573   if (this->val_ == NULL)
3574     val_temp = NULL;
3575   else
3576     {
3577       // var val_temp VAL_TYPE = VAL
3578       val_temp = Statement::make_temporary(NULL, this->val_, loc);
3579       b->add_statement(val_temp);
3580     }
3581
3582   this->clauses_->lower(b, val_temp, this->break_label());
3583
3584   Statement* s = Statement::make_unnamed_label_statement(this->break_label_);
3585   b->add_statement(s);
3586
3587   return Statement::make_block_statement(b, loc);
3588 }
3589
3590 // Return the break label for this switch statement, creating it if
3591 // necessary.
3592
3593 Unnamed_label*
3594 Switch_statement::break_label()
3595 {
3596   if (this->break_label_ == NULL)
3597     this->break_label_ = new Unnamed_label(this->location());
3598   return this->break_label_;
3599 }
3600
3601 // Make a switch statement.
3602
3603 Switch_statement*
3604 Statement::make_switch_statement(Expression* val, source_location location)
3605 {
3606   return new Switch_statement(val, location);
3607 }
3608
3609 // Class Type_case_clauses::Type_case_clause.
3610
3611 // Traversal.
3612
3613 int
3614 Type_case_clauses::Type_case_clause::traverse(Traverse* traverse)
3615 {
3616   if (!this->is_default_
3617       && ((traverse->traverse_mask()
3618            & (Traverse::traverse_types | Traverse::traverse_expressions)) != 0)
3619       && Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3620     return TRAVERSE_EXIT;
3621   if (this->statements_ != NULL)
3622     return this->statements_->traverse(traverse);
3623   return TRAVERSE_CONTINUE;
3624 }
3625
3626 // Lower one clause in a type switch.  Add statements to the block B.
3627 // The type descriptor we are switching on is in DESCRIPTOR_TEMP.
3628 // BREAK_LABEL is the label at the end of the type switch.
3629 // *STMTS_LABEL, if not NULL, is a label to put at the start of the
3630 // statements.
3631
3632 void
3633 Type_case_clauses::Type_case_clause::lower(Block* b,
3634                                            Temporary_statement* descriptor_temp,
3635                                            Unnamed_label* break_label,
3636                                            Unnamed_label** stmts_label) const
3637 {
3638   source_location loc = this->location_;
3639
3640   Unnamed_label* next_case_label = NULL;
3641   if (!this->is_default_)
3642     {
3643       Type* type = this->type_;
3644
3645       Expression* cond;
3646       // The language permits case nil, which is of course a constant
3647       // rather than a type.  It will appear here as an invalid
3648       // forwarding type.
3649       if (type->is_nil_constant_as_type())
3650         {
3651           Expression* ref =
3652             Expression::make_temporary_reference(descriptor_temp, loc);
3653           cond = Expression::make_binary(OPERATOR_EQEQ, ref,
3654                                          Expression::make_nil(loc),
3655                                          loc);
3656         }
3657       else
3658         {
3659           Expression* func;
3660           if (type->interface_type() == NULL)
3661             {
3662               // func ifacetypeeq(*descriptor, *descriptor) bool
3663               static Named_object* ifacetypeeq;
3664               if (ifacetypeeq == NULL)
3665                 {
3666                   const source_location bloc = BUILTINS_LOCATION;
3667                   Typed_identifier_list* param_types =
3668                     new Typed_identifier_list();
3669                   Type* descriptor_type = Type::make_type_descriptor_ptr_type();
3670                   param_types->push_back(Typed_identifier("a", descriptor_type,
3671                                                           bloc));
3672                   param_types->push_back(Typed_identifier("b", descriptor_type,
3673                                                           bloc));
3674                   Typed_identifier_list* ret_types =
3675                     new Typed_identifier_list();
3676                   Type* bool_type = Type::lookup_bool_type();
3677                   ret_types->push_back(Typed_identifier("", bool_type, bloc));
3678                   Function_type* fntype = Type::make_function_type(NULL,
3679                                                                    param_types,
3680                                                                    ret_types,
3681                                                                    bloc);
3682                   ifacetypeeq =
3683                     Named_object::make_function_declaration("ifacetypeeq", NULL,
3684                                                             fntype, bloc);
3685                   const char* n = "runtime.ifacetypeeq";
3686                   ifacetypeeq->func_declaration_value()->set_asm_name(n);
3687                 }
3688
3689               // ifacetypeeq(descriptor_temp, DESCRIPTOR)
3690               func = Expression::make_func_reference(ifacetypeeq, NULL, loc);
3691             }
3692           else
3693             {
3694               // func ifaceI2Tp(*descriptor, *descriptor) bool
3695               static Named_object* ifaceI2Tp;
3696               if (ifaceI2Tp == NULL)
3697                 {
3698                   const source_location bloc = BUILTINS_LOCATION;
3699                   Typed_identifier_list* param_types =
3700                     new Typed_identifier_list();
3701                   Type* descriptor_type = Type::make_type_descriptor_ptr_type();
3702                   param_types->push_back(Typed_identifier("a", descriptor_type,
3703                                                           bloc));
3704                   param_types->push_back(Typed_identifier("b", descriptor_type,
3705                                                           bloc));
3706                   Typed_identifier_list* ret_types =
3707                     new Typed_identifier_list();
3708                   Type* bool_type = Type::lookup_bool_type();
3709                   ret_types->push_back(Typed_identifier("", bool_type, bloc));
3710                   Function_type* fntype = Type::make_function_type(NULL,
3711                                                                    param_types,
3712                                                                    ret_types,
3713                                                                    bloc);
3714                   ifaceI2Tp =
3715                     Named_object::make_function_declaration("ifaceI2Tp", NULL,
3716                                                             fntype, bloc);
3717                   const char* n = "runtime.ifaceI2Tp";
3718                   ifaceI2Tp->func_declaration_value()->set_asm_name(n);
3719                 }
3720
3721               // ifaceI2Tp(descriptor_temp, DESCRIPTOR)
3722               func = Expression::make_func_reference(ifaceI2Tp, NULL, loc);
3723             }
3724           Expression_list* params = new Expression_list();
3725           params->push_back(Expression::make_type_descriptor(type, loc));
3726           Expression* ref =
3727             Expression::make_temporary_reference(descriptor_temp, loc);
3728           params->push_back(ref);
3729           cond = Expression::make_call(func, params, false, loc);
3730         }
3731
3732       Unnamed_label* dest;
3733       if (!this->is_fallthrough_)
3734         {
3735           // if !COND { goto NEXT_CASE_LABEL }
3736           next_case_label = new Unnamed_label(UNKNOWN_LOCATION);
3737           dest = next_case_label;
3738           cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
3739         }
3740       else
3741         {
3742           // if COND { goto STMTS_LABEL }
3743           gcc_assert(stmts_label != NULL);
3744           if (*stmts_label == NULL)
3745             *stmts_label = new Unnamed_label(UNKNOWN_LOCATION);
3746           dest = *stmts_label;
3747         }
3748       Block* then_block = new Block(b, loc);
3749       Statement* s = Statement::make_goto_unnamed_statement(dest, loc);
3750       then_block->add_statement(s);
3751       s = Statement::make_if_statement(cond, then_block, NULL, loc);
3752       b->add_statement(s);
3753     }
3754
3755   if (this->statements_ != NULL
3756       || (!this->is_fallthrough_
3757           && stmts_label != NULL
3758           && *stmts_label != NULL))
3759     {
3760       gcc_assert(!this->is_fallthrough_);
3761       if (stmts_label != NULL && *stmts_label != NULL)
3762         {
3763           gcc_assert(!this->is_default_);
3764           if (this->statements_ != NULL)
3765             (*stmts_label)->set_location(this->statements_->start_location());
3766           Statement* s = Statement::make_unnamed_label_statement(*stmts_label);
3767           b->add_statement(s);
3768           *stmts_label = NULL;
3769         }
3770       if (this->statements_ != NULL)
3771         b->add_statement(Statement::make_block_statement(this->statements_,
3772                                                          loc));
3773     }
3774
3775   if (this->is_fallthrough_)
3776     gcc_assert(next_case_label == NULL);
3777   else
3778     {
3779       source_location gloc = (this->statements_ == NULL
3780                               ? loc
3781                               : this->statements_->end_location());
3782       b->add_statement(Statement::make_goto_unnamed_statement(break_label,
3783                                                               gloc));
3784       if (next_case_label != NULL)
3785         {
3786           Statement* s =
3787             Statement::make_unnamed_label_statement(next_case_label);
3788           b->add_statement(s);
3789         }
3790     }
3791 }
3792
3793 // Class Type_case_clauses.
3794
3795 // Traversal.
3796
3797 int
3798 Type_case_clauses::traverse(Traverse* traverse)
3799 {
3800   for (Type_clauses::iterator p = this->clauses_.begin();
3801        p != this->clauses_.end();
3802        ++p)
3803     {
3804       if (p->traverse(traverse) == TRAVERSE_EXIT)
3805         return TRAVERSE_EXIT;
3806     }
3807   return TRAVERSE_CONTINUE;
3808 }
3809
3810 // Check for duplicate types.
3811
3812 void
3813 Type_case_clauses::check_duplicates() const
3814 {
3815   typedef Unordered_set_hash(const Type*, Type_hash_identical,
3816                              Type_identical) Types_seen;
3817   Types_seen types_seen;
3818   for (Type_clauses::const_iterator p = this->clauses_.begin();
3819        p != this->clauses_.end();
3820        ++p)
3821     {
3822       Type* t = p->type();
3823       if (t == NULL)
3824         continue;
3825       if (t->is_nil_constant_as_type())
3826         t = Type::make_nil_type();
3827       std::pair<Types_seen::iterator, bool> ins = types_seen.insert(t);
3828       if (!ins.second)
3829         error_at(p->location(), "duplicate type in switch");
3830     }
3831 }
3832
3833 // Lower the clauses in a type switch.  Add statements to the block B.
3834 // The type descriptor we are switching on is in DESCRIPTOR_TEMP.
3835 // BREAK_LABEL is the label at the end of the type switch.
3836
3837 void
3838 Type_case_clauses::lower(Block* b, Temporary_statement* descriptor_temp,
3839                          Unnamed_label* break_label) const
3840 {
3841   const Type_case_clause* default_case = NULL;
3842
3843   Unnamed_label* stmts_label = NULL;
3844   for (Type_clauses::const_iterator p = this->clauses_.begin();
3845        p != this->clauses_.end();
3846        ++p)
3847     {
3848       if (!p->is_default())
3849         p->lower(b, descriptor_temp, break_label, &stmts_label);
3850       else
3851         {
3852           // We are generating a series of tests, which means that we
3853           // need to move the default case to the end.
3854           default_case = &*p;
3855         }
3856     }
3857   gcc_assert(stmts_label == NULL);
3858
3859   if (default_case != NULL)
3860     default_case->lower(b, descriptor_temp, break_label, NULL);
3861 }
3862
3863 // Class Type_switch_statement.
3864
3865 // Traversal.
3866
3867 int
3868 Type_switch_statement::do_traverse(Traverse* traverse)
3869 {
3870   if (this->var_ == NULL)
3871     {
3872       if (this->traverse_expression(traverse, &this->expr_) == TRAVERSE_EXIT)
3873         return TRAVERSE_EXIT;
3874     }
3875   if (this->clauses_ != NULL)
3876     return this->clauses_->traverse(traverse);
3877   return TRAVERSE_CONTINUE;
3878 }
3879
3880 // Lower a type switch statement to a series of if statements.  The gc
3881 // compiler is able to generate a table in some cases.  However, that
3882 // does not work for us because we may have type descriptors in
3883 // different shared libraries, so we can't compare them with simple
3884 // equality testing.
3885
3886 Statement*
3887 Type_switch_statement::do_lower(Gogo*, Block* enclosing)
3888 {
3889   const source_location loc = this->location();
3890
3891   if (this->clauses_ != NULL)
3892     this->clauses_->check_duplicates();
3893
3894   Block* b = new Block(enclosing, loc);
3895
3896   Type* val_type = (this->var_ != NULL
3897                     ? this->var_->var_value()->type()
3898                     : this->expr_->type());
3899
3900   // var descriptor_temp DESCRIPTOR_TYPE
3901   Type* descriptor_type = Type::make_type_descriptor_ptr_type();
3902   Temporary_statement* descriptor_temp =
3903     Statement::make_temporary(descriptor_type, NULL, loc);
3904   b->add_statement(descriptor_temp);
3905
3906   if (val_type->interface_type() == NULL)
3907     {
3908       // Doing a type switch on a non-interface type.  Should we issue
3909       // a warning for this case?
3910       Expression* lhs = Expression::make_temporary_reference(descriptor_temp,
3911                                                              loc);
3912       Expression* rhs;
3913       if (val_type->is_nil_type())
3914         rhs = Expression::make_nil(loc);
3915       else
3916         {
3917           if (val_type->is_abstract())
3918             val_type = val_type->make_non_abstract_type();
3919           rhs = Expression::make_type_descriptor(val_type, loc);
3920         }
3921       Statement* s = Statement::make_assignment(lhs, rhs, loc);
3922       b->add_statement(s);
3923     }
3924   else
3925     {
3926       const source_location bloc = BUILTINS_LOCATION;
3927
3928       // func {efacetype,ifacetype}(*interface) *descriptor
3929       // FIXME: This should be inlined.
3930       Typed_identifier_list* param_types = new Typed_identifier_list();
3931       param_types->push_back(Typed_identifier("i", val_type, bloc));
3932       Typed_identifier_list* ret_types = new Typed_identifier_list();
3933       ret_types->push_back(Typed_identifier("", descriptor_type, bloc));
3934       Function_type* fntype = Type::make_function_type(NULL, param_types,
3935                                                        ret_types, bloc);
3936       bool is_empty = val_type->interface_type()->is_empty();
3937       const char* fnname = is_empty ? "efacetype" : "ifacetype";
3938       Named_object* fn =
3939         Named_object::make_function_declaration(fnname, NULL, fntype, bloc);
3940       const char* asm_name = (is_empty
3941                               ? "runtime.efacetype"
3942                               : "runtime.ifacetype");
3943       fn->func_declaration_value()->set_asm_name(asm_name);
3944
3945       // descriptor_temp = ifacetype(val_temp)
3946       Expression* func = Expression::make_func_reference(fn, NULL, loc);
3947       Expression_list* params = new Expression_list();
3948       Expression* ref;
3949       if (this->var_ == NULL)
3950         ref = this->expr_;
3951       else
3952         ref = Expression::make_var_reference(this->var_, loc);
3953       params->push_back(ref);
3954       Expression* call = Expression::make_call(func, params, false, loc);
3955       Expression* lhs = Expression::make_temporary_reference(descriptor_temp,
3956                                                              loc);
3957       Statement* s = Statement::make_assignment(lhs, call, loc);
3958       b->add_statement(s);
3959     }
3960
3961   if (this->clauses_ != NULL)
3962     this->clauses_->lower(b, descriptor_temp, this->break_label());
3963
3964   Statement* s = Statement::make_unnamed_label_statement(this->break_label_);
3965   b->add_statement(s);
3966
3967   return Statement::make_block_statement(b, loc);
3968 }
3969
3970 // Return the break label for this type switch statement, creating it
3971 // if necessary.
3972
3973 Unnamed_label*
3974 Type_switch_statement::break_label()
3975 {
3976   if (this->break_label_ == NULL)
3977     this->break_label_ = new Unnamed_label(this->location());
3978   return this->break_label_;
3979 }
3980
3981 // Make a type switch statement.
3982
3983 Type_switch_statement*
3984 Statement::make_type_switch_statement(Named_object* var, Expression* expr,
3985                                       source_location location)
3986 {
3987   return new Type_switch_statement(var, expr, location);
3988 }
3989
3990 // Class Select_clauses::Select_clause.
3991
3992 // Traversal.
3993
3994 int
3995 Select_clauses::Select_clause::traverse(Traverse* traverse)
3996 {
3997   if (!this->is_lowered_
3998       && (traverse->traverse_mask()
3999           & (Traverse::traverse_types | Traverse::traverse_expressions)) != 0)
4000     {
4001       if (this->channel_ != NULL)
4002         {
4003           if (Expression::traverse(&this->channel_, traverse) == TRAVERSE_EXIT)
4004             return TRAVERSE_EXIT;
4005         }
4006       if (this->val_ != NULL)
4007         {
4008           if (Expression::traverse(&this->val_, traverse) == TRAVERSE_EXIT)
4009             return TRAVERSE_EXIT;
4010         }
4011     }
4012   if (this->statements_ != NULL)
4013     {
4014       if (this->statements_->traverse(traverse) == TRAVERSE_EXIT)
4015         return TRAVERSE_EXIT;
4016     }
4017   return TRAVERSE_CONTINUE;
4018 }
4019
4020 // Lowering.  Here we pull out the channel and the send values, to
4021 // enforce the order of evaluation.  We also add explicit send and
4022 // receive statements to the clauses.
4023
4024 void
4025 Select_clauses::Select_clause::lower(Block* b)
4026 {
4027   if (this->is_default_)
4028     {
4029       gcc_assert(this->channel_ == NULL && this->val_ == NULL);
4030       this->is_lowered_ = true;
4031       return;
4032     }
4033
4034   source_location loc = this->location_;
4035
4036   // Evaluate the channel before the select statement.
4037   Temporary_statement* channel_temp = Statement::make_temporary(NULL,
4038                                                                 this->channel_,
4039                                                                 loc);
4040   b->add_statement(channel_temp);
4041   this->channel_ = Expression::make_temporary_reference(channel_temp, loc);
4042
4043   // If this is a send clause, evaluate the value to send before the
4044   // select statement.
4045   Temporary_statement* val_temp = NULL;
4046   if (this->is_send_)
4047     {
4048       val_temp = Statement::make_temporary(NULL, this->val_, loc);
4049       b->add_statement(val_temp);
4050     }
4051
4052   // Add the send or receive before the rest of the statements if any.
4053   Block *init = new Block(b, loc);
4054   Expression* ref = Expression::make_temporary_reference(channel_temp, loc);
4055   if (this->is_send_)
4056     {
4057       Expression* ref2 = Expression::make_temporary_reference(val_temp, loc);
4058       Send_expression* send = Expression::make_send(ref, ref2, loc);
4059       send->discarding_value();
4060       send->set_for_select();
4061       init->add_statement(Statement::make_statement(send));
4062     }
4063   else
4064     {
4065       Receive_expression* recv = Expression::make_receive(ref, loc);
4066       recv->set_for_select();
4067       if (this->val_ != NULL)
4068         {
4069           gcc_assert(this->var_ == NULL);
4070           init->add_statement(Statement::make_assignment(this->val_, recv,
4071                                                          loc));
4072         }
4073       else if (this->var_ != NULL)
4074         {
4075           this->var_->var_value()->set_init(recv);
4076           this->var_->var_value()->clear_type_from_chan_element();
4077         }
4078       else
4079         {
4080           recv->discarding_value();
4081           init->add_statement(Statement::make_statement(recv));
4082         }
4083     }
4084
4085   if (this->statements_ != NULL)
4086     init->add_statement(Statement::make_block_statement(this->statements_,
4087                                                         loc));
4088
4089   this->statements_ = init;
4090
4091   // Now all references should be handled through the statements, not
4092   // through here.
4093   this->is_lowered_ = true;
4094   this->val_ = NULL;
4095   this->var_ = NULL;
4096 }
4097
4098 // Determine types.
4099
4100 void
4101 Select_clauses::Select_clause::determine_types()
4102 {
4103   gcc_assert(this->is_lowered_);
4104   if (this->statements_ != NULL)
4105     this->statements_->determine_types();
4106 }
4107
4108 // Whether this clause may fall through to the statement which follows
4109 // the overall select statement.
4110
4111 bool
4112 Select_clauses::Select_clause::may_fall_through() const
4113 {
4114   if (this->statements_ == NULL)
4115     return true;
4116   return this->statements_->may_fall_through();
4117 }
4118
4119 // Return a tree for the statements to execute.
4120
4121 tree
4122 Select_clauses::Select_clause::get_statements_tree(Translate_context* context)
4123 {
4124   if (this->statements_ == NULL)
4125     return NULL_TREE;
4126   return this->statements_->get_tree(context);
4127 }
4128
4129 // Class Select_clauses.
4130
4131 // Traversal.
4132
4133 int
4134 Select_clauses::traverse(Traverse* traverse)
4135 {
4136   for (Clauses::iterator p = this->clauses_.begin();
4137        p != this->clauses_.end();
4138        ++p)
4139     {
4140       if (p->traverse(traverse) == TRAVERSE_EXIT)
4141         return TRAVERSE_EXIT;
4142     }
4143   return TRAVERSE_CONTINUE;
4144 }
4145
4146 // Lowering.  Here we pull out the channel and the send values, to
4147 // enforce the order of evaluation.  We also add explicit send and
4148 // receive statements to the clauses.
4149
4150 void
4151 Select_clauses::lower(Block* b)
4152 {
4153   for (Clauses::iterator p = this->clauses_.begin();
4154        p != this->clauses_.end();
4155        ++p)
4156     p->lower(b);
4157 }
4158
4159 // Determine types.
4160
4161 void
4162 Select_clauses::determine_types()
4163 {
4164   for (Clauses::iterator p = this->clauses_.begin();
4165        p != this->clauses_.end();
4166        ++p)
4167     p->determine_types();
4168 }
4169
4170 // Return whether these select clauses fall through to the statement
4171 // following the overall select statement.
4172
4173 bool
4174 Select_clauses::may_fall_through() const
4175 {
4176   for (Clauses::const_iterator p = this->clauses_.begin();
4177        p != this->clauses_.end();
4178        ++p)
4179     if (p->may_fall_through())
4180       return true;
4181   return false;
4182 }
4183
4184 // Return a tree.  We build a call to
4185 //   size_t __go_select(size_t count, _Bool has_default,
4186 //                      channel* channels, _Bool* is_send)
4187 //
4188 // There are COUNT entries in the CHANNELS and IS_SEND arrays.  The
4189 // value in the IS_SEND array is true for send, false for receive.
4190 // __go_select returns an integer from 0 to COUNT, inclusive.  A
4191 // return of 0 means that the default case should be run; this only
4192 // happens if HAS_DEFAULT is non-zero.  Otherwise the number indicates
4193 // the case to run.
4194
4195 // FIXME: This doesn't handle channels which send interface types
4196 // where the receiver has a static type which matches that interface.
4197
4198 tree
4199 Select_clauses::get_tree(Translate_context* context,
4200                          Unnamed_label *break_label,
4201                          source_location location)
4202 {
4203   size_t count = this->clauses_.size();
4204   VEC(constructor_elt, gc)* chan_init = VEC_alloc(constructor_elt, gc, count);
4205   VEC(constructor_elt, gc)* is_send_init = VEC_alloc(constructor_elt, gc,
4206                                                      count);
4207   Select_clause* default_clause = NULL;
4208   tree final_stmt_list = NULL_TREE;
4209   tree channel_type_tree = NULL_TREE;
4210
4211   size_t i = 0;
4212   for (Clauses::iterator p = this->clauses_.begin();
4213        p != this->clauses_.end();
4214        ++p)
4215     {
4216       if (p->is_default())
4217         {
4218           default_clause = &*p;
4219           --count;
4220           continue;
4221         }
4222
4223       if (p->channel()->type()->channel_type() == NULL)
4224         {
4225           // We should have given an error in the send or receive
4226           // statement we created via lowering.
4227           gcc_assert(saw_errors());
4228           return error_mark_node;
4229         }
4230
4231       tree channel_tree = p->channel()->get_tree(context);
4232       if (channel_tree == error_mark_node)
4233         return error_mark_node;
4234       channel_type_tree = TREE_TYPE(channel_tree);
4235
4236       constructor_elt* elt = VEC_quick_push(constructor_elt, chan_init, NULL);
4237       elt->index = build_int_cstu(sizetype, i);
4238       elt->value = channel_tree;
4239
4240       elt = VEC_quick_push(constructor_elt, is_send_init, NULL);
4241       elt->index = build_int_cstu(sizetype, i);
4242       elt->value = p->is_send() ? boolean_true_node : boolean_false_node;
4243
4244       ++i;
4245     }
4246   gcc_assert(i == count);
4247
4248   if (i == 0 && default_clause != NULL)
4249     {
4250       // There is only a default clause.
4251       gcc_assert(final_stmt_list == NULL_TREE);
4252       tree stmt_list = NULL_TREE;
4253       append_to_statement_list(default_clause->get_statements_tree(context),
4254                                &stmt_list);
4255       append_to_statement_list(break_label->get_definition(), &stmt_list);
4256       return stmt_list;
4257     }
4258
4259   tree pointer_chan_type_tree = (channel_type_tree == NULL_TREE
4260                                  ? ptr_type_node
4261                                  : build_pointer_type(channel_type_tree));
4262   tree chans_arg;
4263   tree pointer_boolean_type_tree = build_pointer_type(boolean_type_node);
4264   tree is_sends_arg;
4265
4266   if (i == 0)
4267     {
4268       chans_arg = fold_convert_loc(location, pointer_chan_type_tree,
4269                                    null_pointer_node);
4270       is_sends_arg = fold_convert_loc(location, pointer_boolean_type_tree,
4271                                       null_pointer_node);
4272     }
4273   else
4274     {
4275       tree index_type_tree = build_index_type(size_int(count - 1));
4276       tree chan_array_type_tree = build_array_type(channel_type_tree,
4277                                                    index_type_tree);
4278       tree chan_constructor = build_constructor(chan_array_type_tree,
4279                                                 chan_init);
4280       tree chan_var = create_tmp_var(chan_array_type_tree, "CHAN");
4281       DECL_IGNORED_P(chan_var) = 0;
4282       DECL_INITIAL(chan_var) = chan_constructor;
4283       DECL_SOURCE_LOCATION(chan_var) = location;
4284       TREE_ADDRESSABLE(chan_var) = 1;
4285       tree decl_expr = build1(DECL_EXPR, void_type_node, chan_var);
4286       SET_EXPR_LOCATION(decl_expr, location);
4287       append_to_statement_list(decl_expr, &final_stmt_list);
4288
4289       tree is_send_array_type_tree = build_array_type(boolean_type_node,
4290                                                       index_type_tree);
4291       tree is_send_constructor = build_constructor(is_send_array_type_tree,
4292                                                    is_send_init);
4293       tree is_send_var = create_tmp_var(is_send_array_type_tree, "ISSEND");
4294       DECL_IGNORED_P(is_send_var) = 0;
4295       DECL_INITIAL(is_send_var) = is_send_constructor;
4296       DECL_SOURCE_LOCATION(is_send_var) = location;
4297       TREE_ADDRESSABLE(is_send_var) = 1;
4298       decl_expr = build1(DECL_EXPR, void_type_node, is_send_var);
4299       SET_EXPR_LOCATION(decl_expr, location);
4300       append_to_statement_list(decl_expr, &final_stmt_list);
4301
4302       chans_arg = fold_convert_loc(location, pointer_chan_type_tree,
4303                                    build_fold_addr_expr_loc(location,
4304                                                             chan_var));
4305       is_sends_arg = fold_convert_loc(location, pointer_boolean_type_tree,
4306                                       build_fold_addr_expr_loc(location,
4307                                                                is_send_var));
4308     }
4309
4310   static tree select_fndecl;
4311   tree call = Gogo::call_builtin(&select_fndecl,
4312                                  location,
4313                                  "__go_select",
4314                                  4,
4315                                  sizetype,
4316                                  sizetype,
4317                                  size_int(count),
4318                                  boolean_type_node,
4319                                  (default_clause == NULL
4320                                   ? boolean_false_node
4321                                   : boolean_true_node),
4322                                  pointer_chan_type_tree,
4323                                  chans_arg,
4324                                  pointer_boolean_type_tree,
4325                                  is_sends_arg);
4326   if (call == error_mark_node)
4327     return error_mark_node;
4328
4329   tree stmt_list = NULL_TREE;
4330
4331   if (default_clause != NULL)
4332     this->add_clause_tree(context, 0, default_clause, break_label, &stmt_list);
4333
4334   i = 1;
4335   for (Clauses::iterator p = this->clauses_.begin();
4336        p != this->clauses_.end();
4337        ++p)
4338     {
4339       if (!p->is_default())
4340         {
4341           this->add_clause_tree(context, i, &*p, break_label, &stmt_list);
4342           ++i;
4343         }
4344     }
4345
4346   append_to_statement_list(break_label->get_definition(), &stmt_list);
4347
4348   tree switch_stmt = build3(SWITCH_EXPR, sizetype, call, stmt_list, NULL_TREE);
4349   SET_EXPR_LOCATION(switch_stmt, location);
4350   append_to_statement_list(switch_stmt, &final_stmt_list);
4351
4352   return final_stmt_list;
4353 }
4354
4355 // Add the tree for CLAUSE to STMT_LIST.
4356
4357 void
4358 Select_clauses::add_clause_tree(Translate_context* context, int case_index,
4359                                 Select_clause* clause,
4360                                 Unnamed_label* bottom_label, tree* stmt_list)
4361 {
4362   tree label = create_artificial_label(clause->location());
4363   append_to_statement_list(build3(CASE_LABEL_EXPR, void_type_node,
4364                                   build_int_cst(sizetype, case_index),
4365                                   NULL_TREE, label),
4366                            stmt_list);
4367   append_to_statement_list(clause->get_statements_tree(context), stmt_list);
4368   tree g = bottom_label->get_goto(clause->statements() == NULL
4369                                   ? clause->location()
4370                                   : clause->statements()->end_location());
4371   append_to_statement_list(g, stmt_list);
4372 }
4373
4374 // Class Select_statement.
4375
4376 // Return the break label for this switch statement, creating it if
4377 // necessary.
4378
4379 Unnamed_label*
4380 Select_statement::break_label()
4381 {
4382   if (this->break_label_ == NULL)
4383     this->break_label_ = new Unnamed_label(this->location());
4384   return this->break_label_;
4385 }
4386
4387 // Lower a select statement.  This will still return a select
4388 // statement, but it will be modified to implement the order of
4389 // evaluation rules, and to include the send and receive statements as
4390 // explicit statements in the clauses.
4391
4392 Statement*
4393 Select_statement::do_lower(Gogo*, Block* enclosing)
4394 {
4395   if (this->is_lowered_)
4396     return this;
4397   Block* b = new Block(enclosing, this->location());
4398   this->clauses_->lower(b);
4399   this->is_lowered_ = true;
4400   b->add_statement(this);
4401   return Statement::make_block_statement(b, this->location());
4402 }
4403
4404 // Return the tree for a select statement.
4405
4406 tree
4407 Select_statement::do_get_tree(Translate_context* context)
4408 {
4409   return this->clauses_->get_tree(context, this->break_label(),
4410                                   this->location());
4411 }
4412
4413 // Make a select statement.
4414
4415 Select_statement*
4416 Statement::make_select_statement(source_location location)
4417 {
4418   return new Select_statement(location);
4419 }
4420
4421 // Class For_statement.
4422
4423 // Traversal.
4424
4425 int
4426 For_statement::do_traverse(Traverse* traverse)
4427 {
4428   if (this->init_ != NULL)
4429     {
4430       if (this->init_->traverse(traverse) == TRAVERSE_EXIT)
4431         return TRAVERSE_EXIT;
4432     }
4433   if (this->cond_ != NULL)
4434     {
4435       if (this->traverse_expression(traverse, &this->cond_) == TRAVERSE_EXIT)
4436         return TRAVERSE_EXIT;
4437     }
4438   if (this->post_ != NULL)
4439     {
4440       if (this->post_->traverse(traverse) == TRAVERSE_EXIT)
4441         return TRAVERSE_EXIT;
4442     }
4443   return this->statements_->traverse(traverse);
4444 }
4445
4446 // Lower a For_statement into if statements and gotos.  Getting rid of
4447 // complex statements make it easier to handle garbage collection.
4448
4449 Statement*
4450 For_statement::do_lower(Gogo*, Block* enclosing)
4451 {
4452   Statement* s;
4453   source_location loc = this->location();
4454
4455   Block* b = new Block(enclosing, this->location());
4456   if (this->init_ != NULL)
4457     {
4458       s = Statement::make_block_statement(this->init_,
4459                                           this->init_->start_location());
4460       b->add_statement(s);
4461     }
4462
4463   Unnamed_label* entry = NULL;
4464   if (this->cond_ != NULL)
4465     {
4466       entry = new Unnamed_label(this->location());
4467       b->add_statement(Statement::make_goto_unnamed_statement(entry, loc));
4468     }
4469
4470   Unnamed_label* top = new Unnamed_label(this->location());
4471   b->add_statement(Statement::make_unnamed_label_statement(top));
4472
4473   s = Statement::make_block_statement(this->statements_,
4474                                       this->statements_->start_location());
4475   b->add_statement(s);
4476
4477   source_location end_loc = this->statements_->end_location();
4478
4479   Unnamed_label* cont = this->continue_label_;
4480   if (cont != NULL)
4481     b->add_statement(Statement::make_unnamed_label_statement(cont));
4482
4483   if (this->post_ != NULL)
4484     {
4485       s = Statement::make_block_statement(this->post_,
4486                                           this->post_->start_location());
4487       b->add_statement(s);
4488       end_loc = this->post_->end_location();
4489     }
4490
4491   if (this->cond_ == NULL)
4492     b->add_statement(Statement::make_goto_unnamed_statement(top, end_loc));
4493   else
4494     {
4495       b->add_statement(Statement::make_unnamed_label_statement(entry));
4496
4497       source_location cond_loc = this->cond_->location();
4498       Block* then_block = new Block(b, cond_loc);
4499       s = Statement::make_goto_unnamed_statement(top, cond_loc);
4500       then_block->add_statement(s);
4501
4502       s = Statement::make_if_statement(this->cond_, then_block, NULL, cond_loc);
4503       b->add_statement(s);
4504     }
4505
4506   Unnamed_label* brk = this->break_label_;
4507   if (brk != NULL)
4508     b->add_statement(Statement::make_unnamed_label_statement(brk));
4509
4510   b->set_end_location(end_loc);
4511
4512   return Statement::make_block_statement(b, loc);
4513 }
4514
4515 // Return the break label, creating it if necessary.
4516
4517 Unnamed_label*
4518 For_statement::break_label()
4519 {
4520   if (this->break_label_ == NULL)
4521     this->break_label_ = new Unnamed_label(this->location());
4522   return this->break_label_;
4523 }
4524
4525 // Return the continue LABEL_EXPR.
4526
4527 Unnamed_label*
4528 For_statement::continue_label()
4529 {
4530   if (this->continue_label_ == NULL)
4531     this->continue_label_ = new Unnamed_label(this->location());
4532   return this->continue_label_;
4533 }
4534
4535 // Set the break and continue labels a for statement.  This is used
4536 // when lowering a for range statement.
4537
4538 void
4539 For_statement::set_break_continue_labels(Unnamed_label* break_label,
4540                                          Unnamed_label* continue_label)
4541 {
4542   gcc_assert(this->break_label_ == NULL && this->continue_label_ == NULL);
4543   this->break_label_ = break_label;
4544   this->continue_label_ = continue_label;
4545 }
4546
4547 // Make a for statement.
4548
4549 For_statement*
4550 Statement::make_for_statement(Block* init, Expression* cond, Block* post,
4551                               source_location location)
4552 {
4553   return new For_statement(init, cond, post, location);
4554 }
4555
4556 // Class For_range_statement.
4557
4558 // Traversal.
4559
4560 int
4561 For_range_statement::do_traverse(Traverse* traverse)
4562 {
4563   if (this->traverse_expression(traverse, &this->index_var_) == TRAVERSE_EXIT)
4564     return TRAVERSE_EXIT;
4565   if (this->value_var_ != NULL)
4566     {
4567       if (this->traverse_expression(traverse, &this->value_var_)
4568           == TRAVERSE_EXIT)
4569         return TRAVERSE_EXIT;
4570     }
4571   if (this->traverse_expression(traverse, &this->range_) == TRAVERSE_EXIT)
4572     return TRAVERSE_EXIT;
4573   return this->statements_->traverse(traverse);
4574 }
4575
4576 // Lower a for range statement.  For simplicity we lower this into a
4577 // for statement, which will then be lowered in turn to goto
4578 // statements.
4579
4580 Statement*
4581 For_range_statement::do_lower(Gogo* gogo, Block* enclosing)
4582 {
4583   Type* range_type = this->range_->type();
4584   if (range_type->points_to() != NULL
4585       && range_type->points_to()->array_type() != NULL
4586       && !range_type->points_to()->is_open_array_type())
4587     range_type = range_type->points_to();
4588
4589   Type* index_type;
4590   Type* value_type = NULL;
4591   if (range_type->array_type() != NULL)
4592     {
4593       index_type = Type::lookup_integer_type("int");
4594       value_type = range_type->array_type()->element_type();
4595     }
4596   else if (range_type->is_string_type())
4597     {
4598       index_type = Type::lookup_integer_type("int");
4599       value_type = index_type;
4600     }
4601   else if (range_type->map_type() != NULL)
4602     {
4603       index_type = range_type->map_type()->key_type();
4604       value_type = range_type->map_type()->val_type();
4605     }
4606   else if (range_type->channel_type() != NULL)
4607     {
4608       index_type = range_type->channel_type()->element_type();
4609       if (this->value_var_ != NULL)
4610         {
4611           if (!this->value_var_->type()->is_error_type())
4612             this->report_error(_("too many variables for range clause "
4613                                  "with channel"));
4614           return Statement::make_error_statement(this->location());
4615         }
4616     }
4617   else
4618     {
4619       this->report_error(_("range clause must have "
4620                            "array, slice, setring, map, or channel type"));
4621       return Statement::make_error_statement(this->location());
4622     }
4623
4624   source_location loc = this->location();
4625   Block* temp_block = new Block(enclosing, loc);
4626
4627   Named_object* range_object = NULL;
4628   Temporary_statement* range_temp = NULL;
4629   Var_expression* ve = this->range_->var_expression();
4630   if (ve != NULL)
4631     range_object = ve->named_object();
4632   else
4633     {
4634       range_temp = Statement::make_temporary(NULL, this->range_, loc);
4635       temp_block->add_statement(range_temp);
4636     }
4637
4638   Temporary_statement* index_temp = Statement::make_temporary(index_type,
4639                                                               NULL, loc);
4640   temp_block->add_statement(index_temp);
4641
4642   Temporary_statement* value_temp = NULL;
4643   if (this->value_var_ != NULL)
4644     {
4645       value_temp = Statement::make_temporary(value_type, NULL, loc);
4646       temp_block->add_statement(value_temp);
4647     }
4648
4649   Block* body = new Block(temp_block, loc);
4650
4651   Block* init;
4652   Expression* cond;
4653   Block* iter_init;
4654   Block* post;
4655
4656   // Arrange to do a loop appropriate for the type.  We will produce
4657   //   for INIT ; COND ; POST {
4658   //           ITER_INIT
4659   //           INDEX = INDEX_TEMP
4660   //           VALUE = VALUE_TEMP // If there is a value
4661   //           original statements
4662   //   }
4663
4664   if (range_type->array_type() != NULL)
4665     this->lower_range_array(gogo, temp_block, body, range_object, range_temp,
4666                             index_temp, value_temp, &init, &cond, &iter_init,
4667                             &post);
4668   else if (range_type->is_string_type())
4669     this->lower_range_string(gogo, temp_block, body, range_object, range_temp,
4670                              index_temp, value_temp, &init, &cond, &iter_init,
4671                              &post);
4672   else if (range_type->map_type() != NULL)
4673     this->lower_range_map(gogo, temp_block, body, range_object, range_temp,
4674                           index_temp, value_temp, &init, &cond, &iter_init,
4675                           &post);
4676   else if (range_type->channel_type() != NULL)
4677     this->lower_range_channel(gogo, temp_block, body, range_object, range_temp,
4678                               index_temp, value_temp, &init, &cond, &iter_init,
4679                               &post);
4680   else
4681     gcc_unreachable();
4682
4683   if (iter_init != NULL)
4684     body->add_statement(Statement::make_block_statement(iter_init, loc));
4685
4686   Statement* assign;
4687   Expression* index_ref = Expression::make_temporary_reference(index_temp, loc);
4688   if (this->value_var_ == NULL)
4689     {
4690       assign = Statement::make_assignment(this->index_var_, index_ref, loc);
4691     }
4692   else
4693     {
4694       Expression_list* lhs = new Expression_list();
4695       lhs->push_back(this->index_var_);
4696       lhs->push_back(this->value_var_);
4697
4698       Expression_list* rhs = new Expression_list();
4699       rhs->push_back(index_ref);
4700       rhs->push_back(Expression::make_temporary_reference(value_temp, loc));
4701
4702       assign = Statement::make_tuple_assignment(lhs, rhs, loc);
4703     }
4704   body->add_statement(assign);
4705
4706   body->add_statement(Statement::make_block_statement(this->statements_, loc));
4707
4708   body->set_end_location(this->statements_->end_location());
4709
4710   For_statement* loop = Statement::make_for_statement(init, cond, post,
4711                                                       this->location());
4712   loop->add_statements(body);
4713   loop->set_break_continue_labels(this->break_label_, this->continue_label_);
4714
4715   temp_block->add_statement(loop);
4716
4717   return Statement::make_block_statement(temp_block, loc);
4718 }
4719
4720 // Return a reference to the range, which may be in RANGE_OBJECT or in
4721 // RANGE_TEMP.
4722
4723 Expression*
4724 For_range_statement::make_range_ref(Named_object* range_object,
4725                                     Temporary_statement* range_temp,
4726                                     source_location loc)
4727 {
4728   if (range_object != NULL)
4729     return Expression::make_var_reference(range_object, loc);
4730   else
4731     return Expression::make_temporary_reference(range_temp, loc);
4732 }
4733
4734 // Return a call to the predeclared function FUNCNAME passing a
4735 // reference to the temporary variable ARG.
4736
4737 Expression*
4738 For_range_statement::call_builtin(Gogo* gogo, const char* funcname,
4739                                   Expression* arg,
4740                                   source_location loc)
4741 {
4742   Named_object* no = gogo->lookup_global(funcname);
4743   gcc_assert(no != NULL && no->is_function_declaration());
4744   Expression* func = Expression::make_func_reference(no, NULL, loc);
4745   Expression_list* params = new Expression_list();
4746   params->push_back(arg);
4747   return Expression::make_call(func, params, false, loc);
4748 }
4749
4750 // Lower a for range over an array or slice.
4751
4752 void
4753 For_range_statement::lower_range_array(Gogo* gogo,
4754                                        Block* enclosing,
4755                                        Block* body_block,
4756                                        Named_object* range_object,
4757                                        Temporary_statement* range_temp,
4758                                        Temporary_statement* index_temp,
4759                                        Temporary_statement* value_temp,
4760                                        Block** pinit,
4761                                        Expression** pcond,
4762                                        Block** piter_init,
4763                                        Block** ppost)
4764 {
4765   source_location loc = this->location();
4766
4767   // The loop we generate:
4768   //   len_temp := len(range)
4769   //   for index_temp = 0; index_temp < len_temp; index_temp++ {
4770   //           value_temp = range[index_temp]
4771   //           index = index_temp
4772   //           value = value_temp
4773   //           original body
4774   //   }
4775
4776   // Set *PINIT to
4777   //   var len_temp int
4778   //   len_temp = len(range)
4779   //   index_temp = 0
4780
4781   Block* init = new Block(enclosing, loc);
4782
4783   Expression* ref = this->make_range_ref(range_object, range_temp, loc);
4784   Expression* len_call = this->call_builtin(gogo, "len", ref, loc);
4785   Temporary_statement* len_temp = Statement::make_temporary(index_temp->type(),
4786                                                             len_call, loc);
4787   init->add_statement(len_temp);
4788
4789   mpz_t zval;
4790   mpz_init_set_ui(zval, 0UL);
4791   Expression* zexpr = Expression::make_integer(&zval, NULL, loc);
4792   mpz_clear(zval);
4793
4794   ref = Expression::make_temporary_reference(index_temp, loc);
4795   Statement* s = Statement::make_assignment(ref, zexpr, loc);
4796   init->add_statement(s);
4797
4798   *pinit = init;
4799
4800   // Set *PCOND to
4801   //   index_temp < len_temp
4802
4803   ref = Expression::make_temporary_reference(index_temp, loc);
4804   Expression* ref2 = Expression::make_temporary_reference(len_temp, loc);
4805   Expression* lt = Expression::make_binary(OPERATOR_LT, ref, ref2, loc);
4806
4807   *pcond = lt;
4808
4809   // Set *PITER_INIT to
4810   //   value_temp = range[index_temp]
4811
4812   Block* iter_init = NULL;
4813   if (value_temp != NULL)
4814     {
4815       iter_init = new Block(body_block, loc);
4816
4817       ref = this->make_range_ref(range_object, range_temp, loc);
4818       Expression* ref2 = Expression::make_temporary_reference(index_temp, loc);
4819       Expression* index = Expression::make_index(ref, ref2, NULL, loc);
4820
4821       ref = Expression::make_temporary_reference(value_temp, loc);
4822       s = Statement::make_assignment(ref, index, loc);
4823
4824       iter_init->add_statement(s);
4825     }
4826   *piter_init = iter_init;
4827
4828   // Set *PPOST to
4829   //   index_temp++
4830
4831   Block* post = new Block(enclosing, loc);
4832   ref = Expression::make_temporary_reference(index_temp, loc);
4833   s = Statement::make_inc_statement(ref);
4834   post->add_statement(s);
4835   *ppost = post;
4836 }
4837
4838 // Lower a for range over a string.
4839
4840 void
4841 For_range_statement::lower_range_string(Gogo* gogo,
4842                                         Block* enclosing,
4843                                         Block* body_block,
4844                                         Named_object* range_object,
4845                                         Temporary_statement* range_temp,
4846                                         Temporary_statement* index_temp,
4847                                         Temporary_statement* value_temp,
4848                                         Block** pinit,
4849                                         Expression** pcond,
4850                                         Block** piter_init,
4851                                         Block** ppost)
4852 {
4853   source_location loc = this->location();
4854
4855   // The loop we generate:
4856   //   var next_index_temp int
4857   //   for index_temp = 0; ; index_temp = next_index_temp {
4858   //           next_index_temp, value_temp = stringiter2(range, index_temp)
4859   //           if next_index_temp == 0 {
4860   //                   break
4861   //           }
4862   //           index = index_temp
4863   //           value = value_temp
4864   //           original body
4865   //   }
4866
4867   // Set *PINIT to
4868   //   var next_index_temp int
4869   //   index_temp = 0
4870
4871   Block* init = new Block(enclosing, loc);
4872
4873   Temporary_statement* next_index_temp =
4874     Statement::make_temporary(index_temp->type(), NULL, loc);
4875   init->add_statement(next_index_temp);
4876
4877   mpz_t zval;
4878   mpz_init_set_ui(zval, 0UL);
4879   Expression* zexpr = Expression::make_integer(&zval, NULL, loc);
4880
4881   Expression* ref = Expression::make_temporary_reference(index_temp, loc);
4882   Statement* s = Statement::make_assignment(ref, zexpr, loc);
4883
4884   init->add_statement(s);
4885   *pinit = init;
4886
4887   // The loop has no condition.
4888
4889   *pcond = NULL;
4890
4891   // Set *PITER_INIT to
4892   //   next_index_temp = runtime.stringiter(range, index_temp)
4893   // or
4894   //   next_index_temp, value_temp = runtime.stringiter2(range, index_temp)
4895   // followed by
4896   //   if next_index_temp == 0 {
4897   //           break
4898   //   }
4899
4900   Block* iter_init = new Block(body_block, loc);
4901
4902   Named_object* no;
4903   if (value_temp == NULL)
4904     {
4905       static Named_object* stringiter;
4906       if (stringiter == NULL)
4907         {
4908           source_location bloc = BUILTINS_LOCATION;
4909           Type* int_type = gogo->lookup_global("int")->type_value();
4910
4911           Typed_identifier_list* params = new Typed_identifier_list();
4912           params->push_back(Typed_identifier("s", Type::make_string_type(),
4913                                              bloc));
4914           params->push_back(Typed_identifier("k", int_type, bloc));
4915
4916           Typed_identifier_list* results = new Typed_identifier_list();
4917           results->push_back(Typed_identifier("", int_type, bloc));
4918
4919           Function_type* fntype = Type::make_function_type(NULL, params,
4920                                                            results, bloc);
4921           stringiter = Named_object::make_function_declaration("stringiter",
4922                                                                NULL, fntype,
4923                                                                bloc);
4924           const char* n = "runtime.stringiter";
4925           stringiter->func_declaration_value()->set_asm_name(n);
4926         }
4927       no = stringiter;
4928     }
4929   else
4930     {
4931       static Named_object* stringiter2;
4932       if (stringiter2 == NULL)
4933         {
4934           source_location bloc = BUILTINS_LOCATION;
4935           Type* int_type = gogo->lookup_global("int")->type_value();
4936
4937           Typed_identifier_list* params = new Typed_identifier_list();
4938           params->push_back(Typed_identifier("s", Type::make_string_type(),
4939                                              bloc));
4940           params->push_back(Typed_identifier("k", int_type, bloc));
4941
4942           Typed_identifier_list* results = new Typed_identifier_list();
4943           results->push_back(Typed_identifier("", int_type, bloc));
4944           results->push_back(Typed_identifier("", int_type, bloc));
4945
4946           Function_type* fntype = Type::make_function_type(NULL, params,
4947                                                            results, bloc);
4948           stringiter2 = Named_object::make_function_declaration("stringiter",
4949                                                                 NULL, fntype,
4950                                                                 bloc);
4951           const char* n = "runtime.stringiter2";
4952           stringiter2->func_declaration_value()->set_asm_name(n);
4953         }
4954       no = stringiter2;
4955     }
4956
4957   Expression* func = Expression::make_func_reference(no, NULL, loc);
4958   Expression_list* params = new Expression_list();
4959   params->push_back(this->make_range_ref(range_object, range_temp, loc));
4960   params->push_back(Expression::make_temporary_reference(index_temp, loc));
4961   Call_expression* call = Expression::make_call(func, params, false, loc);
4962
4963   if (value_temp == NULL)
4964     {
4965       ref = Expression::make_temporary_reference(next_index_temp, loc);
4966       s = Statement::make_assignment(ref, call, loc);
4967     }
4968   else
4969     {
4970       Expression_list* lhs = new Expression_list();
4971       lhs->push_back(Expression::make_temporary_reference(next_index_temp,
4972                                                           loc));
4973       lhs->push_back(Expression::make_temporary_reference(value_temp, loc));
4974
4975       Expression_list* rhs = new Expression_list();
4976       rhs->push_back(Expression::make_call_result(call, 0));
4977       rhs->push_back(Expression::make_call_result(call, 1));
4978
4979       s = Statement::make_tuple_assignment(lhs, rhs, loc);
4980     }
4981   iter_init->add_statement(s);
4982
4983   ref = Expression::make_temporary_reference(next_index_temp, loc);
4984   zexpr = Expression::make_integer(&zval, NULL, loc);
4985   mpz_clear(zval);
4986   Expression* equals = Expression::make_binary(OPERATOR_EQEQ, ref, zexpr, loc);
4987
4988   Block* then_block = new Block(iter_init, loc);
4989   s = Statement::make_break_statement(this->break_label(), loc);
4990   then_block->add_statement(s);
4991
4992   s = Statement::make_if_statement(equals, then_block, NULL, loc);
4993   iter_init->add_statement(s);
4994
4995   *piter_init = iter_init;
4996
4997   // Set *PPOST to
4998   //   index_temp = next_index_temp
4999
5000   Block* post = new Block(enclosing, loc);
5001
5002   Expression* lhs = Expression::make_temporary_reference(index_temp, loc);
5003   Expression* rhs = Expression::make_temporary_reference(next_index_temp, loc);
5004   s = Statement::make_assignment(lhs, rhs, loc);
5005
5006   post->add_statement(s);
5007   *ppost = post;
5008 }
5009
5010 // Lower a for range over a map.
5011
5012 void
5013 For_range_statement::lower_range_map(Gogo* gogo,
5014                                      Block* enclosing,
5015                                      Block* body_block,
5016                                      Named_object* range_object,
5017                                      Temporary_statement* range_temp,
5018                                      Temporary_statement* index_temp,
5019                                      Temporary_statement* value_temp,
5020                                      Block** pinit,
5021                                      Expression** pcond,
5022                                      Block** piter_init,
5023                                      Block** ppost)
5024 {
5025   source_location loc = this->location();
5026
5027   // The runtime uses a struct to handle ranges over a map.  The
5028   // struct is four pointers long.  The first pointer is NULL when we
5029   // have completed the iteration.
5030
5031   // The loop we generate:
5032   //   var hiter map_iteration_struct
5033   //   for mapiterinit(range, &hiter); hiter[0] != nil; mapiternext(&hiter) {
5034   //           mapiter2(hiter, &index_temp, &value_temp)
5035   //           index = index_temp
5036   //           value = value_temp
5037   //           original body
5038   //   }
5039
5040   // Set *PINIT to
5041   //   var hiter map_iteration_struct
5042   //   runtime.mapiterinit(range, &hiter)
5043
5044   Block* init = new Block(enclosing, loc);
5045
5046   const unsigned long map_iteration_size = 4;
5047
5048   mpz_t ival;
5049   mpz_init_set_ui(ival, map_iteration_size);
5050   Expression* iexpr = Expression::make_integer(&ival, NULL, loc);
5051   mpz_clear(ival);
5052
5053   Type* byte_type = gogo->lookup_global("byte")->type_value();
5054   Type* ptr_type = Type::make_pointer_type(byte_type);
5055
5056   Type* map_iteration_type = Type::make_array_type(ptr_type, iexpr);
5057   Type* map_iteration_ptr = Type::make_pointer_type(map_iteration_type);
5058
5059   Temporary_statement* hiter = Statement::make_temporary(map_iteration_type,
5060                                                          NULL, loc);
5061   init->add_statement(hiter);
5062
5063   source_location bloc = BUILTINS_LOCATION;
5064   Typed_identifier_list* param_types = new Typed_identifier_list();
5065   param_types->push_back(Typed_identifier("map", this->range_->type(), bloc));
5066   param_types->push_back(Typed_identifier("it", map_iteration_ptr, bloc));
5067   Function_type* fntype = Type::make_function_type(NULL, param_types, NULL,
5068                                                    bloc);
5069
5070   Named_object* mapiterinit =
5071     Named_object::make_function_declaration("mapiterinit", NULL, fntype, bloc);
5072   const char* n = "runtime.mapiterinit";
5073   mapiterinit->func_declaration_value()->set_asm_name(n);
5074
5075   Expression* func = Expression::make_func_reference(mapiterinit, NULL, loc);
5076   Expression_list* params = new Expression_list();
5077   params->push_back(this->make_range_ref(range_object, range_temp, loc));
5078   Expression* ref = Expression::make_temporary_reference(hiter, loc);
5079   params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc));
5080   Expression* call = Expression::make_call(func, params, false, loc);
5081   init->add_statement(Statement::make_statement(call));
5082
5083   *pinit = init;
5084
5085   // Set *PCOND to
5086   //   hiter[0] != nil
5087
5088   ref = Expression::make_temporary_reference(hiter, loc);
5089
5090   mpz_t zval;
5091   mpz_init_set_ui(zval, 0UL);
5092   Expression* zexpr = Expression::make_integer(&zval, NULL, loc);
5093   mpz_clear(zval);
5094
5095   Expression* index = Expression::make_index(ref, zexpr, NULL, loc);
5096
5097   Expression* ne = Expression::make_binary(OPERATOR_NOTEQ, index,
5098                                            Expression::make_nil(loc),
5099                                            loc);
5100
5101   *pcond = ne;
5102
5103   // Set *PITER_INIT to
5104   //   mapiter1(hiter, &index_temp)
5105   // or
5106   //   mapiter2(hiter, &index_temp, &value_temp)
5107
5108   Block* iter_init = new Block(body_block, loc);
5109
5110   param_types = new Typed_identifier_list();
5111   param_types->push_back(Typed_identifier("hiter", map_iteration_ptr, bloc));
5112   Type* pkey_type = Type::make_pointer_type(index_temp->type());
5113   param_types->push_back(Typed_identifier("key", pkey_type, bloc));
5114   if (value_temp != NULL)
5115     {
5116       Type* pval_type = Type::make_pointer_type(value_temp->type());
5117       param_types->push_back(Typed_identifier("val", pval_type, bloc));
5118     }
5119   fntype = Type::make_function_type(NULL, param_types, NULL, bloc);
5120   n = value_temp == NULL ? "mapiter1" : "mapiter2";
5121   Named_object* mapiter = Named_object::make_function_declaration(n, NULL,
5122                                                                   fntype, bloc);
5123   n = value_temp == NULL ? "runtime.mapiter1" : "runtime.mapiter2";
5124   mapiter->func_declaration_value()->set_asm_name(n);
5125
5126   func = Expression::make_func_reference(mapiter, NULL, loc);
5127   params = new Expression_list();
5128   ref = Expression::make_temporary_reference(hiter, loc);
5129   params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc));
5130   ref = Expression::make_temporary_reference(index_temp, loc);
5131   params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc));
5132   if (value_temp != NULL)
5133     {
5134       ref = Expression::make_temporary_reference(value_temp, loc);
5135       params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc));
5136     }
5137   call = Expression::make_call(func, params, false, loc);
5138   iter_init->add_statement(Statement::make_statement(call));
5139
5140   *piter_init = iter_init;
5141
5142   // Set *PPOST to
5143   //   mapiternext(&hiter)
5144
5145   Block* post = new Block(enclosing, loc);
5146
5147   static Named_object* mapiternext;
5148   if (mapiternext == NULL)
5149     {
5150       param_types = new Typed_identifier_list();
5151       param_types->push_back(Typed_identifier("it", map_iteration_ptr, bloc));
5152       fntype = Type::make_function_type(NULL, param_types, NULL, bloc);
5153       mapiternext = Named_object::make_function_declaration("mapiternext",
5154                                                             NULL, fntype,
5155                                                             bloc);
5156       const char* n = "runtime.mapiternext";
5157       mapiternext->func_declaration_value()->set_asm_name(n);
5158     }
5159
5160   func = Expression::make_func_reference(mapiternext, NULL, loc);
5161   params = new Expression_list();
5162   ref = Expression::make_temporary_reference(hiter, loc);
5163   params->push_back(Expression::make_unary(OPERATOR_AND, ref, loc));
5164   call = Expression::make_call(func, params, false, loc);
5165   post->add_statement(Statement::make_statement(call));
5166
5167   *ppost = post;
5168 }
5169
5170 // Lower a for range over a channel.
5171
5172 void
5173 For_range_statement::lower_range_channel(Gogo* gogo,
5174                                          Block*,
5175                                          Block* body_block,
5176                                          Named_object* range_object,
5177                                          Temporary_statement* range_temp,
5178                                          Temporary_statement* index_temp,
5179                                          Temporary_statement* value_temp,
5180                                          Block** pinit,
5181                                          Expression** pcond,
5182                                          Block** piter_init,
5183                                          Block** ppost)
5184 {
5185   gcc_assert(value_temp == NULL);
5186
5187   source_location loc = this->location();
5188
5189   // The loop we generate:
5190   //   for {
5191   //           index_temp = <-range
5192   //           if closed(range) {
5193   //                   break
5194   //           }
5195   //           index = index_temp
5196   //           value = value_temp
5197   //           original body
5198   //   }
5199
5200   // We have no initialization code, no condition, and no post code.
5201
5202   *pinit = NULL;
5203   *pcond = NULL;
5204   *ppost = NULL;
5205
5206   // Set *PITER_INIT to
5207   //   index_temp = <-range
5208   //   if closed(range) {
5209   //           break
5210   //   }
5211
5212   Block* iter_init = new Block(body_block, loc);
5213
5214   Expression* ref = this->make_range_ref(range_object, range_temp, loc);
5215   Expression* cond = this->call_builtin(gogo, "closed", ref, loc);
5216
5217   ref = this->make_range_ref(range_object, range_temp, loc);
5218   Expression* recv = Expression::make_receive(ref, loc);
5219   ref = Expression::make_temporary_reference(index_temp, loc);
5220   Statement* s = Statement::make_assignment(ref, recv, loc);
5221   iter_init->add_statement(s);
5222
5223   Block* then_block = new Block(iter_init, loc);
5224   s = Statement::make_break_statement(this->break_label(), loc);
5225   then_block->add_statement(s);
5226
5227   s = Statement::make_if_statement(cond, then_block, NULL, loc);
5228   iter_init->add_statement(s);
5229
5230   *piter_init = iter_init;
5231 }
5232
5233 // Return the break LABEL_EXPR.
5234
5235 Unnamed_label*
5236 For_range_statement::break_label()
5237 {
5238   if (this->break_label_ == NULL)
5239     this->break_label_ = new Unnamed_label(this->location());
5240   return this->break_label_;
5241 }
5242
5243 // Return the continue LABEL_EXPR.
5244
5245 Unnamed_label*
5246 For_range_statement::continue_label()
5247 {
5248   if (this->continue_label_ == NULL)
5249     this->continue_label_ = new Unnamed_label(this->location());
5250   return this->continue_label_;
5251 }
5252
5253 // Make a for statement with a range clause.
5254
5255 For_range_statement*
5256 Statement::make_for_range_statement(Expression* index_var,
5257                                     Expression* value_var,
5258                                     Expression* range,
5259                                     source_location location)
5260 {
5261   return new For_range_statement(index_var, value_var, range, location);
5262 }