OSDN Git Service

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