github.com/kidsbmilk/gofronted_all@v0.0.0-20220701224323-6479d5976c5d/go/gogo.cc (about) 1 // gogo.cc -- Go frontend parsed representation. 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 <fstream> 10 11 #include "filenames.h" 12 13 #include "go-c.h" 14 #include "go-diagnostics.h" 15 #include "go-encode-id.h" 16 #include "go-dump.h" 17 #include "go-optimize.h" 18 #include "lex.h" 19 #include "types.h" 20 #include "statements.h" 21 #include "expressions.h" 22 #include "runtime.h" 23 #include "import.h" 24 #include "export.h" 25 #include "backend.h" 26 #include "gogo.h" 27 28 // Class Gogo. 29 30 Gogo::Gogo(Backend* backend, Linemap* linemap, int, int pointer_size) 31 : backend_(backend), 32 linemap_(linemap), 33 package_(NULL), 34 functions_(), 35 globals_(new Bindings(NULL)), 36 file_block_names_(), 37 imports_(), 38 imported_unsafe_(false), 39 current_file_imported_unsafe_(false), 40 current_file_imported_embed_(false), 41 packages_(), 42 init_functions_(), 43 var_deps_(), 44 need_init_fn_(false), 45 init_fn_name_(), 46 imported_init_fns_(), 47 pkgpath_(), 48 pkgpath_symbol_(), 49 prefix_(), 50 pkgpath_set_(false), 51 pkgpath_from_option_(false), 52 prefix_from_option_(false), 53 relative_import_path_(), 54 c_header_(), 55 check_divide_by_zero_(true), 56 check_divide_overflow_(true), 57 compiling_runtime_(false), 58 debug_escape_level_(0), 59 debug_optimization_(false), 60 nil_check_size_threshold_(4096), 61 need_eqtype_(false), 62 verify_types_(), 63 interface_types_(), 64 specific_type_functions_(), 65 specific_type_functions_are_written_(false), 66 named_types_are_converted_(false), 67 analysis_sets_(), 68 gc_roots_(), 69 type_descriptors_(), 70 imported_inlinable_functions_(), 71 imported_inline_functions_() 72 { 73 const Location loc = Linemap::predeclared_location(); 74 75 Named_type* uint8_type = Type::make_integer_type("uint8", true, 8, 76 RUNTIME_TYPE_KIND_UINT8); 77 this->add_named_type(uint8_type); 78 this->add_named_type(Type::make_integer_type("uint16", true, 16, 79 RUNTIME_TYPE_KIND_UINT16)); 80 this->add_named_type(Type::make_integer_type("uint32", true, 32, 81 RUNTIME_TYPE_KIND_UINT32)); 82 this->add_named_type(Type::make_integer_type("uint64", true, 64, 83 RUNTIME_TYPE_KIND_UINT64)); 84 85 this->add_named_type(Type::make_integer_type("int8", false, 8, 86 RUNTIME_TYPE_KIND_INT8)); 87 this->add_named_type(Type::make_integer_type("int16", false, 16, 88 RUNTIME_TYPE_KIND_INT16)); 89 Named_type* int32_type = Type::make_integer_type("int32", false, 32, 90 RUNTIME_TYPE_KIND_INT32); 91 this->add_named_type(int32_type); 92 this->add_named_type(Type::make_integer_type("int64", false, 64, 93 RUNTIME_TYPE_KIND_INT64)); 94 95 this->add_named_type(Type::make_float_type("float32", 32, 96 RUNTIME_TYPE_KIND_FLOAT32)); 97 this->add_named_type(Type::make_float_type("float64", 64, 98 RUNTIME_TYPE_KIND_FLOAT64)); 99 100 this->add_named_type(Type::make_complex_type("complex64", 64, 101 RUNTIME_TYPE_KIND_COMPLEX64)); 102 this->add_named_type(Type::make_complex_type("complex128", 128, 103 RUNTIME_TYPE_KIND_COMPLEX128)); 104 105 int int_type_size = pointer_size; 106 if (int_type_size < 32) 107 int_type_size = 32; 108 this->add_named_type(Type::make_integer_type("uint", true, 109 int_type_size, 110 RUNTIME_TYPE_KIND_UINT)); 111 Named_type* int_type = Type::make_integer_type("int", false, int_type_size, 112 RUNTIME_TYPE_KIND_INT); 113 this->add_named_type(int_type); 114 115 this->add_named_type(Type::make_integer_type("uintptr", true, 116 pointer_size, 117 RUNTIME_TYPE_KIND_UINTPTR)); 118 119 // "byte" is an alias for "uint8". 120 uint8_type->integer_type()->set_is_byte(); 121 this->add_named_type(Type::make_integer_type_alias("byte", uint8_type)); 122 123 // "rune" is an alias for "int32". 124 int32_type->integer_type()->set_is_rune(); 125 this->add_named_type(Type::make_integer_type_alias("rune", int32_type)); 126 127 this->add_named_type(Type::make_named_bool_type()); 128 129 this->add_named_type(Type::make_named_string_type()); 130 131 // "error" is interface { Error() string }. 132 { 133 Typed_identifier_list *methods = new Typed_identifier_list; 134 Typed_identifier_list *results = new Typed_identifier_list; 135 results->push_back(Typed_identifier("", Type::lookup_string_type(), loc)); 136 Type *method_type = Type::make_function_type(NULL, NULL, results, loc); 137 methods->push_back(Typed_identifier("Error", method_type, loc)); 138 Interface_type *error_iface = Type::make_interface_type(methods, loc); 139 error_iface->finalize_methods(); 140 Named_type *error_type = Named_object::make_type("error", NULL, error_iface, loc)->type_value(); 141 this->add_named_type(error_type); 142 } 143 144 // "any" is an alias for the empty interface type. 145 { 146 Type* empty = Type::make_empty_interface_type(loc); 147 Named_object* no = Named_object::make_type("any", NULL, empty, loc); 148 Named_type* nt = no->type_value(); 149 nt->set_is_alias(); 150 this->add_named_type(nt); 151 } 152 153 this->globals_->add_constant(Typed_identifier("true", 154 Type::make_boolean_type(), 155 loc), 156 NULL, 157 Expression::make_boolean(true, loc), 158 0); 159 this->globals_->add_constant(Typed_identifier("false", 160 Type::make_boolean_type(), 161 loc), 162 NULL, 163 Expression::make_boolean(false, loc), 164 0); 165 166 this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(), 167 loc), 168 NULL, 169 Expression::make_nil(loc), 170 0); 171 172 Type* abstract_int_type = Type::make_abstract_integer_type(); 173 this->globals_->add_constant(Typed_identifier("iota", abstract_int_type, 174 loc), 175 NULL, 176 Expression::make_iota(), 177 0); 178 179 Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc); 180 new_type->set_is_varargs(); 181 new_type->set_is_builtin(); 182 this->globals_->add_function_declaration("new", NULL, new_type, loc); 183 184 Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc); 185 make_type->set_is_varargs(); 186 make_type->set_is_builtin(); 187 this->globals_->add_function_declaration("make", NULL, make_type, loc); 188 189 Typed_identifier_list* len_result = new Typed_identifier_list(); 190 len_result->push_back(Typed_identifier("", int_type, loc)); 191 Function_type* len_type = Type::make_function_type(NULL, NULL, len_result, 192 loc); 193 len_type->set_is_builtin(); 194 this->globals_->add_function_declaration("len", NULL, len_type, loc); 195 196 Typed_identifier_list* cap_result = new Typed_identifier_list(); 197 cap_result->push_back(Typed_identifier("", int_type, loc)); 198 Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result, 199 loc); 200 cap_type->set_is_builtin(); 201 this->globals_->add_function_declaration("cap", NULL, cap_type, loc); 202 203 Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc); 204 print_type->set_is_varargs(); 205 print_type->set_is_builtin(); 206 this->globals_->add_function_declaration("print", NULL, print_type, loc); 207 208 print_type = Type::make_function_type(NULL, NULL, NULL, loc); 209 print_type->set_is_varargs(); 210 print_type->set_is_builtin(); 211 this->globals_->add_function_declaration("println", NULL, print_type, loc); 212 213 Type *empty = Type::make_empty_interface_type(loc); 214 Typed_identifier_list* panic_parms = new Typed_identifier_list(); 215 panic_parms->push_back(Typed_identifier("e", empty, loc)); 216 Function_type *panic_type = Type::make_function_type(NULL, panic_parms, 217 NULL, loc); 218 panic_type->set_is_builtin(); 219 this->globals_->add_function_declaration("panic", NULL, panic_type, loc); 220 221 Typed_identifier_list* recover_result = new Typed_identifier_list(); 222 recover_result->push_back(Typed_identifier("", empty, loc)); 223 Function_type* recover_type = Type::make_function_type(NULL, NULL, 224 recover_result, 225 loc); 226 recover_type->set_is_builtin(); 227 this->globals_->add_function_declaration("recover", NULL, recover_type, loc); 228 229 Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc); 230 close_type->set_is_varargs(); 231 close_type->set_is_builtin(); 232 this->globals_->add_function_declaration("close", NULL, close_type, loc); 233 234 Typed_identifier_list* copy_result = new Typed_identifier_list(); 235 copy_result->push_back(Typed_identifier("", int_type, loc)); 236 Function_type* copy_type = Type::make_function_type(NULL, NULL, 237 copy_result, loc); 238 copy_type->set_is_varargs(); 239 copy_type->set_is_builtin(); 240 this->globals_->add_function_declaration("copy", NULL, copy_type, loc); 241 242 Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc); 243 append_type->set_is_varargs(); 244 append_type->set_is_builtin(); 245 this->globals_->add_function_declaration("append", NULL, append_type, loc); 246 247 Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc); 248 complex_type->set_is_varargs(); 249 complex_type->set_is_builtin(); 250 this->globals_->add_function_declaration("complex", NULL, complex_type, loc); 251 252 Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc); 253 real_type->set_is_varargs(); 254 real_type->set_is_builtin(); 255 this->globals_->add_function_declaration("real", NULL, real_type, loc); 256 257 Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc); 258 imag_type->set_is_varargs(); 259 imag_type->set_is_builtin(); 260 this->globals_->add_function_declaration("imag", NULL, imag_type, loc); 261 262 Function_type* delete_type = Type::make_function_type(NULL, NULL, NULL, loc); 263 delete_type->set_is_varargs(); 264 delete_type->set_is_builtin(); 265 this->globals_->add_function_declaration("delete", NULL, delete_type, loc); 266 } 267 268 std::string 269 Gogo::pkgpath_for_symbol(const std::string& pkgpath) 270 { 271 go_assert(!pkgpath.empty()); 272 return go_encode_id(pkgpath); 273 } 274 275 // Return a hash code for a string, given a starting hash. 276 277 unsigned int 278 Gogo::hash_string(const std::string& s, unsigned int h) 279 { 280 const char* p = s.data(); 281 size_t len = s.length(); 282 for (; len > 0; --len) 283 { 284 h ^= *p++; 285 h*= 16777619; 286 } 287 return h; 288 } 289 290 // Get the package path to use for type reflection data. This should 291 // ideally be unique across the entire link. 292 293 const std::string& 294 Gogo::pkgpath() const 295 { 296 go_assert(this->pkgpath_set_); 297 return this->pkgpath_; 298 } 299 300 // Set the package path from the -fgo-pkgpath command line option. 301 302 void 303 Gogo::set_pkgpath(const std::string& arg) 304 { 305 go_assert(!this->pkgpath_set_); 306 this->pkgpath_ = arg; 307 this->pkgpath_set_ = true; 308 this->pkgpath_from_option_ = true; 309 } 310 311 // Get the package path to use for symbol names. 312 313 const std::string& 314 Gogo::pkgpath_symbol() const 315 { 316 go_assert(this->pkgpath_set_); 317 return this->pkgpath_symbol_; 318 } 319 320 // Set the unique prefix to use to determine the package path, from 321 // the -fgo-prefix command line option. 322 323 void 324 Gogo::set_prefix(const std::string& arg) 325 { 326 go_assert(!this->prefix_from_option_); 327 this->prefix_ = arg; 328 this->prefix_from_option_ = true; 329 } 330 331 // Munge name for use in an error message. 332 333 std::string 334 Gogo::message_name(const std::string& name) 335 { 336 return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str()); 337 } 338 339 // Get the package name. 340 341 const std::string& 342 Gogo::package_name() const 343 { 344 go_assert(this->package_ != NULL); 345 return this->package_->package_name(); 346 } 347 348 // Set the package name. 349 350 void 351 Gogo::set_package_name(const std::string& package_name, 352 Location location) 353 { 354 if (this->package_ != NULL) 355 { 356 if (this->package_->package_name() != package_name) 357 go_error_at(location, "expected package %<%s%>", 358 Gogo::message_name(this->package_->package_name()).c_str()); 359 return; 360 } 361 362 // Now that we know the name of the package we are compiling, set 363 // the package path to use for reflect.Type.PkgPath and global 364 // symbol names. 365 if (this->pkgpath_set_) 366 this->pkgpath_symbol_ = Gogo::pkgpath_for_symbol(this->pkgpath_); 367 else 368 { 369 if (!this->prefix_from_option_ && package_name == "main") 370 { 371 this->pkgpath_ = package_name; 372 this->pkgpath_symbol_ = Gogo::pkgpath_for_symbol(package_name); 373 } 374 else 375 { 376 if (!this->prefix_from_option_) 377 this->prefix_ = "go"; 378 this->pkgpath_ = this->prefix_ + '.' + package_name; 379 this->pkgpath_symbol_ = (Gogo::pkgpath_for_symbol(this->prefix_) + '.' 380 + Gogo::pkgpath_for_symbol(package_name)); 381 } 382 this->pkgpath_set_ = true; 383 } 384 385 this->package_ = this->register_package(this->pkgpath_, 386 this->pkgpath_symbol_, location); 387 this->package_->set_package_name(package_name, location); 388 389 if (this->is_main_package()) 390 { 391 // Declare "main" as a function which takes no parameters and 392 // returns no value. 393 Location uloc = Linemap::unknown_location(); 394 this->declare_function(Gogo::pack_hidden_name("main", false), 395 Type::make_function_type (NULL, NULL, NULL, uloc), 396 uloc); 397 } 398 } 399 400 // Return whether this is the "main" package. This is not true if 401 // -fgo-pkgpath or -fgo-prefix was used. 402 403 bool 404 Gogo::is_main_package() const 405 { 406 return (this->package_name() == "main" 407 && !this->pkgpath_from_option_ 408 && !this->prefix_from_option_); 409 } 410 411 // Import a package. 412 413 void 414 Gogo::import_package(const std::string& filename, 415 const std::string& local_name, 416 bool is_local_name_exported, 417 bool must_exist, 418 Location location) 419 { 420 if (filename.empty()) 421 { 422 go_error_at(location, "import path is empty"); 423 return; 424 } 425 426 const char *pf = filename.data(); 427 const char *pend = pf + filename.length(); 428 while (pf < pend) 429 { 430 unsigned int c; 431 int adv = Lex::fetch_char(pf, &c); 432 if (adv == 0) 433 { 434 go_error_at(location, "import path contains invalid UTF-8 sequence"); 435 return; 436 } 437 if (c == '\0') 438 { 439 go_error_at(location, "import path contains NUL"); 440 return; 441 } 442 if (c < 0x20 || c == 0x7f) 443 { 444 go_error_at(location, "import path contains control character"); 445 return; 446 } 447 if (c == '\\') 448 { 449 go_error_at(location, "import path contains backslash; use slash"); 450 return; 451 } 452 if (Lex::is_unicode_space(c)) 453 { 454 go_error_at(location, "import path contains space character"); 455 return; 456 } 457 if (c < 0x7f && strchr("!\"#$%&'()*,:;<=>?[]^`{|}", c) != NULL) 458 { 459 go_error_at(location, 460 "import path contains invalid character '%c'", c); 461 return; 462 } 463 pf += adv; 464 } 465 466 if (IS_ABSOLUTE_PATH(filename.c_str())) 467 { 468 go_error_at(location, "import path cannot be absolute path"); 469 return; 470 } 471 472 if (local_name == "init") 473 go_error_at(location, "cannot import package as init"); 474 475 if (filename == "unsafe") 476 { 477 this->import_unsafe(local_name, is_local_name_exported, location); 478 this->current_file_imported_unsafe_ = true; 479 return; 480 } 481 482 if (filename == "embed") 483 this->current_file_imported_embed_ = true; 484 485 Imports::const_iterator p = this->imports_.find(filename); 486 if (p != this->imports_.end()) 487 { 488 Package* package = p->second; 489 package->set_location(location); 490 std::string ln = local_name; 491 bool is_ln_exported = is_local_name_exported; 492 if (ln.empty()) 493 { 494 ln = package->package_name(); 495 go_assert(!ln.empty()); 496 is_ln_exported = Lex::is_exported_name(ln); 497 } 498 if (ln == "_") 499 ; 500 else if (ln == ".") 501 { 502 Bindings* bindings = package->bindings(); 503 for (Bindings::const_declarations_iterator pd = 504 bindings->begin_declarations(); 505 pd != bindings->end_declarations(); 506 ++pd) 507 this->add_dot_import_object(pd->second); 508 std::string dot_alias = "." + package->package_name(); 509 package->add_alias(dot_alias, location); 510 } 511 else 512 { 513 package->add_alias(ln, location); 514 ln = this->pack_hidden_name(ln, is_ln_exported); 515 this->package_->bindings()->add_package(ln, package); 516 } 517 return; 518 } 519 520 Import::Stream* stream = Import::open_package(filename, location, 521 this->relative_import_path_); 522 if (stream == NULL) 523 { 524 if (must_exist) 525 go_error_at(location, "import file %qs not found", filename.c_str()); 526 return; 527 } 528 529 Import* imp = new Import(stream, location); 530 imp->register_builtin_types(this); 531 Package* package = imp->import(this, local_name, is_local_name_exported); 532 if (package != NULL) 533 { 534 if (package->pkgpath() == this->pkgpath()) 535 go_error_at(location, 536 ("imported package uses same package path as package " 537 "being compiled (see %<-fgo-pkgpath%> option)")); 538 539 this->imports_.insert(std::make_pair(filename, package)); 540 } 541 542 imp->clear_stream(); 543 delete stream; 544 545 // FIXME: we never delete imp; we may need it for inlinable functions. 546 } 547 548 Import_init * 549 Gogo::lookup_init(const std::string& init_name) 550 { 551 Import_init tmp("", init_name, -1); 552 Import_init_set::iterator it = this->imported_init_fns_.find(&tmp); 553 return (it != this->imported_init_fns_.end()) ? *it : NULL; 554 } 555 556 // Add an import control function for an imported package to the list. 557 558 void 559 Gogo::add_import_init_fn(const std::string& package_name, 560 const std::string& init_name, int prio) 561 { 562 for (Import_init_set::iterator p = 563 this->imported_init_fns_.begin(); 564 p != this->imported_init_fns_.end(); 565 ++p) 566 { 567 Import_init *ii = (*p); 568 if (ii->init_name() == init_name) 569 { 570 // If a test of package P1, built as part of package P1, 571 // imports package P2, and P2 imports P1 (perhaps 572 // indirectly), then we will see the same import name with 573 // different import priorities. That is OK, so don't give 574 // an error about it. 575 if (ii->package_name() != package_name) 576 { 577 go_error_at(Linemap::unknown_location(), 578 "duplicate package initialization name %qs", 579 Gogo::message_name(init_name).c_str()); 580 go_inform(Linemap::unknown_location(), "used by package %qs", 581 Gogo::message_name(ii->package_name()).c_str()); 582 go_inform(Linemap::unknown_location(), " and by package %qs", 583 Gogo::message_name(package_name).c_str()); 584 } 585 ii->set_priority(prio); 586 return; 587 } 588 } 589 590 Import_init* nii = new Import_init(package_name, init_name, prio); 591 this->imported_init_fns_.insert(nii); 592 } 593 594 // Return whether we are at the global binding level. 595 596 bool 597 Gogo::in_global_scope() const 598 { 599 return this->functions_.empty(); 600 } 601 602 // Return the current binding contour. 603 604 Bindings* 605 Gogo::current_bindings() 606 { 607 if (!this->functions_.empty()) 608 return this->functions_.back().blocks.back()->bindings(); 609 else if (this->package_ != NULL) 610 return this->package_->bindings(); 611 else 612 return this->globals_; 613 } 614 615 const Bindings* 616 Gogo::current_bindings() const 617 { 618 if (!this->functions_.empty()) 619 return this->functions_.back().blocks.back()->bindings(); 620 else if (this->package_ != NULL) 621 return this->package_->bindings(); 622 else 623 return this->globals_; 624 } 625 626 void 627 Gogo::update_init_priority(Import_init* ii, 628 std::set<const Import_init *>* visited) 629 { 630 visited->insert(ii); 631 int succ_prior = -1; 632 633 for (std::set<std::string>::const_iterator pci = 634 ii->precursors().begin(); 635 pci != ii->precursors().end(); 636 ++pci) 637 { 638 Import_init* succ = this->lookup_init(*pci); 639 if (visited->find(succ) == visited->end()) 640 update_init_priority(succ, visited); 641 succ_prior = std::max(succ_prior, succ->priority()); 642 } 643 if (ii->priority() <= succ_prior) 644 ii->set_priority(succ_prior + 1); 645 } 646 647 void 648 Gogo::recompute_init_priorities() 649 { 650 std::set<Import_init *> nonroots; 651 652 for (Import_init_set::const_iterator p = 653 this->imported_init_fns_.begin(); 654 p != this->imported_init_fns_.end(); 655 ++p) 656 { 657 const Import_init *ii = *p; 658 for (std::set<std::string>::const_iterator pci = 659 ii->precursors().begin(); 660 pci != ii->precursors().end(); 661 ++pci) 662 { 663 Import_init* ii_init = this->lookup_init(*pci); 664 nonroots.insert(ii_init); 665 } 666 } 667 668 // Recursively update priorities starting at roots. 669 std::set<const Import_init*> visited; 670 for (Import_init_set::iterator p = 671 this->imported_init_fns_.begin(); 672 p != this->imported_init_fns_.end(); 673 ++p) 674 { 675 Import_init* ii = *p; 676 if (nonroots.find(ii) != nonroots.end()) 677 continue; 678 update_init_priority(ii, &visited); 679 } 680 } 681 682 // Add statements to INIT_STMTS which run the initialization 683 // functions for imported packages. This is only used for the "main" 684 // package. 685 686 void 687 Gogo::init_imports(std::vector<Bstatement*>& init_stmts, Bfunction *bfunction) 688 { 689 go_assert(this->is_main_package()); 690 691 if (this->imported_init_fns_.empty()) 692 return; 693 694 Location unknown_loc = Linemap::unknown_location(); 695 Function_type* func_type = 696 Type::make_function_type(NULL, NULL, NULL, unknown_loc); 697 Btype* fntype = func_type->get_backend_fntype(this); 698 699 // Recompute init priorities based on a walk of the init graph. 700 recompute_init_priorities(); 701 702 // We must call them in increasing priority order. 703 std::vector<const Import_init*> v; 704 for (Import_init_set::const_iterator p = 705 this->imported_init_fns_.begin(); 706 p != this->imported_init_fns_.end(); 707 ++p) 708 { 709 // Don't include dummy inits. They are not real functions. 710 if ((*p)->is_dummy()) 711 continue; 712 if ((*p)->priority() < 0) 713 go_error_at(Linemap::unknown_location(), 714 "internal error: failed to set init priority for %s", 715 (*p)->package_name().c_str()); 716 v.push_back(*p); 717 } 718 std::sort(v.begin(), v.end(), priority_compare); 719 720 // We build calls to the init functions, which take no arguments. 721 std::vector<Bexpression*> empty_args; 722 for (std::vector<const Import_init*>::const_iterator p = v.begin(); 723 p != v.end(); 724 ++p) 725 { 726 const Import_init* ii = *p; 727 std::string user_name = ii->package_name() + ".init"; 728 const std::string& init_name(ii->init_name()); 729 const unsigned int flags = 730 (Backend::function_is_visible 731 | Backend::function_is_declaration 732 | Backend::function_is_inlinable); 733 Bfunction* pfunc = this->backend()->function(fntype, user_name, init_name, 734 flags, unknown_loc); 735 Bexpression* pfunc_code = 736 this->backend()->function_code_expression(pfunc, unknown_loc); 737 Bexpression* pfunc_call = 738 this->backend()->call_expression(bfunction, pfunc_code, empty_args, 739 NULL, unknown_loc); 740 init_stmts.push_back(this->backend()->expression_statement(bfunction, 741 pfunc_call)); 742 } 743 } 744 745 // Register global variables with the garbage collector. We need to 746 // register all variables which can hold a pointer value. They become 747 // roots during the mark phase. We build a struct that is easy to 748 // hook into a list of roots. 749 750 // type gcRoot struct { 751 // decl unsafe.Pointer // Pointer to variable. 752 // size uintptr // Total size of variable. 753 // ptrdata uintptr // Length of variable's gcdata. 754 // gcdata *byte // Pointer mask. 755 // } 756 // 757 // type gcRootList struct { 758 // next *gcRootList 759 // count int 760 // roots [...]gcRoot 761 // } 762 763 // The last entry in the roots array has a NULL decl field. 764 765 void 766 Gogo::register_gc_vars(const std::vector<Named_object*>& var_gc, 767 std::vector<Bstatement*>& init_stmts, 768 Bfunction* init_bfn) 769 { 770 if (var_gc.empty() && this->gc_roots_.empty()) 771 return; 772 773 Type* pvt = Type::make_pointer_type(Type::make_void_type()); 774 Type* uintptr_type = Type::lookup_integer_type("uintptr"); 775 Type* byte_type = Type::lookup_integer_type("byte"); 776 Type* pointer_byte_type = Type::make_pointer_type(byte_type); 777 Struct_type* root_type = 778 Type::make_builtin_struct_type(4, 779 "decl", pvt, 780 "size", uintptr_type, 781 "ptrdata", uintptr_type, 782 "gcdata", pointer_byte_type); 783 784 Location builtin_loc = Linemap::predeclared_location(); 785 unsigned long roots_len = var_gc.size() + this->gc_roots_.size(); 786 Expression* length = Expression::make_integer_ul(roots_len, NULL, 787 builtin_loc); 788 Array_type* root_array_type = Type::make_array_type(root_type, length); 789 root_array_type->set_is_array_incomparable(); 790 791 Type* int_type = Type::lookup_integer_type("int"); 792 Struct_type* root_list_type = 793 Type::make_builtin_struct_type(3, 794 "next", pvt, 795 "count", int_type, 796 "roots", root_array_type); 797 798 // Build an initializer for the roots array. 799 800 Expression_list* roots_init = new Expression_list(); 801 802 for (std::vector<Named_object*>::const_iterator p = var_gc.begin(); 803 p != var_gc.end(); 804 ++p) 805 { 806 Expression_list* init = new Expression_list(); 807 808 Location no_loc = (*p)->location(); 809 Expression* decl = Expression::make_var_reference(*p, no_loc); 810 Expression* decl_addr = 811 Expression::make_unary(OPERATOR_AND, decl, no_loc); 812 decl_addr->unary_expression()->set_does_not_escape(); 813 decl_addr = Expression::make_cast(pvt, decl_addr, no_loc); 814 init->push_back(decl_addr); 815 816 Expression* size = 817 Expression::make_type_info(decl->type(), 818 Expression::TYPE_INFO_SIZE); 819 init->push_back(size); 820 821 Expression* ptrdata = 822 Expression::make_type_info(decl->type(), 823 Expression::TYPE_INFO_BACKEND_PTRDATA); 824 init->push_back(ptrdata); 825 826 Expression* gcdata = Expression::make_ptrmask_symbol(decl->type()); 827 init->push_back(gcdata); 828 829 Expression* root_ctor = 830 Expression::make_struct_composite_literal(root_type, init, no_loc); 831 roots_init->push_back(root_ctor); 832 } 833 834 for (std::vector<Expression*>::const_iterator p = this->gc_roots_.begin(); 835 p != this->gc_roots_.end(); 836 ++p) 837 { 838 Expression_list *init = new Expression_list(); 839 840 Expression* expr = *p; 841 Location eloc = expr->location(); 842 init->push_back(Expression::make_cast(pvt, expr, eloc)); 843 844 Type* type = expr->type()->points_to(); 845 go_assert(type != NULL); 846 847 Expression* size = 848 Expression::make_type_info(type, 849 Expression::TYPE_INFO_SIZE); 850 init->push_back(size); 851 852 Expression* ptrdata = 853 Expression::make_type_info(type, 854 Expression::TYPE_INFO_BACKEND_PTRDATA); 855 init->push_back(ptrdata); 856 857 Expression* gcdata = Expression::make_ptrmask_symbol(type); 858 init->push_back(gcdata); 859 860 Expression* root_ctor = 861 Expression::make_struct_composite_literal(root_type, init, eloc); 862 roots_init->push_back(root_ctor); 863 } 864 865 // Build a constructor for the struct. 866 867 Expression_list* root_list_init = new Expression_list(); 868 root_list_init->push_back(Expression::make_nil(builtin_loc)); 869 root_list_init->push_back(Expression::make_integer_ul(roots_len, int_type, 870 builtin_loc)); 871 872 Expression* roots_ctor = 873 Expression::make_array_composite_literal(root_array_type, roots_init, 874 builtin_loc); 875 root_list_init->push_back(roots_ctor); 876 877 Expression* root_list_ctor = 878 Expression::make_struct_composite_literal(root_list_type, root_list_init, 879 builtin_loc); 880 881 Expression* root_addr = Expression::make_unary(OPERATOR_AND, root_list_ctor, 882 builtin_loc); 883 root_addr->unary_expression()->set_is_gc_root(); 884 Expression* register_roots = Runtime::make_call(Runtime::REGISTER_GC_ROOTS, 885 builtin_loc, 1, root_addr); 886 887 Translate_context context(this, NULL, NULL, NULL); 888 Bexpression* bcall = register_roots->get_backend(&context); 889 init_stmts.push_back(this->backend()->expression_statement(init_bfn, bcall)); 890 } 891 892 // Build the list of type descriptors defined in this package. This is to help 893 // the reflect package to find compiler-generated types. 894 895 // type typeDescriptorList struct { 896 // count int 897 // types [...]unsafe.Pointer 898 // } 899 900 static Struct_type* 901 type_descriptor_list_type(unsigned long len) 902 { 903 Location builtin_loc = Linemap::predeclared_location(); 904 Type* int_type = Type::lookup_integer_type("int"); 905 Type* ptr_type = Type::make_pointer_type(Type::make_void_type()); 906 // Avoid creating zero-length type. 907 unsigned long nelems = (len != 0 ? len : 1); 908 Expression* len_expr = Expression::make_integer_ul(nelems, NULL, 909 builtin_loc); 910 Array_type* array_type = Type::make_array_type(ptr_type, len_expr); 911 array_type->set_is_array_incomparable(); 912 Struct_type* list_type = 913 Type::make_builtin_struct_type(2, "count", int_type, 914 "types", array_type); 915 return list_type; 916 } 917 918 void 919 Gogo::build_type_descriptor_list() 920 { 921 // Create the list type 922 Location builtin_loc = Linemap::predeclared_location(); 923 unsigned long len = this->type_descriptors_.size(); 924 Struct_type* list_type = type_descriptor_list_type(len); 925 Btype* bt = list_type->get_backend(this); 926 Btype* bat = list_type->field(1)->type()->get_backend(this); 927 928 // Create the variable 929 std::string name = this->type_descriptor_list_symbol(this->pkgpath_symbol()); 930 unsigned int flags = Backend::variable_is_constant; 931 Bvariable* bv = this->backend()->implicit_variable(name, name, bt, flags, 0); 932 933 // Build the initializer 934 std::vector<unsigned long> indexes; 935 std::vector<Bexpression*> vals; 936 std::vector<Type*>::iterator p = this->type_descriptors_.begin(); 937 for (unsigned long i = 0; i < len; ++i, ++p) 938 { 939 Bexpression* bexpr = (*p)->type_descriptor_pointer(this, 940 builtin_loc); 941 indexes.push_back(i); 942 vals.push_back(bexpr); 943 } 944 Bexpression* barray = 945 this->backend()->array_constructor_expression(bat, indexes, vals, 946 builtin_loc); 947 948 Translate_context context(this, NULL, NULL, NULL); 949 std::vector<Bexpression*> fields; 950 Expression* len_expr = Expression::make_integer_ul(len, NULL, 951 builtin_loc); 952 fields.push_back(len_expr->get_backend(&context)); 953 fields.push_back(barray); 954 Bexpression* binit = 955 this->backend()->constructor_expression(bt, fields, builtin_loc); 956 957 this->backend()->implicit_variable_set_init(bv, name, bt, flags, binit); 958 } 959 960 // Register the type descriptors with the runtime. This is to help 961 // the reflect package to find compiler-generated types. 962 963 void 964 Gogo::register_type_descriptors(std::vector<Bstatement*>& init_stmts, 965 Bfunction* init_bfn) 966 { 967 // Create the list type 968 Location builtin_loc = Linemap::predeclared_location(); 969 Struct_type* list_type = type_descriptor_list_type(1); 970 Btype* bt = list_type->get_backend(this); 971 972 // Collect type lists from transitive imports. 973 std::vector<std::string> list_names; 974 for (Import_init_set::iterator it = this->imported_init_fns_.begin(); 975 it != this->imported_init_fns_.end(); 976 ++it) 977 { 978 std::string pkgpath_symbol = 979 this->pkgpath_symbol_from_init_fn_name((*it)->init_name()); 980 list_names.push_back(this->type_descriptor_list_symbol(pkgpath_symbol)); 981 } 982 // Add the main package itself. 983 list_names.push_back(this->type_descriptor_list_symbol("main")); 984 985 // Build a list of lists. 986 std::vector<unsigned long> indexes; 987 std::vector<Bexpression*> vals; 988 unsigned long i = 0; 989 for (std::vector<std::string>::iterator p = list_names.begin(); 990 p != list_names.end(); 991 ++p) 992 { 993 Bvariable* bv = 994 this->backend()->implicit_variable_reference(*p, *p, bt); 995 Bexpression* bexpr = this->backend()->var_expression(bv, builtin_loc); 996 bexpr = this->backend()->address_expression(bexpr, builtin_loc); 997 998 indexes.push_back(i); 999 vals.push_back(bexpr); 1000 i++; 1001 } 1002 Expression* len_expr = Expression::make_integer_ul(i, NULL, builtin_loc); 1003 Type* list_ptr_type = Type::make_pointer_type(list_type); 1004 Type* list_array_type = Type::make_array_type(list_ptr_type, len_expr); 1005 Btype* bat = list_array_type->get_backend(this); 1006 Bexpression* barray = 1007 this->backend()->array_constructor_expression(bat, indexes, vals, 1008 builtin_loc); 1009 1010 // Create a variable holding the list. 1011 std::string name = this->typelists_symbol(); 1012 unsigned int flags = (Backend::variable_is_hidden 1013 | Backend::variable_is_constant); 1014 Bvariable* bv = this->backend()->implicit_variable(name, name, bat, flags, 1015 0); 1016 this->backend()->implicit_variable_set_init(bv, name, bat, flags, barray); 1017 1018 // Build the call in main package's init function. 1019 Translate_context context(this, NULL, NULL, NULL); 1020 Bexpression* bexpr = this->backend()->var_expression(bv, builtin_loc); 1021 bexpr = this->backend()->address_expression(bexpr, builtin_loc); 1022 Type* array_ptr_type = Type::make_pointer_type(list_array_type); 1023 Expression* expr = Expression::make_backend(bexpr, array_ptr_type, 1024 builtin_loc); 1025 expr = Runtime::make_call(Runtime::REGISTER_TYPE_DESCRIPTORS, 1026 builtin_loc, 2, len_expr->copy(), expr); 1027 Bexpression* bcall = expr->get_backend(&context); 1028 init_stmts.push_back(this->backend()->expression_statement(init_bfn, 1029 bcall)); 1030 } 1031 1032 // Build the decl for the initialization function. 1033 1034 Named_object* 1035 Gogo::initialization_function_decl() 1036 { 1037 std::string name = this->get_init_fn_name(); 1038 Location loc = this->package_->location(); 1039 1040 Function_type* fntype = Type::make_function_type(NULL, NULL, NULL, loc); 1041 Function* initfn = new Function(fntype, NULL, NULL, loc); 1042 return Named_object::make_function(name, NULL, initfn); 1043 } 1044 1045 // Create the magic initialization function. CODE_STMT is the 1046 // code that it needs to run. 1047 1048 Named_object* 1049 Gogo::create_initialization_function(Named_object* initfn, 1050 Bstatement* code_stmt) 1051 { 1052 // Make sure that we thought we needed an initialization function, 1053 // as otherwise we will not have reported it in the export data. 1054 go_assert(this->is_main_package() || this->need_init_fn_); 1055 1056 if (initfn == NULL) 1057 initfn = this->initialization_function_decl(); 1058 1059 // Bind the initialization function code to a block. 1060 Bfunction* fndecl = initfn->func_value()->get_or_make_decl(this, initfn); 1061 Location pkg_loc = this->package_->location(); 1062 std::vector<Bvariable*> vars; 1063 this->backend()->block(fndecl, NULL, vars, pkg_loc, pkg_loc); 1064 1065 if (!this->backend()->function_set_body(fndecl, code_stmt)) 1066 { 1067 go_assert(saw_errors()); 1068 return NULL; 1069 } 1070 return initfn; 1071 } 1072 1073 // Given an expression, collect all the global variables defined in 1074 // this package that it references. 1075 1076 class Find_vars : public Traverse 1077 { 1078 private: 1079 // The list of variables we accumulate. 1080 typedef Unordered_set(Named_object*) Vars; 1081 1082 // A hash table we use to avoid looping. The index is a 1083 // Named_object* or a Temporary_statement*. We only look through 1084 // objects defined in this package. 1085 typedef Unordered_set(const void*) Seen_objects; 1086 1087 public: 1088 Find_vars() 1089 : Traverse(traverse_expressions | traverse_statements), 1090 vars_(), seen_objects_(), lhs_is_ref_(false) 1091 { } 1092 1093 // An iterator through the variables found, after the traversal. 1094 typedef Vars::const_iterator const_iterator; 1095 1096 const_iterator 1097 begin() const 1098 { return this->vars_.begin(); } 1099 1100 const_iterator 1101 end() const 1102 { return this->vars_.end(); } 1103 1104 int 1105 expression(Expression**); 1106 1107 int 1108 statement(Block*, size_t* index, Statement*); 1109 1110 private: 1111 // Accumulated variables. 1112 Vars vars_; 1113 // Objects we have already seen. 1114 Seen_objects seen_objects_; 1115 // Whether an assignment to a variable counts as a reference. 1116 bool lhs_is_ref_; 1117 }; 1118 1119 // Collect global variables referenced by EXPR. Look through function 1120 // calls and variable initializations. 1121 1122 int 1123 Find_vars::expression(Expression** pexpr) 1124 { 1125 Expression* e = *pexpr; 1126 1127 Var_expression* ve = e->var_expression(); 1128 if (ve != NULL) 1129 { 1130 Named_object* v = ve->named_object(); 1131 if (!v->is_variable() || v->package() != NULL) 1132 { 1133 // This is a result parameter or a variable defined in a 1134 // different package. Either way we don't care about it. 1135 return TRAVERSE_CONTINUE; 1136 } 1137 1138 std::pair<Seen_objects::iterator, bool> ins = 1139 this->seen_objects_.insert(v); 1140 if (!ins.second) 1141 { 1142 // We've seen this variable before. 1143 return TRAVERSE_CONTINUE; 1144 } 1145 1146 if (v->var_value()->is_global()) 1147 this->vars_.insert(v); 1148 1149 Expression* init = v->var_value()->init(); 1150 if (init != NULL) 1151 { 1152 if (Expression::traverse(&init, this) == TRAVERSE_EXIT) 1153 return TRAVERSE_EXIT; 1154 } 1155 } 1156 1157 // We traverse the code of any function or bound method we see. Note that 1158 // this means that we will traverse the code of a function or bound method 1159 // whose address is taken even if it is not called. 1160 Func_expression* fe = e->func_expression(); 1161 Bound_method_expression* bme = e->bound_method_expression(); 1162 if (fe != NULL || bme != NULL) 1163 { 1164 const Named_object* f = fe != NULL ? fe->named_object() : bme->function(); 1165 if (f->is_function() && f->package() == NULL) 1166 { 1167 std::pair<Seen_objects::iterator, bool> ins = 1168 this->seen_objects_.insert(f); 1169 if (ins.second) 1170 { 1171 // This is the first time we have seen this name. 1172 bool hold = this->lhs_is_ref_; 1173 this->lhs_is_ref_ = true; 1174 int r = f->func_value()->block()->traverse(this); 1175 this->lhs_is_ref_ = hold; 1176 if (r == TRAVERSE_EXIT) 1177 return TRAVERSE_EXIT; 1178 } 1179 } 1180 } 1181 1182 Temporary_reference_expression* tre = e->temporary_reference_expression(); 1183 if (tre != NULL) 1184 { 1185 Temporary_statement* ts = tre->statement(); 1186 Expression* init = ts->init(); 1187 if (init != NULL) 1188 { 1189 std::pair<Seen_objects::iterator, bool> ins = 1190 this->seen_objects_.insert(ts); 1191 if (ins.second) 1192 { 1193 // This is the first time we have seen this temporary 1194 // statement. 1195 if (Expression::traverse(&init, this) == TRAVERSE_EXIT) 1196 return TRAVERSE_EXIT; 1197 } 1198 } 1199 } 1200 1201 return TRAVERSE_CONTINUE; 1202 } 1203 1204 // Check a statement while searching for variables. This is where we 1205 // skip variables on the left hand side of assigments if appropriate. 1206 1207 int 1208 Find_vars::statement(Block*, size_t*, Statement* s) 1209 { 1210 if (this->lhs_is_ref_) 1211 return TRAVERSE_CONTINUE; 1212 Assignment_statement* as = s->assignment_statement(); 1213 if (as == NULL) 1214 return TRAVERSE_CONTINUE; 1215 1216 // Only traverse subexpressions of the LHS. 1217 if (as->lhs()->traverse_subexpressions(this) == TRAVERSE_EXIT) 1218 return TRAVERSE_EXIT; 1219 1220 Expression* rhs = as->rhs(); 1221 if (Expression::traverse(&rhs, this) == TRAVERSE_EXIT) 1222 return TRAVERSE_EXIT; 1223 1224 return TRAVERSE_SKIP_COMPONENTS; 1225 } 1226 1227 // Return true if EXPR, PREINIT, or DEP refers to VAR. 1228 1229 static bool 1230 expression_requires(Expression* expr, Block* preinit, Named_object* dep, 1231 Named_object* var) 1232 { 1233 Find_vars find_vars; 1234 if (expr != NULL) 1235 Expression::traverse(&expr, &find_vars); 1236 if (preinit != NULL) 1237 preinit->traverse(&find_vars); 1238 if (dep != NULL) 1239 { 1240 Expression* init = dep->var_value()->init(); 1241 if (init != NULL) 1242 Expression::traverse(&init, &find_vars); 1243 if (dep->var_value()->has_pre_init()) 1244 dep->var_value()->preinit()->traverse(&find_vars); 1245 } 1246 1247 for (Find_vars::const_iterator p = find_vars.begin(); 1248 p != find_vars.end(); 1249 ++p) 1250 { 1251 if (*p == var) 1252 return true; 1253 } 1254 return false; 1255 } 1256 1257 // Sort variable initializations. If the initialization expression 1258 // for variable A refers directly or indirectly to the initialization 1259 // expression for variable B, then we must initialize B before A. 1260 1261 class Var_init 1262 { 1263 public: 1264 Var_init() 1265 : var_(NULL), init_(NULL), dep_count_(0) 1266 { } 1267 1268 Var_init(Named_object* var, Bstatement* init) 1269 : var_(var), init_(init), dep_count_(0) 1270 { } 1271 1272 // Return the variable. 1273 Named_object* 1274 var() const 1275 { return this->var_; } 1276 1277 // Return the initialization expression. 1278 Bstatement* 1279 init() const 1280 { return this->init_; } 1281 1282 // Return the number of remaining dependencies. 1283 size_t 1284 dep_count() const 1285 { return this->dep_count_; } 1286 1287 // Increment the number of dependencies. 1288 void 1289 add_dependency() 1290 { ++this->dep_count_; } 1291 1292 // Decrement the number of dependencies. 1293 void 1294 remove_dependency() 1295 { --this->dep_count_; } 1296 1297 private: 1298 // The variable being initialized. 1299 Named_object* var_; 1300 // The backend initialization statement. 1301 Bstatement* init_; 1302 // The number of initializations this is dependent on. A variable 1303 // initialization should not be emitted if any of its dependencies 1304 // have not yet been resolved. 1305 size_t dep_count_; 1306 }; 1307 1308 // For comparing Var_init keys in a map. 1309 1310 inline bool 1311 operator<(const Var_init& v1, const Var_init& v2) 1312 { return v1.var()->name() < v2.var()->name(); } 1313 1314 typedef std::list<Var_init> Var_inits; 1315 1316 // Sort the variable initializations. The rule we follow is that we 1317 // emit them in the order they appear in the array, except that if the 1318 // initialization expression for a variable V1 depends upon another 1319 // variable V2 then we initialize V1 after V2. 1320 1321 static void 1322 sort_var_inits(Var_inits* var_inits) 1323 { 1324 if (var_inits->empty()) 1325 return; 1326 1327 std::map<Named_object*, Var_init*> var_to_init; 1328 1329 // A mapping from a variable initialization to a set of 1330 // variable initializations that depend on it. 1331 typedef std::map<Var_init, std::set<Var_init*> > Init_deps; 1332 Init_deps init_deps; 1333 bool init_loop = false; 1334 1335 // Map from variable to Var_init. 1336 for (Var_inits::iterator pvar = var_inits->begin(); 1337 pvar != var_inits->end(); 1338 ++pvar) 1339 { 1340 Named_object* var = pvar->var(); 1341 var_to_init[var] = &*pvar; 1342 } 1343 1344 // Add dependencies to init_deps, and check for cycles. 1345 for (Var_inits::iterator pvar = var_inits->begin(); 1346 pvar != var_inits->end(); 1347 ++pvar) 1348 { 1349 Named_object* var = pvar->var(); 1350 1351 const std::vector<Named_object*>* refs = 1352 pvar->var()->var_value()->init_refs(); 1353 if (refs == NULL) 1354 continue; 1355 for (std::vector<Named_object*>::const_iterator pdep = refs->begin(); 1356 pdep != refs->end(); 1357 ++pdep) 1358 { 1359 Named_object* dep = *pdep; 1360 if (var == dep) 1361 { 1362 // This is a reference from a variable to itself. 1363 go_error_at(var->location(), 1364 ("initialization expression for %qs " 1365 "depends upon itself"), 1366 var->message_name().c_str()); 1367 continue; 1368 } 1369 1370 Var_init* dep_init = var_to_init[dep]; 1371 if (dep_init == NULL) 1372 { 1373 // This is a dependency on some variable that doesn't 1374 // have an initializer, so for purposes of 1375 // initialization ordering this is irrelevant. 1376 continue; 1377 } 1378 1379 init_deps[*dep_init].insert(&(*pvar)); 1380 pvar->add_dependency(); 1381 1382 // Check for cycles. 1383 const std::vector<Named_object*>* deprefs = 1384 dep_init->var()->var_value()->init_refs(); 1385 if (deprefs == NULL) 1386 continue; 1387 for (std::vector<Named_object*>::const_iterator pdepdep = 1388 deprefs->begin(); 1389 pdepdep != deprefs->end(); 1390 ++pdepdep) 1391 { 1392 if (*pdepdep == var) 1393 { 1394 go_error_at(var->location(), 1395 ("initialization expressions for %qs and " 1396 "%qs depend upon each other"), 1397 var->message_name().c_str(), 1398 dep->message_name().c_str()); 1399 go_inform(dep->location(), "%qs defined here", 1400 dep->message_name().c_str()); 1401 init_loop = true; 1402 break; 1403 } 1404 } 1405 } 1406 } 1407 1408 var_to_init.clear(); 1409 1410 // If there are no dependencies then the declaration order is sorted. 1411 if (!init_deps.empty() && !init_loop) 1412 { 1413 // Otherwise, sort variable initializations by emitting all variables with 1414 // no dependencies in declaration order. VAR_INITS is already in 1415 // declaration order. 1416 Var_inits ready; 1417 while (!var_inits->empty()) 1418 { 1419 Var_inits::iterator v1;; 1420 for (v1 = var_inits->begin(); v1 != var_inits->end(); ++v1) 1421 { 1422 if (v1->dep_count() == 0) 1423 break; 1424 } 1425 go_assert(v1 != var_inits->end()); 1426 1427 // V1 either has no dependencies or its dependencies have already 1428 // been emitted, add it to READY next. When V1 is emitted, remove 1429 // a dependency from each V that depends on V1. 1430 ready.splice(ready.end(), *var_inits, v1); 1431 1432 Init_deps::iterator p1 = init_deps.find(*v1); 1433 if (p1 != init_deps.end()) 1434 { 1435 std::set<Var_init*> resolved = p1->second; 1436 for (std::set<Var_init*>::iterator pv = resolved.begin(); 1437 pv != resolved.end(); 1438 ++pv) 1439 (*pv)->remove_dependency(); 1440 init_deps.erase(p1); 1441 } 1442 } 1443 var_inits->swap(ready); 1444 go_assert(init_deps.empty()); 1445 } 1446 } 1447 1448 // Give an error if the initialization expression for VAR depends on 1449 // itself. We only check if INIT is not NULL and there is no 1450 // dependency; when INIT is NULL, it means that PREINIT sets VAR, 1451 // which we will interpret as a loop. 1452 1453 void 1454 Gogo::check_self_dep(Named_object* var) 1455 { 1456 Expression* init = var->var_value()->init(); 1457 Block* preinit = var->var_value()->preinit(); 1458 Named_object* dep = this->var_depends_on(var->var_value()); 1459 if (init != NULL 1460 && dep == NULL 1461 && expression_requires(init, preinit, NULL, var)) 1462 go_error_at(var->location(), 1463 "initialization expression for %qs depends upon itself", 1464 var->message_name().c_str()); 1465 } 1466 1467 // Write out the global definitions. 1468 1469 void 1470 Gogo::write_globals() 1471 { 1472 this->build_interface_method_tables(); 1473 1474 Bindings* bindings = this->current_bindings(); 1475 1476 for (Bindings::const_declarations_iterator p = bindings->begin_declarations(); 1477 p != bindings->end_declarations(); 1478 ++p) 1479 { 1480 // If any function declarations needed a descriptor, make sure 1481 // we build it. 1482 Named_object* no = p->second; 1483 if (no->is_function_declaration()) 1484 no->func_declaration_value()->build_backend_descriptor(this); 1485 } 1486 1487 // Lists of globally declared types, variables, constants, and functions 1488 // that must be defined. 1489 std::vector<Btype*> type_decls; 1490 std::vector<Bvariable*> var_decls; 1491 std::vector<Bexpression*> const_decls; 1492 std::vector<Bfunction*> func_decls; 1493 1494 // The init function declaration and associated Bfunction, if necessary. 1495 Named_object* init_fndecl = NULL; 1496 Bfunction* init_bfn = NULL; 1497 1498 std::vector<Bstatement*> init_stmts; 1499 std::vector<Bstatement*> var_init_stmts; 1500 1501 if (this->is_main_package()) 1502 { 1503 init_fndecl = this->initialization_function_decl(); 1504 init_bfn = init_fndecl->func_value()->get_or_make_decl(this, init_fndecl); 1505 } 1506 1507 // A list of variable initializations. 1508 Var_inits var_inits; 1509 1510 // A list of variables which need to be registered with the garbage 1511 // collector. 1512 size_t count_definitions = bindings->size_definitions(); 1513 std::vector<Named_object*> var_gc; 1514 var_gc.reserve(count_definitions); 1515 1516 for (Bindings::const_definitions_iterator p = bindings->begin_definitions(); 1517 p != bindings->end_definitions(); 1518 ++p) 1519 { 1520 Named_object* no = *p; 1521 go_assert(!no->is_type_declaration() && !no->is_function_declaration()); 1522 1523 // There is nothing to do for a package. 1524 if (no->is_package()) 1525 continue; 1526 1527 // There is nothing to do for an object which was imported from 1528 // a different package into the global scope. 1529 if (no->package() != NULL) 1530 continue; 1531 1532 // Skip blank named functions and constants. 1533 if ((no->is_function() && no->func_value()->is_sink()) 1534 || (no->is_const() && no->const_value()->is_sink())) 1535 continue; 1536 1537 // Skip global sink variables with static initializers. With 1538 // non-static initializers we have to evaluate for side effects, 1539 // and we wind up initializing a dummy variable. That is not 1540 // ideal but it works and it's a rare case. 1541 if (no->is_variable() 1542 && no->var_value()->is_global_sink() 1543 && !no->var_value()->has_pre_init() 1544 && (no->var_value()->init() == NULL 1545 || no->var_value()->init()->is_static_initializer())) 1546 continue; 1547 1548 // There is nothing useful we can output for constants which 1549 // have ideal or non-integral type. 1550 if (no->is_const()) 1551 { 1552 Type* type = no->const_value()->type(); 1553 if (type == NULL) 1554 type = no->const_value()->expr()->type(); 1555 if (type->is_abstract() || !type->is_numeric_type()) 1556 continue; 1557 } 1558 1559 if (!no->is_variable()) 1560 no->get_backend(this, const_decls, type_decls, func_decls); 1561 else 1562 { 1563 Variable* var = no->var_value(); 1564 Bvariable* bvar = no->get_backend_variable(this, NULL); 1565 var_decls.push_back(bvar); 1566 1567 // Check for a sink variable, which may be used to run an 1568 // initializer purely for its side effects. 1569 bool is_sink = no->name()[0] == '_' && no->name()[1] == '.'; 1570 1571 Bstatement* var_init_stmt = NULL; 1572 if (!var->has_pre_init()) 1573 { 1574 // If the backend representation of the variable initializer is 1575 // constant, we can just set the initial value using 1576 // global_var_set_init instead of during the init() function. 1577 // The initializer is constant if it is the zero-value of the 1578 // variable's type or if the initial value is an immutable value 1579 // that is not copied to the heap. 1580 bool is_static_initializer = false; 1581 if (var->init() == NULL) 1582 is_static_initializer = true; 1583 else 1584 { 1585 Type* var_type = var->type(); 1586 Expression* init = var->init(); 1587 Expression* init_cast = 1588 Expression::make_cast(var_type, init, var->location()); 1589 is_static_initializer = init_cast->is_static_initializer(); 1590 } 1591 1592 // Non-constant variable initializations might need to create 1593 // temporary variables, which will need the initialization 1594 // function as context. 1595 Named_object* var_init_fn; 1596 if (is_static_initializer) 1597 var_init_fn = NULL; 1598 else 1599 { 1600 if (init_fndecl == NULL) 1601 { 1602 init_fndecl = this->initialization_function_decl(); 1603 Function* func = init_fndecl->func_value(); 1604 init_bfn = func->get_or_make_decl(this, init_fndecl); 1605 } 1606 var_init_fn = init_fndecl; 1607 } 1608 Bexpression* var_binit = var->get_init(this, var_init_fn); 1609 1610 if (var_binit == NULL) 1611 ; 1612 else if (is_static_initializer) 1613 { 1614 if (expression_requires(var->init(), NULL, 1615 this->var_depends_on(var), no)) 1616 go_error_at(no->location(), 1617 "initialization expression for %qs depends " 1618 "upon itself", 1619 no->message_name().c_str()); 1620 this->backend()->global_variable_set_init(bvar, var_binit); 1621 } 1622 else if (is_sink) 1623 var_init_stmt = 1624 this->backend()->expression_statement(init_bfn, var_binit); 1625 else 1626 { 1627 Location loc = var->location(); 1628 Bexpression* var_expr = 1629 this->backend()->var_expression(bvar, loc); 1630 var_init_stmt = 1631 this->backend()->assignment_statement(init_bfn, var_expr, 1632 var_binit, loc); 1633 } 1634 } 1635 else 1636 { 1637 // We are going to create temporary variables which 1638 // means that we need an fndecl. 1639 if (init_fndecl == NULL) 1640 init_fndecl = this->initialization_function_decl(); 1641 1642 Bvariable* var_decl = is_sink ? NULL : bvar; 1643 var_init_stmt = var->get_init_block(this, init_fndecl, var_decl); 1644 } 1645 1646 if (var_init_stmt != NULL) 1647 { 1648 if (var->init() == NULL && !var->has_pre_init()) 1649 var_init_stmts.push_back(var_init_stmt); 1650 else 1651 var_inits.push_back(Var_init(no, var_init_stmt)); 1652 } 1653 else if (this->var_depends_on(var) != NULL) 1654 { 1655 // This variable is initialized from something that is 1656 // not in its init or preinit. This variable needs to 1657 // participate in dependency analysis sorting, in case 1658 // some other variable depends on this one. 1659 Btype* btype = no->var_value()->type()->get_backend(this); 1660 Bexpression* zero = this->backend()->zero_expression(btype); 1661 Bstatement* zero_stmt = 1662 this->backend()->expression_statement(init_bfn, zero); 1663 var_inits.push_back(Var_init(no, zero_stmt)); 1664 } 1665 1666 // Collect a list of all global variables with pointers, 1667 // to register them for the garbage collector. 1668 if (!is_sink && var->type()->has_pointer()) 1669 { 1670 // Avoid putting runtime.gcRoots itself on the list. 1671 if (this->compiling_runtime() 1672 && this->package_name() == "runtime" 1673 && (Gogo::unpack_hidden_name(no->name()) == "gcRoots" 1674 || Gogo::unpack_hidden_name(no->name()) == "gcRootsIndex")) 1675 ; 1676 else 1677 var_gc.push_back(no); 1678 } 1679 } 1680 } 1681 1682 // Output inline functions, which are in different packages. 1683 for (std::vector<Named_object*>::const_iterator p = 1684 this->imported_inline_functions_.begin(); 1685 p != this->imported_inline_functions_.end(); 1686 ++p) 1687 (*p)->get_backend(this, const_decls, type_decls, func_decls); 1688 1689 // Build the list of type descriptors. 1690 this->build_type_descriptor_list(); 1691 1692 if (this->is_main_package()) 1693 { 1694 // Register the type descriptor lists, so that at run time 1695 // the reflect package can find compiler-created types, and 1696 // deduplicate if the same type is created with reflection. 1697 // This needs to be done before calling any package's init 1698 // function, as it may create type through reflection. 1699 this->register_type_descriptors(init_stmts, init_bfn); 1700 1701 // Initialize imported packages. 1702 this->init_imports(init_stmts, init_bfn); 1703 } 1704 1705 // Register global variables with the garbage collector. 1706 this->register_gc_vars(var_gc, init_stmts, init_bfn); 1707 1708 // Simple variable initializations, after all variables are 1709 // registered. 1710 init_stmts.push_back(this->backend()->statement_list(var_init_stmts)); 1711 1712 // Complete variable initializations, first sorting them into a 1713 // workable order. 1714 if (!var_inits.empty()) 1715 { 1716 sort_var_inits(&var_inits); 1717 for (Var_inits::const_iterator p = var_inits.begin(); 1718 p != var_inits.end(); 1719 ++p) 1720 init_stmts.push_back(p->init()); 1721 } 1722 1723 // After all the variables are initialized, call the init 1724 // functions if there are any. Init functions take no arguments, so 1725 // we pass in EMPTY_ARGS to call them. 1726 std::vector<Bexpression*> empty_args; 1727 for (std::vector<Named_object*>::const_iterator p = 1728 this->init_functions_.begin(); 1729 p != this->init_functions_.end(); 1730 ++p) 1731 { 1732 Location func_loc = (*p)->location(); 1733 Function* func = (*p)->func_value(); 1734 Bfunction* initfn = func->get_or_make_decl(this, *p); 1735 Bexpression* func_code = 1736 this->backend()->function_code_expression(initfn, func_loc); 1737 Bexpression* call = this->backend()->call_expression(init_bfn, func_code, 1738 empty_args, 1739 NULL, func_loc); 1740 Bstatement* ist = this->backend()->expression_statement(init_bfn, call); 1741 init_stmts.push_back(ist); 1742 } 1743 1744 // Set up a magic function to do all the initialization actions. 1745 // This will be called if this package is imported. 1746 Bstatement* init_fncode = this->backend()->statement_list(init_stmts); 1747 if (this->need_init_fn_ || this->is_main_package()) 1748 { 1749 init_fndecl = 1750 this->create_initialization_function(init_fndecl, init_fncode); 1751 if (init_fndecl != NULL) 1752 func_decls.push_back(init_fndecl->func_value()->get_decl()); 1753 } 1754 1755 // We should not have seen any new bindings created during the conversion. 1756 go_assert(count_definitions == this->current_bindings()->size_definitions()); 1757 1758 // Define all globally declared values. 1759 if (!saw_errors()) 1760 this->backend()->write_global_definitions(type_decls, const_decls, 1761 func_decls, var_decls); 1762 } 1763 1764 // Return the current block. 1765 1766 Block* 1767 Gogo::current_block() 1768 { 1769 if (this->functions_.empty()) 1770 return NULL; 1771 else 1772 return this->functions_.back().blocks.back(); 1773 } 1774 1775 // Look up a name in the current binding contour. If PFUNCTION is not 1776 // NULL, set it to the function in which the name is defined, or NULL 1777 // if the name is defined in global scope. 1778 1779 Named_object* 1780 Gogo::lookup(const std::string& name, Named_object** pfunction) const 1781 { 1782 if (pfunction != NULL) 1783 *pfunction = NULL; 1784 1785 if (Gogo::is_sink_name(name)) 1786 return Named_object::make_sink(); 1787 1788 for (Open_functions::const_reverse_iterator p = this->functions_.rbegin(); 1789 p != this->functions_.rend(); 1790 ++p) 1791 { 1792 Named_object* ret = p->blocks.back()->bindings()->lookup(name); 1793 if (ret != NULL) 1794 { 1795 if (pfunction != NULL) 1796 *pfunction = p->function; 1797 return ret; 1798 } 1799 } 1800 1801 if (this->package_ != NULL) 1802 { 1803 Named_object* ret = this->package_->bindings()->lookup(name); 1804 if (ret != NULL) 1805 { 1806 if (ret->package() != NULL) 1807 { 1808 std::string dot_alias = "." + ret->package()->package_name(); 1809 ret->package()->note_usage(dot_alias); 1810 } 1811 return ret; 1812 } 1813 } 1814 1815 // We do not look in the global namespace. If we did, the global 1816 // namespace would effectively hide names which were defined in 1817 // package scope which we have not yet seen. Instead, 1818 // define_global_names is called after parsing is over to connect 1819 // undefined names at package scope with names defined at global 1820 // scope. 1821 1822 return NULL; 1823 } 1824 1825 // Look up a name in the current block, without searching enclosing 1826 // blocks. 1827 1828 Named_object* 1829 Gogo::lookup_in_block(const std::string& name) const 1830 { 1831 go_assert(!this->functions_.empty()); 1832 go_assert(!this->functions_.back().blocks.empty()); 1833 return this->functions_.back().blocks.back()->bindings()->lookup_local(name); 1834 } 1835 1836 // Look up a name in the global namespace. 1837 1838 Named_object* 1839 Gogo::lookup_global(const char* name) const 1840 { 1841 return this->globals_->lookup(name); 1842 } 1843 1844 // Add an imported package. 1845 1846 Package* 1847 Gogo::add_imported_package(const std::string& real_name, 1848 const std::string& alias_arg, 1849 bool is_alias_exported, 1850 const std::string& pkgpath, 1851 const std::string& pkgpath_symbol, 1852 Location location, 1853 bool* padd_to_globals) 1854 { 1855 Package* ret = this->register_package(pkgpath, pkgpath_symbol, location); 1856 ret->set_package_name(real_name, location); 1857 1858 *padd_to_globals = false; 1859 1860 if (alias_arg == "_") 1861 ; 1862 else if (alias_arg == ".") 1863 { 1864 *padd_to_globals = true; 1865 std::string dot_alias = "." + real_name; 1866 ret->add_alias(dot_alias, location); 1867 } 1868 else 1869 { 1870 std::string alias = alias_arg; 1871 if (alias.empty()) 1872 { 1873 alias = real_name; 1874 is_alias_exported = Lex::is_exported_name(alias); 1875 } 1876 ret->add_alias(alias, location); 1877 alias = this->pack_hidden_name(alias, is_alias_exported); 1878 Named_object* no = this->package_->bindings()->add_package(alias, ret); 1879 if (!no->is_package()) 1880 return NULL; 1881 } 1882 1883 return ret; 1884 } 1885 1886 // Register a package. This package may or may not be imported. This 1887 // returns the Package structure for the package, creating if it 1888 // necessary. LOCATION is the location of the import statement that 1889 // led us to see this package. PKGPATH_SYMBOL is the symbol to use 1890 // for names in the package; it may be the empty string, in which case 1891 // we either get it later or make a guess when we need it. 1892 1893 Package* 1894 Gogo::register_package(const std::string& pkgpath, 1895 const std::string& pkgpath_symbol, Location location) 1896 { 1897 Package* package = NULL; 1898 std::pair<Packages::iterator, bool> ins = 1899 this->packages_.insert(std::make_pair(pkgpath, package)); 1900 if (!ins.second) 1901 { 1902 // We have seen this package name before. 1903 package = ins.first->second; 1904 go_assert(package != NULL && package->pkgpath() == pkgpath); 1905 if (!pkgpath_symbol.empty()) 1906 package->set_pkgpath_symbol(pkgpath_symbol); 1907 if (Linemap::is_unknown_location(package->location())) 1908 package->set_location(location); 1909 } 1910 else 1911 { 1912 // First time we have seen this package name. 1913 package = new Package(pkgpath, pkgpath_symbol, location); 1914 go_assert(ins.first->second == NULL); 1915 ins.first->second = package; 1916 } 1917 1918 return package; 1919 } 1920 1921 // Return the pkgpath symbol for a package, given the pkgpath. 1922 1923 std::string 1924 Gogo::pkgpath_symbol_for_package(const std::string& pkgpath) 1925 { 1926 Packages::iterator p = this->packages_.find(pkgpath); 1927 go_assert(p != this->packages_.end()); 1928 return p->second->pkgpath_symbol(); 1929 } 1930 1931 // Start compiling a function. 1932 1933 Named_object* 1934 Gogo::start_function(const std::string& name, Function_type* type, 1935 bool add_method_to_type, Location location) 1936 { 1937 bool at_top_level = this->functions_.empty(); 1938 1939 Block* block = new Block(NULL, location); 1940 1941 Named_object* enclosing = (at_top_level 1942 ? NULL 1943 : this->functions_.back().function); 1944 1945 Function* function = new Function(type, enclosing, block, location); 1946 1947 if (type->is_method()) 1948 { 1949 const Typed_identifier* receiver = type->receiver(); 1950 Variable* this_param = new Variable(receiver->type(), NULL, false, 1951 true, true, location); 1952 std::string rname = receiver->name(); 1953 unsigned rcounter = 0; 1954 1955 // We need to give a nameless receiver parameter a synthesized name to 1956 // avoid having it clash with some other nameless param. FIXME. 1957 Gogo::rename_if_empty(&rname, "r", &rcounter); 1958 1959 block->bindings()->add_variable(rname, NULL, this_param); 1960 } 1961 1962 const Typed_identifier_list* parameters = type->parameters(); 1963 bool is_varargs = type->is_varargs(); 1964 unsigned pcounter = 0; 1965 if (parameters != NULL) 1966 { 1967 for (Typed_identifier_list::const_iterator p = parameters->begin(); 1968 p != parameters->end(); 1969 ++p) 1970 { 1971 Variable* param = new Variable(p->type(), NULL, false, true, false, 1972 p->location()); 1973 if (is_varargs && p + 1 == parameters->end()) 1974 param->set_is_varargs_parameter(); 1975 1976 std::string pname = p->name(); 1977 1978 // We need to give each nameless parameter a non-empty name to avoid 1979 // having it clash with some other nameless param. FIXME. 1980 Gogo::rename_if_empty(&pname, "p", &pcounter); 1981 1982 block->bindings()->add_variable(pname, NULL, param); 1983 } 1984 } 1985 1986 function->create_result_variables(this); 1987 1988 const std::string* pname; 1989 std::string nested_name; 1990 bool is_init = false; 1991 if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method()) 1992 { 1993 if ((type->parameters() != NULL && !type->parameters()->empty()) 1994 || (type->results() != NULL && !type->results()->empty())) 1995 go_error_at(location, 1996 "func init must have no arguments and no return values"); 1997 // There can be multiple "init" functions, so give them each a 1998 // different name. 1999 nested_name = this->init_function_name(); 2000 pname = &nested_name; 2001 is_init = true; 2002 } 2003 else if (!name.empty()) 2004 pname = &name; 2005 else 2006 { 2007 // Invent a name for a nested function. 2008 nested_name = this->nested_function_name(enclosing); 2009 pname = &nested_name; 2010 } 2011 2012 Named_object* ret; 2013 if (Gogo::is_sink_name(*pname)) 2014 { 2015 std::string sname(this->sink_function_name()); 2016 ret = Named_object::make_function(sname, NULL, function); 2017 ret->func_value()->set_is_sink(); 2018 2019 if (!type->is_method()) 2020 ret = this->package_->bindings()->add_named_object(ret); 2021 else if (add_method_to_type) 2022 { 2023 // We should report errors even for sink methods. 2024 Type* rtype = type->receiver()->type(); 2025 // Avoid points_to and deref to avoid getting an error if 2026 // the type is not yet defined. 2027 if (rtype->classification() == Type::TYPE_POINTER) 2028 rtype = rtype->points_to(); 2029 while (rtype->named_type() != NULL 2030 && rtype->named_type()->is_alias()) 2031 rtype = rtype->named_type()->real_type()->forwarded(); 2032 if (rtype->is_error_type()) 2033 ; 2034 else if (rtype->named_type() != NULL) 2035 { 2036 if (rtype->named_type()->named_object()->package() != NULL) 2037 go_error_at(type->receiver()->location(), 2038 "may not define methods on non-local type"); 2039 } 2040 else if (rtype->forward_declaration_type() != NULL) 2041 { 2042 // Go ahead and add the method in case we need to report 2043 // an error when we see the definition. 2044 rtype->forward_declaration_type()->add_existing_method(ret); 2045 } 2046 else 2047 go_error_at(type->receiver()->location(), 2048 ("invalid receiver type " 2049 "(receiver must be a named type)")); 2050 } 2051 } 2052 else if (!type->is_method()) 2053 { 2054 ret = this->package_->bindings()->add_function(*pname, NULL, function); 2055 if (!ret->is_function() || ret->func_value() != function) 2056 { 2057 // Redefinition error. Invent a name to avoid knockon 2058 // errors. 2059 std::string rname(this->redefined_function_name()); 2060 ret = this->package_->bindings()->add_function(rname, NULL, function); 2061 } 2062 } 2063 else 2064 { 2065 if (!add_method_to_type) 2066 ret = Named_object::make_function(name, NULL, function); 2067 else 2068 { 2069 go_assert(at_top_level); 2070 Type* rtype = type->receiver()->type(); 2071 2072 while (rtype->named_type() != NULL 2073 && rtype->named_type()->is_alias()) 2074 rtype = rtype->named_type()->real_type()->forwarded(); 2075 2076 // We want to look through the pointer created by the 2077 // parser, without getting an error if the type is not yet 2078 // defined. 2079 if (rtype->classification() == Type::TYPE_POINTER) 2080 rtype = rtype->points_to(); 2081 2082 while (rtype->named_type() != NULL 2083 && rtype->named_type()->is_alias()) 2084 rtype = rtype->named_type()->real_type()->forwarded(); 2085 2086 if (rtype->is_error_type()) 2087 ret = Named_object::make_function(name, NULL, function); 2088 else if (rtype->named_type() != NULL) 2089 { 2090 if (rtype->named_type()->named_object()->package() != NULL) 2091 { 2092 go_error_at(type->receiver()->location(), 2093 "may not define methods on non-local type"); 2094 ret = Named_object::make_function(name, NULL, function); 2095 } 2096 else 2097 { 2098 ret = rtype->named_type()->add_method(name, function); 2099 if (!ret->is_function()) 2100 { 2101 // Redefinition error. 2102 ret = Named_object::make_function(name, NULL, function); 2103 } 2104 } 2105 } 2106 else if (rtype->forward_declaration_type() != NULL) 2107 { 2108 Named_object* type_no = 2109 rtype->forward_declaration_type()->named_object(); 2110 if (type_no->is_unknown()) 2111 { 2112 // If we are seeing methods it really must be a 2113 // type. Declare it as such. An alternative would 2114 // be to support lists of methods for unknown 2115 // expressions. Either way the error messages if 2116 // this is not a type are going to get confusing. 2117 Named_object* declared = 2118 this->declare_package_type(type_no->name(), 2119 type_no->location()); 2120 go_assert(declared 2121 == type_no->unknown_value()->real_named_object()); 2122 } 2123 ret = rtype->forward_declaration_type()->add_method(name, 2124 function); 2125 } 2126 else 2127 { 2128 go_error_at(type->receiver()->location(), 2129 ("invalid receiver type (receiver must " 2130 "be a named type)")); 2131 ret = Named_object::make_function(name, NULL, function); 2132 } 2133 } 2134 this->package_->bindings()->add_method(ret); 2135 } 2136 2137 this->functions_.resize(this->functions_.size() + 1); 2138 Open_function& of(this->functions_.back()); 2139 of.function = ret; 2140 of.blocks.push_back(block); 2141 2142 if (is_init) 2143 { 2144 this->init_functions_.push_back(ret); 2145 this->need_init_fn_ = true; 2146 } 2147 2148 return ret; 2149 } 2150 2151 // Finish compiling a function. 2152 2153 void 2154 Gogo::finish_function(Location location) 2155 { 2156 this->finish_block(location); 2157 go_assert(this->functions_.back().blocks.empty()); 2158 this->functions_.pop_back(); 2159 } 2160 2161 // Return the current function. 2162 2163 Named_object* 2164 Gogo::current_function() const 2165 { 2166 go_assert(!this->functions_.empty()); 2167 return this->functions_.back().function; 2168 } 2169 2170 // Start a new block. 2171 2172 void 2173 Gogo::start_block(Location location) 2174 { 2175 go_assert(!this->functions_.empty()); 2176 Block* block = new Block(this->current_block(), location); 2177 this->functions_.back().blocks.push_back(block); 2178 } 2179 2180 // Finish a block. 2181 2182 Block* 2183 Gogo::finish_block(Location location) 2184 { 2185 go_assert(!this->functions_.empty()); 2186 go_assert(!this->functions_.back().blocks.empty()); 2187 Block* block = this->functions_.back().blocks.back(); 2188 this->functions_.back().blocks.pop_back(); 2189 block->set_end_location(location); 2190 return block; 2191 } 2192 2193 // Add an erroneous name. 2194 2195 Named_object* 2196 Gogo::add_erroneous_name(const std::string& name) 2197 { 2198 return this->package_->bindings()->add_erroneous_name(name); 2199 } 2200 2201 // Add an unknown name. 2202 2203 Named_object* 2204 Gogo::add_unknown_name(const std::string& name, Location location) 2205 { 2206 return this->package_->bindings()->add_unknown_name(name, location); 2207 } 2208 2209 // Declare a function. 2210 2211 Named_object* 2212 Gogo::declare_function(const std::string& name, Function_type* type, 2213 Location location) 2214 { 2215 if (!type->is_method()) 2216 return this->current_bindings()->add_function_declaration(name, NULL, type, 2217 location); 2218 else 2219 { 2220 // We don't bother to add this to the list of global 2221 // declarations. 2222 Type* rtype = type->receiver()->type(); 2223 2224 while (rtype->named_type() != NULL 2225 && rtype->named_type()->is_alias()) 2226 rtype = rtype->named_type()->real_type()->forwarded(); 2227 2228 // We want to look through the pointer created by the 2229 // parser, without getting an error if the type is not yet 2230 // defined. 2231 if (rtype->classification() == Type::TYPE_POINTER) 2232 rtype = rtype->points_to(); 2233 2234 while (rtype->named_type() != NULL 2235 && rtype->named_type()->is_alias()) 2236 rtype = rtype->named_type()->real_type()->forwarded(); 2237 2238 if (rtype->is_error_type()) 2239 return NULL; 2240 else if (rtype->named_type() != NULL) 2241 return rtype->named_type()->add_method_declaration(name, NULL, type, 2242 location); 2243 else if (rtype->forward_declaration_type() != NULL) 2244 { 2245 Forward_declaration_type* ftype = rtype->forward_declaration_type(); 2246 return ftype->add_method_declaration(name, NULL, type, location); 2247 } 2248 else 2249 { 2250 go_error_at(type->receiver()->location(), 2251 "invalid receiver type (receiver must be a named type)"); 2252 return Named_object::make_erroneous_name(name); 2253 } 2254 } 2255 } 2256 2257 // Add a label definition. 2258 2259 Label* 2260 Gogo::add_label_definition(const std::string& label_name, 2261 Location location) 2262 { 2263 go_assert(!this->functions_.empty()); 2264 Function* func = this->functions_.back().function->func_value(); 2265 Label* label = func->add_label_definition(this, label_name, location); 2266 this->add_statement(Statement::make_label_statement(label, location)); 2267 return label; 2268 } 2269 2270 // Add a label reference. 2271 2272 Label* 2273 Gogo::add_label_reference(const std::string& label_name, 2274 Location location, bool issue_goto_errors) 2275 { 2276 go_assert(!this->functions_.empty()); 2277 Function* func = this->functions_.back().function->func_value(); 2278 return func->add_label_reference(this, label_name, location, 2279 issue_goto_errors); 2280 } 2281 2282 // Return the current binding state. 2283 2284 Bindings_snapshot* 2285 Gogo::bindings_snapshot(Location location) 2286 { 2287 return new Bindings_snapshot(this->current_block(), location); 2288 } 2289 2290 // Add a statement. 2291 2292 void 2293 Gogo::add_statement(Statement* statement) 2294 { 2295 go_assert(!this->functions_.empty() 2296 && !this->functions_.back().blocks.empty()); 2297 this->functions_.back().blocks.back()->add_statement(statement); 2298 } 2299 2300 // Add a block. 2301 2302 void 2303 Gogo::add_block(Block* block, Location location) 2304 { 2305 go_assert(!this->functions_.empty() 2306 && !this->functions_.back().blocks.empty()); 2307 Statement* statement = Statement::make_block_statement(block, location); 2308 this->functions_.back().blocks.back()->add_statement(statement); 2309 } 2310 2311 // Add a constant. 2312 2313 Named_object* 2314 Gogo::add_constant(const Typed_identifier& tid, Expression* expr, 2315 int iota_value) 2316 { 2317 return this->current_bindings()->add_constant(tid, NULL, expr, iota_value); 2318 } 2319 2320 // Add a type. 2321 2322 void 2323 Gogo::add_type(const std::string& name, Type* type, Location location) 2324 { 2325 Named_object* no = this->current_bindings()->add_type(name, NULL, type, 2326 location); 2327 if (!this->in_global_scope() && no->is_type()) 2328 { 2329 Named_object* f = this->functions_.back().function; 2330 unsigned int index; 2331 if (f->is_function()) 2332 index = f->func_value()->new_local_type_index(); 2333 else 2334 index = 0; 2335 no->type_value()->set_in_function(f, index); 2336 } 2337 } 2338 2339 // Add a named type. 2340 2341 void 2342 Gogo::add_named_type(Named_type* type) 2343 { 2344 go_assert(this->in_global_scope()); 2345 this->current_bindings()->add_named_type(type); 2346 } 2347 2348 // Declare a type. 2349 2350 Named_object* 2351 Gogo::declare_type(const std::string& name, Location location) 2352 { 2353 Bindings* bindings = this->current_bindings(); 2354 Named_object* no = bindings->add_type_declaration(name, NULL, location); 2355 if (!this->in_global_scope() && no->is_type_declaration()) 2356 { 2357 Named_object* f = this->functions_.back().function; 2358 unsigned int index; 2359 if (f->is_function()) 2360 index = f->func_value()->new_local_type_index(); 2361 else 2362 index = 0; 2363 no->type_declaration_value()->set_in_function(f, index); 2364 } 2365 return no; 2366 } 2367 2368 // Declare a type at the package level. 2369 2370 Named_object* 2371 Gogo::declare_package_type(const std::string& name, Location location) 2372 { 2373 return this->package_->bindings()->add_type_declaration(name, NULL, location); 2374 } 2375 2376 // Declare a function at the package level. 2377 2378 Named_object* 2379 Gogo::declare_package_function(const std::string& name, Function_type* type, 2380 Location location) 2381 { 2382 return this->package_->bindings()->add_function_declaration(name, NULL, type, 2383 location); 2384 } 2385 2386 // Add a function declaration to the list of functions we may want to 2387 // inline. 2388 2389 void 2390 Gogo::add_imported_inlinable_function(Named_object* no) 2391 { 2392 go_assert(no->is_function_declaration()); 2393 Function_declaration* fd = no->func_declaration_value(); 2394 if (fd->is_on_inlinable_list()) 2395 return; 2396 this->imported_inlinable_functions_.push_back(no); 2397 fd->set_is_on_inlinable_list(); 2398 } 2399 2400 // Define a type which was already declared. 2401 2402 void 2403 Gogo::define_type(Named_object* no, Named_type* type) 2404 { 2405 this->current_bindings()->define_type(no, type); 2406 } 2407 2408 // Add a variable. 2409 2410 Named_object* 2411 Gogo::add_variable(const std::string& name, Variable* variable) 2412 { 2413 Named_object* no = this->current_bindings()->add_variable(name, NULL, 2414 variable); 2415 2416 // In a function the middle-end wants to see a DECL_EXPR node. 2417 if (no != NULL 2418 && no->is_variable() 2419 && !no->var_value()->is_parameter() 2420 && !this->functions_.empty()) 2421 this->add_statement(Statement::make_variable_declaration(no)); 2422 2423 return no; 2424 } 2425 2426 void 2427 Gogo::rename_if_empty(std::string* pname, const char* tag, unsigned* count) 2428 { 2429 if (pname->empty() || Gogo::is_sink_name(*pname)) 2430 { 2431 char buf[50]; 2432 go_assert(strlen(tag) < 10); 2433 snprintf(buf, sizeof buf, "%s.%u", tag, *count); 2434 ++(*count); 2435 *pname = buf; 2436 } 2437 } 2438 2439 2440 // Add a sink--a reference to the blank identifier _. 2441 2442 Named_object* 2443 Gogo::add_sink() 2444 { 2445 return Named_object::make_sink(); 2446 } 2447 2448 // Add a named object for a dot import. 2449 2450 void 2451 Gogo::add_dot_import_object(Named_object* no) 2452 { 2453 // If the name already exists, then it was defined in some file seen 2454 // earlier. If the earlier name is just a declaration, don't add 2455 // this name, because that will cause the previous declaration to 2456 // merge to this imported name, which should not happen. Just add 2457 // this name to the list of file block names to get appropriate 2458 // errors if we see a later definition. 2459 Named_object* e = this->package_->bindings()->lookup(no->name()); 2460 if (e != NULL && e->package() == NULL) 2461 { 2462 if (e->is_unknown()) 2463 e = e->resolve(); 2464 if (e->package() == NULL 2465 && (e->is_type_declaration() 2466 || e->is_function_declaration() 2467 || e->is_unknown())) 2468 { 2469 this->add_file_block_name(no->name(), no->location()); 2470 return; 2471 } 2472 } 2473 2474 this->current_bindings()->add_named_object(no); 2475 } 2476 2477 // Add a linkname. This implements the go:linkname compiler directive. 2478 // We only support this for functions and function declarations. 2479 2480 void 2481 Gogo::add_linkname(const std::string& go_name, bool is_exported, 2482 const std::string& ext_name, Location loc) 2483 { 2484 Named_object* no = 2485 this->package_->bindings()->lookup(this->pack_hidden_name(go_name, 2486 is_exported)); 2487 if (no == NULL) 2488 go_error_at(loc, "%s is not defined", go_name.c_str()); 2489 else if (no->is_function()) 2490 { 2491 if (ext_name.empty()) 2492 no->func_value()->set_is_exported_by_linkname(); 2493 else 2494 no->func_value()->set_asm_name(ext_name); 2495 } 2496 else if (no->is_function_declaration()) 2497 { 2498 if (ext_name.empty()) 2499 go_error_at(loc, 2500 ("%<//go:linkname%> missing external name " 2501 "for declaration of %s"), 2502 go_name.c_str()); 2503 else 2504 no->func_declaration_value()->set_asm_name(ext_name); 2505 } 2506 else 2507 go_error_at(loc, 2508 ("%s is not a function; " 2509 "%<//go:linkname%> is only supported for functions"), 2510 go_name.c_str()); 2511 } 2512 2513 // Mark all local variables used. This is used when some types of 2514 // parse error occur. 2515 2516 void 2517 Gogo::mark_locals_used() 2518 { 2519 for (Open_functions::iterator pf = this->functions_.begin(); 2520 pf != this->functions_.end(); 2521 ++pf) 2522 { 2523 for (std::vector<Block*>::iterator pb = pf->blocks.begin(); 2524 pb != pf->blocks.end(); 2525 ++pb) 2526 (*pb)->bindings()->mark_locals_used(); 2527 } 2528 } 2529 2530 // Record that we've seen an interface type. 2531 2532 void 2533 Gogo::record_interface_type(Interface_type* itype) 2534 { 2535 this->interface_types_.push_back(itype); 2536 } 2537 2538 // Define the global names. We do this only after parsing all the 2539 // input files, because the program might define the global names 2540 // itself. 2541 2542 void 2543 Gogo::define_global_names() 2544 { 2545 if (this->is_main_package()) 2546 { 2547 // Every Go program has to import the runtime package, so that 2548 // it is properly initialized. We can't use 2549 // predeclared_location here as it will cause runtime functions 2550 // to appear to be builtin functions. 2551 this->import_package("runtime", "_", false, false, 2552 this->package_->location()); 2553 } 2554 2555 for (Bindings::const_declarations_iterator p = 2556 this->globals_->begin_declarations(); 2557 p != this->globals_->end_declarations(); 2558 ++p) 2559 { 2560 Named_object* global_no = p->second; 2561 std::string name(Gogo::pack_hidden_name(global_no->name(), false)); 2562 Named_object* no = this->package_->bindings()->lookup(name); 2563 if (no == NULL) 2564 continue; 2565 no = no->resolve(); 2566 if (no->is_type_declaration()) 2567 { 2568 if (global_no->is_type()) 2569 { 2570 if (no->type_declaration_value()->has_methods()) 2571 { 2572 for (std::vector<Named_object*>::const_iterator pm = 2573 no->type_declaration_value()->methods()->begin(); 2574 pm != no->type_declaration_value()->methods()->end(); 2575 pm++) 2576 go_error_at((*pm)->location(), 2577 "may not define methods on non-local type"); 2578 } 2579 no->set_type_value(global_no->type_value()); 2580 } 2581 else 2582 { 2583 go_error_at(no->location(), "expected type"); 2584 Type* errtype = Type::make_error_type(); 2585 Named_object* err = 2586 Named_object::make_type("erroneous_type", NULL, errtype, 2587 Linemap::predeclared_location()); 2588 no->set_type_value(err->type_value()); 2589 } 2590 } 2591 else if (no->is_unknown()) 2592 no->unknown_value()->set_real_named_object(global_no); 2593 } 2594 2595 // Give an error if any name is defined in both the package block 2596 // and the file block. For example, this can happen if one file 2597 // imports "fmt" and another file defines a global variable fmt. 2598 for (Bindings::const_declarations_iterator p = 2599 this->package_->bindings()->begin_declarations(); 2600 p != this->package_->bindings()->end_declarations(); 2601 ++p) 2602 { 2603 if (p->second->is_unknown() 2604 && p->second->unknown_value()->real_named_object() == NULL) 2605 { 2606 // No point in warning about an undefined name, as we will 2607 // get other errors later anyhow. 2608 continue; 2609 } 2610 File_block_names::const_iterator pf = 2611 this->file_block_names_.find(p->second->name()); 2612 if (pf != this->file_block_names_.end()) 2613 { 2614 std::string n = p->second->message_name(); 2615 go_error_at(p->second->location(), 2616 "%qs defined as both imported name and global name", 2617 n.c_str()); 2618 go_inform(pf->second, "%qs imported here", n.c_str()); 2619 } 2620 2621 // No package scope identifier may be named "init". 2622 if (!p->second->is_function() 2623 && Gogo::unpack_hidden_name(p->second->name()) == "init") 2624 { 2625 go_error_at(p->second->location(), 2626 "cannot declare init - must be func"); 2627 } 2628 } 2629 } 2630 2631 // Clear out names in file scope. 2632 2633 void 2634 Gogo::clear_file_scope() 2635 { 2636 this->package_->bindings()->clear_file_scope(this); 2637 2638 // Warn about packages which were imported but not used. 2639 bool quiet = saw_errors(); 2640 for (Packages::iterator p = this->packages_.begin(); 2641 p != this->packages_.end(); 2642 ++p) 2643 { 2644 Package* package = p->second; 2645 if (package != this->package_ && !quiet) 2646 { 2647 for (Package::Aliases::const_iterator p1 = package->aliases().begin(); 2648 p1 != package->aliases().end(); 2649 ++p1) 2650 { 2651 if (!p1->second->used()) 2652 { 2653 // Give a more refined error message if the alias name is known. 2654 std::string pkg_name = package->package_name(); 2655 if (p1->first != pkg_name && p1->first[0] != '.') 2656 { 2657 go_error_at(p1->second->location(), 2658 "imported and not used: %s as %s", 2659 Gogo::message_name(pkg_name).c_str(), 2660 Gogo::message_name(p1->first).c_str()); 2661 } 2662 else 2663 go_error_at(p1->second->location(), 2664 "imported and not used: %s", 2665 Gogo::message_name(pkg_name).c_str()); 2666 } 2667 } 2668 } 2669 package->clear_used(); 2670 } 2671 2672 this->current_file_imported_unsafe_ = false; 2673 this->current_file_imported_embed_ = false; 2674 } 2675 2676 // Queue up a type-specific hash function for later writing. These 2677 // are written out in write_specific_type_functions, called after the 2678 // parse tree is lowered. 2679 2680 void 2681 Gogo::queue_hash_function(Type* type, int64_t size, Backend_name* bname, 2682 Function_type* hash_fntype) 2683 { 2684 go_assert(!this->specific_type_functions_are_written_); 2685 go_assert(!this->in_global_scope()); 2686 Specific_type_function::Specific_type_function_kind kind = 2687 Specific_type_function::SPECIFIC_HASH; 2688 Specific_type_function* tsf = new Specific_type_function(type, NULL, size, 2689 kind, bname, 2690 hash_fntype); 2691 this->specific_type_functions_.push_back(tsf); 2692 } 2693 2694 // Queue up a type-specific equal function for later writing. These 2695 // are written out in write_specific_type_functions, called after the 2696 // parse tree is lowered. 2697 2698 void 2699 Gogo::queue_equal_function(Type* type, Named_type* name, int64_t size, 2700 Backend_name* bname, Function_type* equal_fntype) 2701 { 2702 go_assert(!this->specific_type_functions_are_written_); 2703 go_assert(!this->in_global_scope()); 2704 Specific_type_function::Specific_type_function_kind kind = 2705 Specific_type_function::SPECIFIC_EQUAL; 2706 Specific_type_function* tsf = new Specific_type_function(type, name, size, 2707 kind, bname, 2708 equal_fntype); 2709 this->specific_type_functions_.push_back(tsf); 2710 } 2711 2712 // Look for types which need specific hash or equality functions. 2713 2714 class Specific_type_functions : public Traverse 2715 { 2716 public: 2717 Specific_type_functions(Gogo* gogo) 2718 : Traverse(traverse_types), 2719 gogo_(gogo) 2720 { } 2721 2722 int 2723 type(Type*); 2724 2725 private: 2726 Gogo* gogo_; 2727 }; 2728 2729 int 2730 Specific_type_functions::type(Type* t) 2731 { 2732 switch (t->classification()) 2733 { 2734 case Type::TYPE_NAMED: 2735 { 2736 Named_type* nt = t->named_type(); 2737 if (nt->is_alias()) 2738 return TRAVERSE_CONTINUE; 2739 if (t->needs_specific_type_functions(this->gogo_)) 2740 t->equal_function(this->gogo_, nt, NULL); 2741 2742 // If this is a struct type, we don't want to make functions 2743 // for the unnamed struct. 2744 Type* rt = nt->real_type(); 2745 if (rt->struct_type() == NULL) 2746 { 2747 if (Type::traverse(rt, this) == TRAVERSE_EXIT) 2748 return TRAVERSE_EXIT; 2749 } 2750 else 2751 { 2752 // If this type is defined in another package, then we don't 2753 // need to worry about the unexported fields. 2754 bool is_defined_elsewhere = nt->named_object()->package() != NULL; 2755 const Struct_field_list* fields = rt->struct_type()->fields(); 2756 for (Struct_field_list::const_iterator p = fields->begin(); 2757 p != fields->end(); 2758 ++p) 2759 { 2760 if (is_defined_elsewhere 2761 && Gogo::is_hidden_name(p->field_name())) 2762 continue; 2763 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT) 2764 return TRAVERSE_EXIT; 2765 } 2766 } 2767 2768 return TRAVERSE_SKIP_COMPONENTS; 2769 } 2770 2771 case Type::TYPE_STRUCT: 2772 case Type::TYPE_ARRAY: 2773 if (t->needs_specific_type_functions(this->gogo_)) 2774 t->equal_function(this->gogo_, NULL, NULL); 2775 break; 2776 2777 case Type::TYPE_MAP: 2778 { 2779 Type* key_type = t->map_type()->key_type()->unalias(); 2780 if (key_type->needs_specific_type_functions(this->gogo_)) 2781 key_type->hash_function(this->gogo_, NULL); 2782 } 2783 break; 2784 2785 default: 2786 break; 2787 } 2788 2789 return TRAVERSE_CONTINUE; 2790 } 2791 2792 // Write out type specific functions. 2793 2794 void 2795 Gogo::write_specific_type_functions() 2796 { 2797 Specific_type_functions stf(this); 2798 this->traverse(&stf); 2799 2800 while (!this->specific_type_functions_.empty()) 2801 { 2802 Specific_type_function* tsf = this->specific_type_functions_.back(); 2803 this->specific_type_functions_.pop_back(); 2804 if (tsf->kind == Specific_type_function::SPECIFIC_HASH) 2805 tsf->type->write_hash_function(this, tsf->size, &tsf->bname, 2806 tsf->fntype); 2807 else 2808 tsf->type->write_equal_function(this, tsf->name, tsf->size, 2809 &tsf->bname, tsf->fntype); 2810 delete tsf; 2811 } 2812 this->specific_type_functions_are_written_ = true; 2813 } 2814 2815 // Traverse the tree. 2816 2817 void 2818 Gogo::traverse(Traverse* traverse) 2819 { 2820 // Traverse the current package first for consistency. The other 2821 // packages will only contain imported types, constants, and 2822 // declarations. 2823 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT) 2824 return; 2825 for (Packages::const_iterator p = this->packages_.begin(); 2826 p != this->packages_.end(); 2827 ++p) 2828 { 2829 if (p->second != this->package_) 2830 { 2831 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT) 2832 break; 2833 } 2834 } 2835 } 2836 2837 // Add a type to verify. This is used for types of sink variables, in 2838 // order to give appropriate error messages. 2839 2840 void 2841 Gogo::add_type_to_verify(Type* type) 2842 { 2843 this->verify_types_.push_back(type); 2844 } 2845 2846 // Traversal class used to verify types. 2847 2848 class Verify_types : public Traverse 2849 { 2850 public: 2851 Verify_types() 2852 : Traverse(traverse_types) 2853 { } 2854 2855 int 2856 type(Type*); 2857 }; 2858 2859 // Verify that a type is correct. 2860 2861 int 2862 Verify_types::type(Type* t) 2863 { 2864 if (!t->verify()) 2865 return TRAVERSE_SKIP_COMPONENTS; 2866 return TRAVERSE_CONTINUE; 2867 } 2868 2869 // Verify that all types are correct. 2870 2871 void 2872 Gogo::verify_types() 2873 { 2874 Verify_types traverse; 2875 this->traverse(&traverse); 2876 2877 for (std::vector<Type*>::iterator p = this->verify_types_.begin(); 2878 p != this->verify_types_.end(); 2879 ++p) 2880 (*p)->verify(); 2881 this->verify_types_.clear(); 2882 } 2883 2884 // Traversal class used to lower parse tree. 2885 2886 class Lower_parse_tree : public Traverse 2887 { 2888 public: 2889 Lower_parse_tree(Gogo* gogo, Named_object* function) 2890 : Traverse(traverse_variables 2891 | traverse_constants 2892 | traverse_functions 2893 | traverse_statements 2894 | traverse_expressions), 2895 gogo_(gogo), function_(function), iota_value_(-1), inserter_() 2896 { } 2897 2898 void 2899 set_inserter(const Statement_inserter* inserter) 2900 { this->inserter_ = *inserter; } 2901 2902 int 2903 variable(Named_object*); 2904 2905 int 2906 constant(Named_object*, bool); 2907 2908 int 2909 function(Named_object*); 2910 2911 int 2912 statement(Block*, size_t* pindex, Statement*); 2913 2914 int 2915 expression(Expression**); 2916 2917 private: 2918 // General IR. 2919 Gogo* gogo_; 2920 // The function we are traversing. 2921 Named_object* function_; 2922 // Value to use for the predeclared constant iota. 2923 int iota_value_; 2924 // Current statement inserter for use by expressions. 2925 Statement_inserter inserter_; 2926 }; 2927 2928 // Lower variables. 2929 2930 int 2931 Lower_parse_tree::variable(Named_object* no) 2932 { 2933 if (!no->is_variable()) 2934 return TRAVERSE_CONTINUE; 2935 2936 if (no->is_variable() && no->var_value()->is_global()) 2937 { 2938 // Global variables can have loops in their initialization 2939 // expressions. This is handled in lower_init_expression. 2940 no->var_value()->lower_init_expression(this->gogo_, this->function_, 2941 &this->inserter_); 2942 return TRAVERSE_CONTINUE; 2943 } 2944 2945 // This is a local variable. We are going to return 2946 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the 2947 // initialization expression when we reach the variable declaration 2948 // statement. However, that means that we need to traverse the type 2949 // ourselves. 2950 if (no->var_value()->has_type()) 2951 { 2952 Type* type = no->var_value()->type(); 2953 if (type != NULL) 2954 { 2955 if (Type::traverse(type, this) == TRAVERSE_EXIT) 2956 return TRAVERSE_EXIT; 2957 } 2958 } 2959 go_assert(!no->var_value()->has_pre_init()); 2960 2961 return TRAVERSE_SKIP_COMPONENTS; 2962 } 2963 2964 // Lower constants. We handle constants specially so that we can set 2965 // the right value for the predeclared constant iota. This works in 2966 // conjunction with the way we lower Const_expression objects. 2967 2968 int 2969 Lower_parse_tree::constant(Named_object* no, bool) 2970 { 2971 Named_constant* nc = no->const_value(); 2972 2973 // Don't get into trouble if the constant's initializer expression 2974 // refers to the constant itself. 2975 if (nc->lowering()) 2976 return TRAVERSE_CONTINUE; 2977 nc->set_lowering(); 2978 2979 go_assert(this->iota_value_ == -1); 2980 this->iota_value_ = nc->iota_value(); 2981 nc->traverse_expression(this); 2982 this->iota_value_ = -1; 2983 2984 nc->clear_lowering(); 2985 2986 // We will traverse the expression a second time, but that will be 2987 // fast. 2988 2989 return TRAVERSE_CONTINUE; 2990 } 2991 2992 // Lower the body of a function, and set the closure type. Record the 2993 // function while lowering it, so that we can pass it down when 2994 // lowering an expression. 2995 2996 int 2997 Lower_parse_tree::function(Named_object* no) 2998 { 2999 no->func_value()->set_closure_type(); 3000 3001 go_assert(this->function_ == NULL); 3002 this->function_ = no; 3003 int t = no->func_value()->traverse(this); 3004 this->function_ = NULL; 3005 3006 if (t == TRAVERSE_EXIT) 3007 return t; 3008 return TRAVERSE_SKIP_COMPONENTS; 3009 } 3010 3011 // Lower statement parse trees. 3012 3013 int 3014 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig) 3015 { 3016 // Because we explicitly traverse the statement's contents 3017 // ourselves, we want to skip block statements here. There is 3018 // nothing to lower in a block statement. 3019 if (sorig->is_block_statement()) 3020 return TRAVERSE_CONTINUE; 3021 3022 Statement_inserter hold_inserter(this->inserter_); 3023 this->inserter_ = Statement_inserter(block, pindex); 3024 3025 // Lower the expressions first. 3026 int t = sorig->traverse_contents(this); 3027 if (t == TRAVERSE_EXIT) 3028 { 3029 this->inserter_ = hold_inserter; 3030 return t; 3031 } 3032 3033 // Keep lowering until nothing changes. 3034 Statement* s = sorig; 3035 while (true) 3036 { 3037 Statement* snew = s->lower(this->gogo_, this->function_, block, 3038 &this->inserter_); 3039 if (snew == s) 3040 break; 3041 s = snew; 3042 t = s->traverse_contents(this); 3043 if (t == TRAVERSE_EXIT) 3044 { 3045 this->inserter_ = hold_inserter; 3046 return t; 3047 } 3048 } 3049 3050 if (s != sorig) 3051 block->replace_statement(*pindex, s); 3052 3053 this->inserter_ = hold_inserter; 3054 return TRAVERSE_SKIP_COMPONENTS; 3055 } 3056 3057 // Lower expression parse trees. 3058 3059 int 3060 Lower_parse_tree::expression(Expression** pexpr) 3061 { 3062 // We have to lower all subexpressions first, so that we can get 3063 // their type if necessary. This is awkward, because we don't have 3064 // a postorder traversal pass. 3065 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT) 3066 return TRAVERSE_EXIT; 3067 // Keep lowering until nothing changes. 3068 while (true) 3069 { 3070 Expression* e = *pexpr; 3071 Expression* enew = e->lower(this->gogo_, this->function_, 3072 &this->inserter_, this->iota_value_); 3073 if (enew == e) 3074 break; 3075 if (enew->traverse_subexpressions(this) == TRAVERSE_EXIT) 3076 return TRAVERSE_EXIT; 3077 *pexpr = enew; 3078 } 3079 3080 // Lower the type of this expression before the parent looks at it, 3081 // in case the type contains an array that has expressions in its 3082 // length. Skip an Unknown_expression, as at this point that means 3083 // a composite literal key that does not have a type. 3084 if ((*pexpr)->unknown_expression() == NULL) 3085 Type::traverse((*pexpr)->type(), this); 3086 3087 return TRAVERSE_SKIP_COMPONENTS; 3088 } 3089 3090 // Lower the parse tree. This is called after the parse is complete, 3091 // when all names should be resolved. 3092 3093 void 3094 Gogo::lower_parse_tree() 3095 { 3096 Lower_parse_tree lower_parse_tree(this, NULL); 3097 this->traverse(&lower_parse_tree); 3098 3099 // If we found any functions defined in other packages that are 3100 // inlinables, import their bodies and turn them into functions. 3101 // 3102 // Note that as we import inlinable functions we may find more 3103 // inlinable functions, so don't use an iterator. 3104 for (size_t i = 0; i < this->imported_inlinable_functions_.size(); i++) 3105 { 3106 Named_object* no = this->imported_inlinable_functions_[i]; 3107 no->func_declaration_value()->import_function_body(this, no); 3108 } 3109 3110 // There might be type definitions that involve expressions such as the 3111 // array length. Make sure to lower these expressions as well. Otherwise, 3112 // errors hidden within a type can introduce unexpected errors into later 3113 // passes. 3114 for (std::vector<Type*>::iterator p = this->verify_types_.begin(); 3115 p != this->verify_types_.end(); 3116 ++p) 3117 Type::traverse(*p, &lower_parse_tree); 3118 } 3119 3120 // Lower a block. 3121 3122 void 3123 Gogo::lower_block(Named_object* function, Block* block) 3124 { 3125 Lower_parse_tree lower_parse_tree(this, function); 3126 block->traverse(&lower_parse_tree); 3127 } 3128 3129 // Lower an expression. INSERTER may be NULL, in which case the 3130 // expression had better not need to create any temporaries. 3131 3132 void 3133 Gogo::lower_expression(Named_object* function, Statement_inserter* inserter, 3134 Expression** pexpr) 3135 { 3136 Lower_parse_tree lower_parse_tree(this, function); 3137 if (inserter != NULL) 3138 lower_parse_tree.set_inserter(inserter); 3139 lower_parse_tree.expression(pexpr); 3140 } 3141 3142 // Lower a constant. This is called when lowering a reference to a 3143 // constant. We have to make sure that the constant has already been 3144 // lowered. 3145 3146 void 3147 Gogo::lower_constant(Named_object* no) 3148 { 3149 go_assert(no->is_const()); 3150 Lower_parse_tree lower(this, NULL); 3151 lower.constant(no, false); 3152 } 3153 3154 // Make implicit type conversions explicit. Currently only does for 3155 // interface conversions, so the escape analysis can see them and 3156 // optimize. 3157 3158 class Add_conversions : public Traverse 3159 { 3160 public: 3161 Add_conversions() 3162 : Traverse(traverse_statements 3163 | traverse_expressions) 3164 { } 3165 3166 int 3167 statement(Block*, size_t* pindex, Statement*); 3168 3169 int 3170 expression(Expression**); 3171 }; 3172 3173 // Add explicit conversions in a statement. 3174 3175 int 3176 Add_conversions::statement(Block*, size_t*, Statement* sorig) 3177 { 3178 sorig->add_conversions(); 3179 return TRAVERSE_CONTINUE; 3180 } 3181 3182 // Add explicit conversions in an expression. 3183 3184 int 3185 Add_conversions::expression(Expression** pexpr) 3186 { 3187 (*pexpr)->add_conversions(); 3188 return TRAVERSE_CONTINUE; 3189 } 3190 3191 void 3192 Gogo::add_conversions() 3193 { 3194 Add_conversions add_conversions; 3195 this->traverse(&add_conversions); 3196 } 3197 3198 void 3199 Gogo::add_conversions_in_block(Block *b) 3200 { 3201 Add_conversions add_conversions; 3202 b->traverse(&add_conversions); 3203 } 3204 3205 // Traversal class for simple deadcode elimination. 3206 3207 class Remove_deadcode : public Traverse 3208 { 3209 public: 3210 Remove_deadcode() 3211 : Traverse(traverse_statements 3212 | traverse_expressions) 3213 { } 3214 3215 int 3216 statement(Block*, size_t* pindex, Statement*); 3217 3218 int 3219 expression(Expression**); 3220 }; 3221 3222 // Remove deadcode in a statement. 3223 3224 int 3225 Remove_deadcode::statement(Block* block, size_t* pindex, Statement* sorig) 3226 { 3227 Location loc = sorig->location(); 3228 If_statement* ifs = sorig->if_statement(); 3229 if (ifs != NULL) 3230 { 3231 // Remove the dead branch of an if statement. 3232 bool bval; 3233 if (ifs->condition()->boolean_constant_value(&bval)) 3234 { 3235 Statement* s; 3236 if (bval) 3237 s = Statement::make_block_statement(ifs->then_block(), 3238 loc); 3239 else 3240 if (ifs->else_block() != NULL) 3241 s = Statement::make_block_statement(ifs->else_block(), 3242 loc); 3243 else 3244 // Make a dummy statement. 3245 s = Statement::make_statement(Expression::make_boolean(false, loc), 3246 true); 3247 3248 block->replace_statement(*pindex, s); 3249 } 3250 } 3251 return TRAVERSE_CONTINUE; 3252 } 3253 3254 // Remove deadcode in an expression. 3255 3256 int 3257 Remove_deadcode::expression(Expression** pexpr) 3258 { 3259 // Discard the right arm of a shortcut expression of constant value. 3260 Binary_expression* be = (*pexpr)->binary_expression(); 3261 bool bval; 3262 if (be != NULL 3263 && be->boolean_constant_value(&bval) 3264 && (be->op() == OPERATOR_ANDAND 3265 || be->op() == OPERATOR_OROR)) 3266 { 3267 *pexpr = Expression::make_boolean(bval, be->location()); 3268 Type_context context(NULL, false); 3269 (*pexpr)->determine_type(&context); 3270 } 3271 return TRAVERSE_CONTINUE; 3272 } 3273 3274 // Remove deadcode. 3275 3276 void 3277 Gogo::remove_deadcode() 3278 { 3279 Remove_deadcode remove_deadcode; 3280 this->traverse(&remove_deadcode); 3281 } 3282 3283 // Traverse the tree to create function descriptors as needed. 3284 3285 class Create_function_descriptors : public Traverse 3286 { 3287 public: 3288 Create_function_descriptors(Gogo* gogo) 3289 : Traverse(traverse_functions | traverse_expressions), 3290 gogo_(gogo) 3291 { } 3292 3293 int 3294 function(Named_object*); 3295 3296 int 3297 expression(Expression**); 3298 3299 private: 3300 Gogo* gogo_; 3301 }; 3302 3303 // Create a descriptor for every top-level exported function and every 3304 // function referenced by an inline function. 3305 3306 int 3307 Create_function_descriptors::function(Named_object* no) 3308 { 3309 if (no->is_function() 3310 && no->func_value()->enclosing() == NULL 3311 && !no->func_value()->is_method() 3312 && ((!Gogo::is_hidden_name(no->name()) 3313 && !Gogo::is_thunk(no)) 3314 || no->func_value()->is_referenced_by_inline())) 3315 no->func_value()->descriptor(this->gogo_, no); 3316 3317 return TRAVERSE_CONTINUE; 3318 } 3319 3320 // If we see a function referenced in any way other than calling it, 3321 // create a descriptor for it. 3322 3323 int 3324 Create_function_descriptors::expression(Expression** pexpr) 3325 { 3326 Expression* expr = *pexpr; 3327 3328 Func_expression* fe = expr->func_expression(); 3329 if (fe != NULL) 3330 { 3331 // We would not get here for a call to this function, so this is 3332 // a reference to a function other than calling it. We need a 3333 // descriptor. 3334 if (fe->closure() != NULL) 3335 return TRAVERSE_CONTINUE; 3336 Named_object* no = fe->named_object(); 3337 if (no->is_function() && !no->func_value()->is_method()) 3338 no->func_value()->descriptor(this->gogo_, no); 3339 else if (no->is_function_declaration() 3340 && !no->func_declaration_value()->type()->is_method() 3341 && !Linemap::is_predeclared_location(no->location())) 3342 no->func_declaration_value()->descriptor(this->gogo_, no); 3343 return TRAVERSE_CONTINUE; 3344 } 3345 3346 Bound_method_expression* bme = expr->bound_method_expression(); 3347 if (bme != NULL) 3348 { 3349 // We would not get here for a call to this method, so this is a 3350 // method value. We need to create a thunk. 3351 Bound_method_expression::create_thunk(this->gogo_, bme->method(), 3352 bme->function()); 3353 return TRAVERSE_CONTINUE; 3354 } 3355 3356 Interface_field_reference_expression* ifre = 3357 expr->interface_field_reference_expression(); 3358 if (ifre != NULL) 3359 { 3360 // We would not get here for a call to this interface method, so 3361 // this is a method value. We need to create a thunk. 3362 Interface_type* type = ifre->expr()->type()->interface_type(); 3363 if (type != NULL) 3364 Interface_field_reference_expression::create_thunk(this->gogo_, type, 3365 ifre->name()); 3366 return TRAVERSE_CONTINUE; 3367 } 3368 3369 Call_expression* ce = expr->call_expression(); 3370 if (ce != NULL) 3371 { 3372 Expression* fn = ce->fn(); 3373 if (fn->func_expression() != NULL 3374 || fn->bound_method_expression() != NULL 3375 || fn->interface_field_reference_expression() != NULL) 3376 { 3377 // Traverse the arguments but not the function. 3378 Expression_list* args = ce->args(); 3379 if (args != NULL) 3380 { 3381 if (args->traverse(this) == TRAVERSE_EXIT) 3382 return TRAVERSE_EXIT; 3383 } 3384 3385 // Traverse the subexpressions of the function, if any. 3386 if (fn->traverse_subexpressions(this) == TRAVERSE_EXIT) 3387 return TRAVERSE_EXIT; 3388 3389 return TRAVERSE_SKIP_COMPONENTS; 3390 } 3391 } 3392 3393 return TRAVERSE_CONTINUE; 3394 } 3395 3396 // Create function descriptors as needed. We need a function 3397 // descriptor for all exported functions and for all functions that 3398 // are referenced without being called. 3399 3400 void 3401 Gogo::create_function_descriptors() 3402 { 3403 // Create a function descriptor for any exported function that is 3404 // declared in this package. This is so that we have a descriptor 3405 // for functions written in assembly. Gather the descriptors first 3406 // so that we don't add declarations while looping over them. 3407 std::vector<Named_object*> fndecls; 3408 Bindings* b = this->package_->bindings(); 3409 for (Bindings::const_declarations_iterator p = b->begin_declarations(); 3410 p != b->end_declarations(); 3411 ++p) 3412 { 3413 Named_object* no = p->second; 3414 if (no->is_function_declaration() 3415 && !no->func_declaration_value()->type()->is_method() 3416 && !Linemap::is_predeclared_location(no->location()) 3417 && !Gogo::is_hidden_name(no->name())) 3418 fndecls.push_back(no); 3419 } 3420 for (std::vector<Named_object*>::const_iterator p = fndecls.begin(); 3421 p != fndecls.end(); 3422 ++p) 3423 (*p)->func_declaration_value()->descriptor(this, *p); 3424 fndecls.clear(); 3425 3426 Create_function_descriptors cfd(this); 3427 this->traverse(&cfd); 3428 } 3429 3430 // Finalize the methods of an interface type. 3431 3432 int 3433 Finalize_methods::type(Type* t) 3434 { 3435 // Check the classification so that we don't finalize the methods 3436 // twice for a named interface type. 3437 switch (t->classification()) 3438 { 3439 case Type::TYPE_INTERFACE: 3440 t->interface_type()->finalize_methods(); 3441 break; 3442 3443 case Type::TYPE_NAMED: 3444 { 3445 Named_type* nt = t->named_type(); 3446 3447 if (nt->is_alias()) 3448 return TRAVERSE_CONTINUE; 3449 3450 Type* rt = nt->real_type(); 3451 if (rt->classification() != Type::TYPE_STRUCT) 3452 { 3453 // Finalize the methods of the real type first. 3454 if (Type::traverse(rt, this) == TRAVERSE_EXIT) 3455 return TRAVERSE_EXIT; 3456 3457 // Finalize the methods of this type. 3458 nt->finalize_methods(this->gogo_); 3459 } 3460 else 3461 { 3462 // We don't want to finalize the methods of a named struct 3463 // type, as the methods should be attached to the named 3464 // type, not the struct type. We just want to finalize 3465 // the field types. 3466 // 3467 // It is possible that a field type refers indirectly to 3468 // this type, such as via a field with function type with 3469 // an argument or result whose type is this type. To 3470 // avoid the cycle, first finalize the methods of any 3471 // embedded types, which are the only types we need to 3472 // know to finalize the methods of this type. 3473 const Struct_field_list* fields = rt->struct_type()->fields(); 3474 if (fields != NULL) 3475 { 3476 for (Struct_field_list::const_iterator pf = fields->begin(); 3477 pf != fields->end(); 3478 ++pf) 3479 { 3480 if (pf->is_anonymous()) 3481 { 3482 if (Type::traverse(pf->type(), this) == TRAVERSE_EXIT) 3483 return TRAVERSE_EXIT; 3484 } 3485 } 3486 } 3487 3488 // Finalize the methods of this type. 3489 nt->finalize_methods(this->gogo_); 3490 3491 // Finalize all the struct fields. 3492 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT) 3493 return TRAVERSE_EXIT; 3494 } 3495 3496 // If this type is defined in a different package, then finalize the 3497 // types of all the methods, since we won't see them otherwise. 3498 if (nt->named_object()->package() != NULL && nt->has_any_methods()) 3499 { 3500 const Methods* methods = nt->methods(); 3501 for (Methods::const_iterator p = methods->begin(); 3502 p != methods->end(); 3503 ++p) 3504 { 3505 if (Type::traverse(p->second->type(), this) == TRAVERSE_EXIT) 3506 return TRAVERSE_EXIT; 3507 } 3508 } 3509 3510 // Finalize the types of all methods that are declared but not 3511 // defined, since we won't see the declarations otherwise. 3512 if (nt->named_object()->package() == NULL 3513 && nt->local_methods() != NULL) 3514 { 3515 const Bindings* methods = nt->local_methods(); 3516 for (Bindings::const_declarations_iterator p = 3517 methods->begin_declarations(); 3518 p != methods->end_declarations(); 3519 p++) 3520 { 3521 if (p->second->is_function_declaration()) 3522 { 3523 Type* mt = p->second->func_declaration_value()->type(); 3524 if (Type::traverse(mt, this) == TRAVERSE_EXIT) 3525 return TRAVERSE_EXIT; 3526 } 3527 } 3528 } 3529 3530 return TRAVERSE_SKIP_COMPONENTS; 3531 } 3532 3533 case Type::TYPE_STRUCT: 3534 // Traverse the field types first in case there is an embedded 3535 // field with methods that the struct should inherit. 3536 if (t->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT) 3537 return TRAVERSE_EXIT; 3538 t->struct_type()->finalize_methods(this->gogo_); 3539 return TRAVERSE_SKIP_COMPONENTS; 3540 3541 default: 3542 break; 3543 } 3544 3545 return TRAVERSE_CONTINUE; 3546 } 3547 3548 // Finalize method lists and build stub methods for types. 3549 3550 void 3551 Gogo::finalize_methods() 3552 { 3553 Finalize_methods finalize(this); 3554 this->traverse(&finalize); 3555 } 3556 3557 // Finalize the method list for a type. This is called when a type is 3558 // parsed for an inlined function body, which happens after the 3559 // finalize_methods pass. 3560 3561 void 3562 Gogo::finalize_methods_for_type(Type* type) 3563 { 3564 Finalize_methods finalize(this); 3565 Type::traverse(type, &finalize); 3566 } 3567 3568 // Set types for unspecified variables and constants. 3569 3570 void 3571 Gogo::determine_types() 3572 { 3573 Bindings* bindings = this->current_bindings(); 3574 for (Bindings::const_definitions_iterator p = bindings->begin_definitions(); 3575 p != bindings->end_definitions(); 3576 ++p) 3577 { 3578 if ((*p)->is_function()) 3579 (*p)->func_value()->determine_types(); 3580 else if ((*p)->is_variable()) 3581 (*p)->var_value()->determine_type(); 3582 else if ((*p)->is_const()) 3583 (*p)->const_value()->determine_type(); 3584 3585 // See if a variable requires us to build an initialization 3586 // function. We know that we will see all global variables 3587 // here. 3588 if (!this->need_init_fn_ && (*p)->is_variable()) 3589 { 3590 Variable* variable = (*p)->var_value(); 3591 3592 // If this is a global variable which requires runtime 3593 // initialization, we need an initialization function. 3594 if (!variable->is_global()) 3595 ; 3596 else if (variable->init() == NULL) 3597 ; 3598 else if (variable->type()->interface_type() != NULL) 3599 this->need_init_fn_ = true; 3600 else if (variable->init()->is_constant()) 3601 ; 3602 else if (!variable->init()->is_composite_literal()) 3603 this->need_init_fn_ = true; 3604 else if (variable->init()->is_nonconstant_composite_literal()) 3605 this->need_init_fn_ = true; 3606 3607 // If this is a global variable which holds a pointer value, 3608 // then we need an initialization function to register it as a 3609 // GC root. 3610 if (variable->is_global() && variable->type()->has_pointer()) 3611 this->need_init_fn_ = true; 3612 } 3613 } 3614 3615 // Determine the types of constants in packages. 3616 for (Packages::const_iterator p = this->packages_.begin(); 3617 p != this->packages_.end(); 3618 ++p) 3619 p->second->determine_types(); 3620 } 3621 3622 // Traversal class used for type checking. 3623 3624 class Check_types_traverse : public Traverse 3625 { 3626 public: 3627 Check_types_traverse(Gogo* gogo) 3628 : Traverse(traverse_variables 3629 | traverse_constants 3630 | traverse_functions 3631 | traverse_statements 3632 | traverse_expressions), 3633 gogo_(gogo) 3634 { } 3635 3636 int 3637 variable(Named_object*); 3638 3639 int 3640 constant(Named_object*, bool); 3641 3642 int 3643 function(Named_object*); 3644 3645 int 3646 statement(Block*, size_t* pindex, Statement*); 3647 3648 int 3649 expression(Expression**); 3650 3651 private: 3652 // General IR. 3653 Gogo* gogo_; 3654 }; 3655 3656 // Check that a variable initializer has the right type. 3657 3658 int 3659 Check_types_traverse::variable(Named_object* named_object) 3660 { 3661 if (named_object->is_variable()) 3662 { 3663 Variable* var = named_object->var_value(); 3664 3665 // Give error if variable type is not defined. 3666 var->type()->base(); 3667 3668 Expression* init = var->init(); 3669 std::string reason; 3670 if (init != NULL 3671 && !Type::are_assignable(var->type(), init->type(), &reason)) 3672 { 3673 if (reason.empty()) 3674 go_error_at(var->location(), "incompatible type in initialization"); 3675 else 3676 go_error_at(var->location(), 3677 "incompatible type in initialization (%s)", 3678 reason.c_str()); 3679 init = Expression::make_error(named_object->location()); 3680 var->clear_init(); 3681 } 3682 else if (init != NULL 3683 && init->func_expression() != NULL) 3684 { 3685 Named_object* no = init->func_expression()->named_object(); 3686 Function_type* fntype; 3687 if (no->is_function()) 3688 fntype = no->func_value()->type(); 3689 else if (no->is_function_declaration()) 3690 fntype = no->func_declaration_value()->type(); 3691 else 3692 go_unreachable(); 3693 3694 // Builtin functions cannot be used as function values for variable 3695 // initialization. 3696 if (fntype->is_builtin()) 3697 { 3698 go_error_at(init->location(), 3699 "invalid use of special built-in function %qs; " 3700 "must be called", 3701 no->message_name().c_str()); 3702 } 3703 } 3704 if (!var->is_used() 3705 && !var->is_global() 3706 && !var->is_parameter() 3707 && !var->is_receiver() 3708 && !var->type()->is_error() 3709 && (init == NULL || !init->is_error_expression()) 3710 && !Lex::is_invalid_identifier(named_object->name())) 3711 go_error_at(var->location(), "%qs declared but not used", 3712 named_object->message_name().c_str()); 3713 } 3714 return TRAVERSE_CONTINUE; 3715 } 3716 3717 // Check that a constant initializer has the right type. 3718 3719 int 3720 Check_types_traverse::constant(Named_object* named_object, bool) 3721 { 3722 Named_constant* constant = named_object->const_value(); 3723 Type* ctype = constant->type(); 3724 if (ctype->integer_type() == NULL 3725 && ctype->float_type() == NULL 3726 && ctype->complex_type() == NULL 3727 && !ctype->is_boolean_type() 3728 && !ctype->is_string_type()) 3729 { 3730 if (ctype->is_nil_type()) 3731 go_error_at(constant->location(), "const initializer cannot be nil"); 3732 else if (!ctype->is_error()) 3733 go_error_at(constant->location(), "invalid constant type"); 3734 constant->set_error(); 3735 } 3736 else if (!constant->expr()->is_constant()) 3737 { 3738 go_error_at(constant->expr()->location(), "expression is not constant"); 3739 constant->set_error(); 3740 } 3741 else if (!Type::are_assignable(constant->type(), constant->expr()->type(), 3742 NULL)) 3743 { 3744 go_error_at(constant->location(), 3745 "initialization expression has wrong type"); 3746 constant->set_error(); 3747 } 3748 return TRAVERSE_CONTINUE; 3749 } 3750 3751 // There are no types to check in a function, but this is where we 3752 // issue warnings about labels which are defined but not referenced. 3753 3754 int 3755 Check_types_traverse::function(Named_object* no) 3756 { 3757 no->func_value()->check_labels(); 3758 return TRAVERSE_CONTINUE; 3759 } 3760 3761 // Check that types are valid in a statement. 3762 3763 int 3764 Check_types_traverse::statement(Block*, size_t*, Statement* s) 3765 { 3766 s->check_types(this->gogo_); 3767 return TRAVERSE_CONTINUE; 3768 } 3769 3770 // Check that types are valid in an expression. 3771 3772 int 3773 Check_types_traverse::expression(Expression** expr) 3774 { 3775 (*expr)->check_types(this->gogo_); 3776 return TRAVERSE_CONTINUE; 3777 } 3778 3779 // Check that types are valid. 3780 3781 void 3782 Gogo::check_types() 3783 { 3784 Check_types_traverse traverse(this); 3785 this->traverse(&traverse); 3786 3787 Bindings* bindings = this->current_bindings(); 3788 for (Bindings::const_declarations_iterator p = bindings->begin_declarations(); 3789 p != bindings->end_declarations(); 3790 ++p) 3791 { 3792 // Also check the types in a function declaration's signature. 3793 Named_object* no = p->second; 3794 if (no->is_function_declaration()) 3795 no->func_declaration_value()->check_types(); 3796 } 3797 } 3798 3799 // Check the types in a single block. 3800 3801 void 3802 Gogo::check_types_in_block(Block* block) 3803 { 3804 Check_types_traverse traverse(this); 3805 block->traverse(&traverse); 3806 } 3807 3808 // For each global variable defined in the current package, record the 3809 // set of variables that its initializer depends on. We do this after 3810 // lowering so that all unknown names are resolved to their final 3811 // locations. We do this before write barrier insertion because that 3812 // makes it harder to distinguish references from assignments in 3813 // preinit blocks. 3814 3815 void 3816 Gogo::record_global_init_refs() 3817 { 3818 Bindings* bindings = this->package_->bindings(); 3819 for (Bindings::const_definitions_iterator pb = bindings->begin_definitions(); 3820 pb != bindings->end_definitions(); 3821 pb++) 3822 { 3823 Named_object* no = *pb; 3824 if (!no->is_variable()) 3825 continue; 3826 3827 Variable* var = no->var_value(); 3828 go_assert(var->is_global()); 3829 3830 Find_vars find_vars; 3831 Expression* init = var->init(); 3832 if (init != NULL) 3833 Expression::traverse(&init, &find_vars); 3834 if (var->has_pre_init()) 3835 var->preinit()->traverse(&find_vars); 3836 Named_object* dep = this->var_depends_on(var); 3837 if (dep != NULL) 3838 { 3839 Expression* dinit = dep->var_value()->init(); 3840 if (dinit != NULL) 3841 Expression::traverse(&dinit, &find_vars); 3842 if (dep->var_value()->has_pre_init()) 3843 dep->var_value()->preinit()->traverse(&find_vars); 3844 } 3845 3846 for (Find_vars::const_iterator pv = find_vars.begin(); 3847 pv != find_vars.end(); 3848 ++pv) 3849 var->add_init_ref(*pv); 3850 } 3851 } 3852 3853 // A traversal class which finds all the expressions which must be 3854 // evaluated in order within a statement or larger expression. This 3855 // is used to implement the rules about order of evaluation. 3856 3857 class Find_eval_ordering : public Traverse 3858 { 3859 private: 3860 typedef std::vector<Expression**> Expression_pointers; 3861 3862 public: 3863 Find_eval_ordering() 3864 : Traverse(traverse_blocks 3865 | traverse_statements 3866 | traverse_expressions), 3867 exprs_() 3868 { } 3869 3870 size_t 3871 size() const 3872 { return this->exprs_.size(); } 3873 3874 typedef Expression_pointers::const_iterator const_iterator; 3875 3876 const_iterator 3877 begin() const 3878 { return this->exprs_.begin(); } 3879 3880 const_iterator 3881 end() const 3882 { return this->exprs_.end(); } 3883 3884 protected: 3885 int 3886 block(Block*) 3887 { return TRAVERSE_SKIP_COMPONENTS; } 3888 3889 int 3890 statement(Block*, size_t*, Statement*) 3891 { return TRAVERSE_SKIP_COMPONENTS; } 3892 3893 int 3894 expression(Expression**); 3895 3896 private: 3897 // A list of pointers to expressions with side-effects. 3898 Expression_pointers exprs_; 3899 }; 3900 3901 // If an expression must be evaluated in order, put it on the list. 3902 3903 int 3904 Find_eval_ordering::expression(Expression** expression_pointer) 3905 { 3906 Binary_expression* binexp = (*expression_pointer)->binary_expression(); 3907 if (binexp != NULL 3908 && (binexp->op() == OPERATOR_ANDAND || binexp->op() == OPERATOR_OROR)) 3909 { 3910 // Shortcut expressions may potentially have side effects which need 3911 // to be ordered, so add them to the list. 3912 // We don't order its subexpressions here since they may be evaluated 3913 // conditionally. This is handled in remove_shortcuts. 3914 this->exprs_.push_back(expression_pointer); 3915 return TRAVERSE_SKIP_COMPONENTS; 3916 } 3917 3918 // We have to look at subexpressions before this one. 3919 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT) 3920 return TRAVERSE_EXIT; 3921 if ((*expression_pointer)->must_eval_in_order()) 3922 this->exprs_.push_back(expression_pointer); 3923 return TRAVERSE_SKIP_COMPONENTS; 3924 } 3925 3926 // A traversal class for ordering evaluations. 3927 3928 class Order_eval : public Traverse 3929 { 3930 public: 3931 Order_eval(Gogo* gogo) 3932 : Traverse(traverse_variables 3933 | traverse_statements), 3934 gogo_(gogo) 3935 { } 3936 3937 int 3938 variable(Named_object*); 3939 3940 int 3941 statement(Block*, size_t*, Statement*); 3942 3943 private: 3944 // The IR. 3945 Gogo* gogo_; 3946 }; 3947 3948 // Implement the order of evaluation rules for a statement. 3949 3950 int 3951 Order_eval::statement(Block* block, size_t* pindex, Statement* stmt) 3952 { 3953 // FIXME: This approach doesn't work for switch statements, because 3954 // we add the new statements before the whole switch when we need to 3955 // instead add them just before the switch expression. The right 3956 // fix is probably to lower switch statements with nonconstant cases 3957 // to a series of conditionals. 3958 if (stmt->switch_statement() != NULL) 3959 return TRAVERSE_CONTINUE; 3960 3961 Find_eval_ordering find_eval_ordering; 3962 3963 // If S is a variable declaration, then ordinary traversal won't do 3964 // anything. We want to explicitly traverse the initialization 3965 // expression if there is one. 3966 Variable_declaration_statement* vds = stmt->variable_declaration_statement(); 3967 Expression* init = NULL; 3968 Expression* orig_init = NULL; 3969 if (vds == NULL) 3970 stmt->traverse_contents(&find_eval_ordering); 3971 else 3972 { 3973 init = vds->var()->var_value()->init(); 3974 if (init == NULL) 3975 return TRAVERSE_CONTINUE; 3976 orig_init = init; 3977 3978 // It might seem that this could be 3979 // init->traverse_subexpressions. Unfortunately that can fail 3980 // in a case like 3981 // var err os.Error 3982 // newvar, err := call(arg()) 3983 // Here newvar will have an init of call result 0 of 3984 // call(arg()). If we only traverse subexpressions, we will 3985 // only find arg(), and we won't bother to move anything out. 3986 // Then we get to the assignment to err, we will traverse the 3987 // whole statement, and this time we will find both call() and 3988 // arg(), and so we will move them out. This will cause them to 3989 // be put into temporary variables before the assignment to err 3990 // but after the declaration of newvar. To avoid that problem, 3991 // we traverse the entire expression here. 3992 Expression::traverse(&init, &find_eval_ordering); 3993 } 3994 3995 size_t c = find_eval_ordering.size(); 3996 if (c == 0) 3997 return TRAVERSE_CONTINUE; 3998 3999 // If there is only one expression with a side-effect, we can 4000 // usually leave it in place. 4001 if (c == 1) 4002 { 4003 switch (stmt->classification()) 4004 { 4005 case Statement::STATEMENT_ASSIGNMENT: 4006 // For an assignment statement, we need to evaluate an 4007 // expression on the right hand side before we evaluate any 4008 // index expression on the left hand side, so for that case 4009 // we always move the expression. Otherwise we mishandle 4010 // m[0] = len(m) where m is a map. 4011 break; 4012 4013 case Statement::STATEMENT_EXPRESSION: 4014 { 4015 // If this is a call statement that doesn't return any 4016 // values, it will not have been counted as a value to 4017 // move. We need to move any subexpressions in case they 4018 // are themselves call statements that require passing a 4019 // closure. 4020 Expression* expr = stmt->expression_statement()->expr(); 4021 if (expr->call_expression() != NULL 4022 && expr->call_expression()->result_count() == 0) 4023 break; 4024 return TRAVERSE_CONTINUE; 4025 } 4026 4027 default: 4028 // We can leave the expression in place. 4029 return TRAVERSE_CONTINUE; 4030 } 4031 } 4032 4033 bool is_thunk = stmt->thunk_statement() != NULL; 4034 Expression_statement* es = stmt->expression_statement(); 4035 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin(); 4036 p != find_eval_ordering.end(); 4037 ++p) 4038 { 4039 Expression** pexpr = *p; 4040 4041 // The last expression in a thunk will be the call passed to go 4042 // or defer, which we must not evaluate early. 4043 if (is_thunk && p + 1 == find_eval_ordering.end()) 4044 break; 4045 4046 Location loc = (*pexpr)->location(); 4047 Statement* s; 4048 if ((*pexpr)->call_expression() == NULL 4049 || (*pexpr)->call_expression()->result_count() < 2) 4050 { 4051 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, 4052 loc); 4053 s = ts; 4054 *pexpr = Expression::make_temporary_reference(ts, loc); 4055 } 4056 else 4057 { 4058 // A call expression which returns multiple results needs to 4059 // be handled specially. We can't create a temporary 4060 // because there is no type to give it. Any actual uses of 4061 // the values will be done via Call_result_expressions. 4062 // 4063 // Since a given call expression can be shared by multiple 4064 // Call_result_expressions, avoid hoisting the call the 4065 // second time we see it here. In addition, don't try to 4066 // hoist the top-level multi-return call in the statement, 4067 // since doing this would result a tree with more than one copy 4068 // of the call. 4069 if (this->remember_expression(*pexpr)) 4070 s = NULL; 4071 else if (es != NULL && *pexpr == es->expr()) 4072 s = NULL; 4073 else 4074 s = Statement::make_statement(*pexpr, true); 4075 } 4076 4077 if (s != NULL) 4078 { 4079 block->insert_statement_before(*pindex, s); 4080 ++*pindex; 4081 } 4082 } 4083 4084 if (init != orig_init) 4085 vds->var()->var_value()->set_init(init); 4086 4087 return TRAVERSE_CONTINUE; 4088 } 4089 4090 // Implement the order of evaluation rules for the initializer of a 4091 // global variable. 4092 4093 int 4094 Order_eval::variable(Named_object* no) 4095 { 4096 if (no->is_result_variable()) 4097 return TRAVERSE_CONTINUE; 4098 Variable* var = no->var_value(); 4099 Expression* init = var->init(); 4100 if (!var->is_global() || init == NULL) 4101 return TRAVERSE_CONTINUE; 4102 4103 Find_eval_ordering find_eval_ordering; 4104 Expression::traverse(&init, &find_eval_ordering); 4105 4106 if (find_eval_ordering.size() <= 1) 4107 { 4108 // If there is only one expression with a side-effect, we can 4109 // leave it in place. 4110 return TRAVERSE_SKIP_COMPONENTS; 4111 } 4112 4113 Expression* orig_init = init; 4114 4115 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin(); 4116 p != find_eval_ordering.end(); 4117 ++p) 4118 { 4119 Expression** pexpr = *p; 4120 Location loc = (*pexpr)->location(); 4121 Statement* s; 4122 if ((*pexpr)->call_expression() == NULL 4123 || (*pexpr)->call_expression()->result_count() < 2) 4124 { 4125 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, 4126 loc); 4127 s = ts; 4128 *pexpr = Expression::make_temporary_reference(ts, loc); 4129 } 4130 else 4131 { 4132 // A call expression which returns multiple results needs to 4133 // be handled specially. 4134 s = Statement::make_statement(*pexpr, true); 4135 } 4136 var->add_preinit_statement(this->gogo_, s); 4137 } 4138 4139 if (init != orig_init) 4140 var->set_init(init); 4141 4142 return TRAVERSE_SKIP_COMPONENTS; 4143 } 4144 4145 // Use temporary variables to implement the order of evaluation rules. 4146 4147 void 4148 Gogo::order_evaluations() 4149 { 4150 Order_eval order_eval(this); 4151 this->traverse(&order_eval); 4152 } 4153 4154 // Order evaluations in a block. 4155 4156 void 4157 Gogo::order_block(Block* block) 4158 { 4159 Order_eval order_eval(this); 4160 block->traverse(&order_eval); 4161 } 4162 4163 // A traversal class used to find a single shortcut operator within an 4164 // expression. 4165 4166 class Find_shortcut : public Traverse 4167 { 4168 public: 4169 Find_shortcut() 4170 : Traverse(traverse_blocks 4171 | traverse_statements 4172 | traverse_expressions), 4173 found_(NULL) 4174 { } 4175 4176 // A pointer to the expression which was found, or NULL if none was 4177 // found. 4178 Expression** 4179 found() const 4180 { return this->found_; } 4181 4182 protected: 4183 int 4184 block(Block*) 4185 { return TRAVERSE_SKIP_COMPONENTS; } 4186 4187 int 4188 statement(Block*, size_t*, Statement*) 4189 { return TRAVERSE_SKIP_COMPONENTS; } 4190 4191 int 4192 expression(Expression**); 4193 4194 private: 4195 Expression** found_; 4196 }; 4197 4198 // Find a shortcut expression. 4199 4200 int 4201 Find_shortcut::expression(Expression** pexpr) 4202 { 4203 Expression* expr = *pexpr; 4204 Binary_expression* be = expr->binary_expression(); 4205 if (be == NULL) 4206 return TRAVERSE_CONTINUE; 4207 Operator op = be->op(); 4208 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND) 4209 return TRAVERSE_CONTINUE; 4210 go_assert(this->found_ == NULL); 4211 this->found_ = pexpr; 4212 return TRAVERSE_EXIT; 4213 } 4214 4215 // A traversal class used to turn shortcut operators into explicit if 4216 // statements. 4217 4218 class Shortcuts : public Traverse 4219 { 4220 public: 4221 Shortcuts(Gogo* gogo) 4222 : Traverse(traverse_variables 4223 | traverse_statements), 4224 gogo_(gogo) 4225 { } 4226 4227 protected: 4228 int 4229 variable(Named_object*); 4230 4231 int 4232 statement(Block*, size_t*, Statement*); 4233 4234 private: 4235 // Convert a shortcut operator. 4236 Statement* 4237 convert_shortcut(Block* enclosing, Expression** pshortcut); 4238 4239 // The IR. 4240 Gogo* gogo_; 4241 }; 4242 4243 // Remove shortcut operators in a single statement. 4244 4245 int 4246 Shortcuts::statement(Block* block, size_t* pindex, Statement* s) 4247 { 4248 // FIXME: This approach doesn't work for switch statements, because 4249 // we add the new statements before the whole switch when we need to 4250 // instead add them just before the switch expression. The right 4251 // fix is probably to lower switch statements with nonconstant cases 4252 // to a series of conditionals. 4253 if (s->switch_statement() != NULL) 4254 return TRAVERSE_CONTINUE; 4255 4256 while (true) 4257 { 4258 Find_shortcut find_shortcut; 4259 4260 // If S is a variable declaration, then ordinary traversal won't 4261 // do anything. We want to explicitly traverse the 4262 // initialization expression if there is one. 4263 Variable_declaration_statement* vds = s->variable_declaration_statement(); 4264 Expression* init = NULL; 4265 if (vds == NULL) 4266 s->traverse_contents(&find_shortcut); 4267 else 4268 { 4269 init = vds->var()->var_value()->init(); 4270 if (init == NULL) 4271 return TRAVERSE_CONTINUE; 4272 init->traverse(&init, &find_shortcut); 4273 } 4274 Expression** pshortcut = find_shortcut.found(); 4275 if (pshortcut == NULL) 4276 return TRAVERSE_CONTINUE; 4277 4278 Statement* snew = this->convert_shortcut(block, pshortcut); 4279 block->insert_statement_before(*pindex, snew); 4280 ++*pindex; 4281 4282 if (pshortcut == &init) 4283 vds->var()->var_value()->set_init(init); 4284 } 4285 } 4286 4287 // Remove shortcut operators in the initializer of a global variable. 4288 4289 int 4290 Shortcuts::variable(Named_object* no) 4291 { 4292 if (no->is_result_variable()) 4293 return TRAVERSE_CONTINUE; 4294 Variable* var = no->var_value(); 4295 Expression* init = var->init(); 4296 if (!var->is_global() || init == NULL) 4297 return TRAVERSE_CONTINUE; 4298 4299 while (true) 4300 { 4301 Find_shortcut find_shortcut; 4302 init->traverse(&init, &find_shortcut); 4303 Expression** pshortcut = find_shortcut.found(); 4304 if (pshortcut == NULL) 4305 return TRAVERSE_CONTINUE; 4306 4307 Statement* snew = this->convert_shortcut(NULL, pshortcut); 4308 var->add_preinit_statement(this->gogo_, snew); 4309 if (pshortcut == &init) 4310 var->set_init(init); 4311 } 4312 } 4313 4314 // Given an expression which uses a shortcut operator, return a 4315 // statement which implements it, and update *PSHORTCUT accordingly. 4316 4317 Statement* 4318 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut) 4319 { 4320 Binary_expression* shortcut = (*pshortcut)->binary_expression(); 4321 Expression* left = shortcut->left(); 4322 Expression* right = shortcut->right(); 4323 Location loc = shortcut->location(); 4324 4325 Block* retblock = new Block(enclosing, loc); 4326 retblock->set_end_location(loc); 4327 4328 Temporary_statement* ts = Statement::make_temporary(shortcut->type(), 4329 left, loc); 4330 retblock->add_statement(ts); 4331 4332 Block* block = new Block(retblock, loc); 4333 block->set_end_location(loc); 4334 Expression* tmpref = Expression::make_temporary_reference(ts, loc); 4335 Statement* assign = Statement::make_assignment(tmpref, right, loc); 4336 block->add_statement(assign); 4337 4338 Expression* cond = Expression::make_temporary_reference(ts, loc); 4339 if (shortcut->binary_expression()->op() == OPERATOR_OROR) 4340 cond = Expression::make_unary(OPERATOR_NOT, cond, loc); 4341 4342 Statement* if_statement = Statement::make_if_statement(cond, block, NULL, 4343 loc); 4344 retblock->add_statement(if_statement); 4345 4346 *pshortcut = Expression::make_temporary_reference(ts, loc); 4347 4348 delete shortcut; 4349 4350 // Now convert any shortcut operators in LEFT and RIGHT. 4351 // LEFT and RIGHT were skipped in the top level 4352 // Gogo::order_evaluations. We need to order their 4353 // components first. 4354 Order_eval order_eval(this->gogo_); 4355 retblock->traverse(&order_eval); 4356 Shortcuts shortcuts(this->gogo_); 4357 retblock->traverse(&shortcuts); 4358 4359 return Statement::make_block_statement(retblock, loc); 4360 } 4361 4362 // Turn shortcut operators into explicit if statements. Doing this 4363 // considerably simplifies the order of evaluation rules. 4364 4365 void 4366 Gogo::remove_shortcuts() 4367 { 4368 Shortcuts shortcuts(this); 4369 this->traverse(&shortcuts); 4370 } 4371 4372 // Turn shortcut operators into explicit if statements in a block. 4373 4374 void 4375 Gogo::remove_shortcuts_in_block(Block* block) 4376 { 4377 Shortcuts shortcuts(this); 4378 block->traverse(&shortcuts); 4379 } 4380 4381 // Traversal to flatten parse tree after order of evaluation rules are applied. 4382 4383 class Flatten : public Traverse 4384 { 4385 public: 4386 Flatten(Gogo* gogo, Named_object* function) 4387 : Traverse(traverse_variables 4388 | traverse_functions 4389 | traverse_statements 4390 | traverse_expressions), 4391 gogo_(gogo), function_(function), inserter_() 4392 { } 4393 4394 void 4395 set_inserter(const Statement_inserter* inserter) 4396 { this->inserter_ = *inserter; } 4397 4398 int 4399 variable(Named_object*); 4400 4401 int 4402 function(Named_object*); 4403 4404 int 4405 statement(Block*, size_t* pindex, Statement*); 4406 4407 int 4408 expression(Expression**); 4409 4410 private: 4411 // General IR. 4412 Gogo* gogo_; 4413 // The function we are traversing. 4414 Named_object* function_; 4415 // Current statement inserter for use by expressions. 4416 Statement_inserter inserter_; 4417 }; 4418 4419 // Flatten variables. 4420 4421 int 4422 Flatten::variable(Named_object* no) 4423 { 4424 if (!no->is_variable()) 4425 return TRAVERSE_CONTINUE; 4426 4427 if (no->is_variable() && no->var_value()->is_global()) 4428 { 4429 // Global variables can have loops in their initialization 4430 // expressions. This is handled in flatten_init_expression. 4431 no->var_value()->flatten_init_expression(this->gogo_, this->function_, 4432 &this->inserter_); 4433 return TRAVERSE_CONTINUE; 4434 } 4435 4436 if (!no->var_value()->is_parameter() 4437 && !no->var_value()->is_receiver() 4438 && !no->var_value()->is_closure() 4439 && no->var_value()->is_non_escaping_address_taken() 4440 && !no->var_value()->is_in_heap() 4441 && no->var_value()->toplevel_decl() == NULL) 4442 { 4443 // Local variable that has address taken but not escape. 4444 // It needs to be live beyond its lexical scope. So we 4445 // create a top-level declaration for it. 4446 // No need to do it if it is already in the top level. 4447 Block* top_block = function_->func_value()->block(); 4448 if (top_block->bindings()->lookup_local(no->name()) != no) 4449 { 4450 Variable* var = no->var_value(); 4451 Temporary_statement* ts = 4452 Statement::make_temporary(var->type(), NULL, var->location()); 4453 ts->set_is_address_taken(); 4454 top_block->add_statement_at_front(ts); 4455 var->set_toplevel_decl(ts); 4456 } 4457 } 4458 4459 go_assert(!no->var_value()->has_pre_init()); 4460 4461 return TRAVERSE_SKIP_COMPONENTS; 4462 } 4463 4464 // Flatten the body of a function. Record the function while flattening it, 4465 // so that we can pass it down when flattening an expression. 4466 4467 int 4468 Flatten::function(Named_object* no) 4469 { 4470 go_assert(this->function_ == NULL); 4471 this->function_ = no; 4472 int t = no->func_value()->traverse(this); 4473 this->function_ = NULL; 4474 4475 if (t == TRAVERSE_EXIT) 4476 return t; 4477 return TRAVERSE_SKIP_COMPONENTS; 4478 } 4479 4480 // Flatten statement parse trees. 4481 4482 int 4483 Flatten::statement(Block* block, size_t* pindex, Statement* sorig) 4484 { 4485 // Because we explicitly traverse the statement's contents 4486 // ourselves, we want to skip block statements here. There is 4487 // nothing to flatten in a block statement. 4488 if (sorig->is_block_statement()) 4489 return TRAVERSE_CONTINUE; 4490 4491 Statement_inserter hold_inserter(this->inserter_); 4492 this->inserter_ = Statement_inserter(block, pindex); 4493 4494 // Flatten the expressions first. 4495 int t = sorig->traverse_contents(this); 4496 if (t == TRAVERSE_EXIT) 4497 { 4498 this->inserter_ = hold_inserter; 4499 return t; 4500 } 4501 4502 // Keep flattening until nothing changes. 4503 Statement* s = sorig; 4504 while (true) 4505 { 4506 Statement* snew = s->flatten(this->gogo_, this->function_, block, 4507 &this->inserter_); 4508 if (snew == s) 4509 break; 4510 s = snew; 4511 t = s->traverse_contents(this); 4512 if (t == TRAVERSE_EXIT) 4513 { 4514 this->inserter_ = hold_inserter; 4515 return t; 4516 } 4517 } 4518 4519 if (s != sorig) 4520 block->replace_statement(*pindex, s); 4521 4522 this->inserter_ = hold_inserter; 4523 return TRAVERSE_SKIP_COMPONENTS; 4524 } 4525 4526 // Flatten expression parse trees. 4527 4528 int 4529 Flatten::expression(Expression** pexpr) 4530 { 4531 // Keep flattening until nothing changes. 4532 while (true) 4533 { 4534 Expression* e = *pexpr; 4535 if (e->traverse_subexpressions(this) == TRAVERSE_EXIT) 4536 return TRAVERSE_EXIT; 4537 4538 Expression* enew = e->flatten(this->gogo_, this->function_, 4539 &this->inserter_); 4540 if (enew == e) 4541 break; 4542 *pexpr = enew; 4543 } 4544 return TRAVERSE_SKIP_COMPONENTS; 4545 } 4546 4547 // Flatten a block. 4548 4549 void 4550 Gogo::flatten_block(Named_object* function, Block* block) 4551 { 4552 Flatten flatten(this, function); 4553 block->traverse(&flatten); 4554 } 4555 4556 // Flatten an expression. INSERTER may be NULL, in which case the 4557 // expression had better not need to create any temporaries. 4558 4559 void 4560 Gogo::flatten_expression(Named_object* function, Statement_inserter* inserter, 4561 Expression** pexpr) 4562 { 4563 Flatten flatten(this, function); 4564 if (inserter != NULL) 4565 flatten.set_inserter(inserter); 4566 flatten.expression(pexpr); 4567 } 4568 4569 void 4570 Gogo::flatten() 4571 { 4572 Flatten flatten(this, NULL); 4573 this->traverse(&flatten); 4574 } 4575 4576 // Traversal to convert calls to the predeclared recover function to 4577 // pass in an argument indicating whether it can recover from a panic 4578 // or not. 4579 4580 class Convert_recover : public Traverse 4581 { 4582 public: 4583 Convert_recover(Named_object* arg) 4584 : Traverse(traverse_expressions), 4585 arg_(arg) 4586 { } 4587 4588 protected: 4589 int 4590 expression(Expression**); 4591 4592 private: 4593 // The argument to pass to the function. 4594 Named_object* arg_; 4595 }; 4596 4597 // Convert calls to recover. 4598 4599 int 4600 Convert_recover::expression(Expression** pp) 4601 { 4602 Call_expression* ce = (*pp)->call_expression(); 4603 if (ce != NULL && ce->is_recover_call()) 4604 ce->set_recover_arg(Expression::make_var_reference(this->arg_, 4605 ce->location())); 4606 return TRAVERSE_CONTINUE; 4607 } 4608 4609 // Traversal for build_recover_thunks. 4610 4611 class Build_recover_thunks : public Traverse 4612 { 4613 public: 4614 Build_recover_thunks(Gogo* gogo) 4615 : Traverse(traverse_functions), 4616 gogo_(gogo) 4617 { } 4618 4619 int 4620 function(Named_object*); 4621 4622 private: 4623 Expression* 4624 can_recover_arg(Location); 4625 4626 // General IR. 4627 Gogo* gogo_; 4628 }; 4629 4630 // If this function calls recover, turn it into a thunk. 4631 4632 int 4633 Build_recover_thunks::function(Named_object* orig_no) 4634 { 4635 Function* orig_func = orig_no->func_value(); 4636 if (!orig_func->calls_recover() 4637 || orig_func->is_recover_thunk() 4638 || orig_func->has_recover_thunk()) 4639 return TRAVERSE_CONTINUE; 4640 4641 Gogo* gogo = this->gogo_; 4642 Location location = orig_func->location(); 4643 4644 static int count; 4645 char buf[50]; 4646 4647 Function_type* orig_fntype = orig_func->type(); 4648 Typed_identifier_list* new_params = new Typed_identifier_list(); 4649 std::string receiver_name; 4650 if (orig_fntype->is_method()) 4651 { 4652 const Typed_identifier* receiver = orig_fntype->receiver(); 4653 snprintf(buf, sizeof buf, "rt.%u", count); 4654 ++count; 4655 receiver_name = buf; 4656 new_params->push_back(Typed_identifier(receiver_name, receiver->type(), 4657 receiver->location())); 4658 } 4659 const Typed_identifier_list* orig_params = orig_fntype->parameters(); 4660 if (orig_params != NULL && !orig_params->empty()) 4661 { 4662 for (Typed_identifier_list::const_iterator p = orig_params->begin(); 4663 p != orig_params->end(); 4664 ++p) 4665 { 4666 snprintf(buf, sizeof buf, "pt.%u", count); 4667 ++count; 4668 new_params->push_back(Typed_identifier(buf, p->type(), 4669 p->location())); 4670 } 4671 } 4672 snprintf(buf, sizeof buf, "pr.%u", count); 4673 ++count; 4674 std::string can_recover_name = buf; 4675 new_params->push_back(Typed_identifier(can_recover_name, 4676 Type::lookup_bool_type(), 4677 orig_fntype->location())); 4678 4679 const Typed_identifier_list* orig_results = orig_fntype->results(); 4680 Typed_identifier_list* new_results; 4681 if (orig_results == NULL || orig_results->empty()) 4682 new_results = NULL; 4683 else 4684 { 4685 new_results = new Typed_identifier_list(); 4686 for (Typed_identifier_list::const_iterator p = orig_results->begin(); 4687 p != orig_results->end(); 4688 ++p) 4689 new_results->push_back(Typed_identifier("", p->type(), p->location())); 4690 } 4691 4692 Function_type *new_fntype = Type::make_function_type(NULL, new_params, 4693 new_results, 4694 orig_fntype->location()); 4695 if (orig_fntype->is_varargs()) 4696 new_fntype->set_is_varargs(); 4697 4698 Type* rtype = NULL; 4699 if (orig_fntype->is_method()) 4700 rtype = orig_fntype->receiver()->type(); 4701 std::string name(gogo->recover_thunk_name(orig_no->name(), rtype)); 4702 Named_object *new_no = gogo->start_function(name, new_fntype, false, 4703 location); 4704 Function *new_func = new_no->func_value(); 4705 if (orig_func->enclosing() != NULL) 4706 new_func->set_enclosing(orig_func->enclosing()); 4707 4708 // We build the code for the original function attached to the new 4709 // function, and then swap the original and new function bodies. 4710 // This means that existing references to the original function will 4711 // then refer to the new function. That makes this code a little 4712 // confusing, in that the reference to NEW_NO really refers to the 4713 // other function, not the one we are building. 4714 4715 Expression* closure = NULL; 4716 if (orig_func->needs_closure()) 4717 { 4718 // For the new function we are creating, declare a new parameter 4719 // variable NEW_CLOSURE_NO and set it to be the closure variable 4720 // of the function. This will be set to the closure value 4721 // passed in by the caller. Then pass a reference to this 4722 // variable as the closure value when calling the original 4723 // function. In other words, simply pass the closure value 4724 // through the thunk we are creating. 4725 Named_object* orig_closure_no = orig_func->closure_var(); 4726 Variable* orig_closure_var = orig_closure_no->var_value(); 4727 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false, 4728 false, false, location); 4729 new_var->set_is_closure(); 4730 snprintf(buf, sizeof buf, "closure.%u", count); 4731 ++count; 4732 Named_object* new_closure_no = Named_object::make_variable(buf, NULL, 4733 new_var); 4734 new_func->set_closure_var(new_closure_no); 4735 closure = Expression::make_var_reference(new_closure_no, location); 4736 } 4737 4738 Expression* fn = Expression::make_func_reference(new_no, closure, location); 4739 4740 Expression_list* args = new Expression_list(); 4741 if (new_params != NULL) 4742 { 4743 // Note that we skip the last parameter, which is the boolean 4744 // indicating whether recover can succed. 4745 for (Typed_identifier_list::const_iterator p = new_params->begin(); 4746 p + 1 != new_params->end(); 4747 ++p) 4748 { 4749 Named_object* p_no = gogo->lookup(p->name(), NULL); 4750 go_assert(p_no != NULL 4751 && p_no->is_variable() 4752 && p_no->var_value()->is_parameter()); 4753 args->push_back(Expression::make_var_reference(p_no, location)); 4754 } 4755 } 4756 args->push_back(this->can_recover_arg(location)); 4757 4758 gogo->start_block(location); 4759 4760 Call_expression* call = Expression::make_call(fn, args, false, location); 4761 4762 // Any varargs call has already been lowered. 4763 call->set_varargs_are_lowered(); 4764 4765 Statement* s = Statement::make_return_from_call(call, location); 4766 s->determine_types(); 4767 gogo->add_statement(s); 4768 4769 Block* b = gogo->finish_block(location); 4770 4771 gogo->add_block(b, location); 4772 4773 // Lower the call in case it returns multiple results. 4774 gogo->lower_block(new_no, b); 4775 4776 gogo->finish_function(location); 4777 4778 // Swap the function bodies and types. 4779 new_func->swap_for_recover(orig_func); 4780 orig_func->set_is_recover_thunk(); 4781 new_func->set_calls_recover(); 4782 new_func->set_has_recover_thunk(); 4783 4784 Bindings* orig_bindings = orig_func->block()->bindings(); 4785 Bindings* new_bindings = new_func->block()->bindings(); 4786 if (orig_fntype->is_method()) 4787 { 4788 // We changed the receiver to be a regular parameter. We have 4789 // to update the binding accordingly in both functions. 4790 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name); 4791 go_assert(orig_rec_no != NULL 4792 && orig_rec_no->is_variable() 4793 && !orig_rec_no->var_value()->is_receiver()); 4794 orig_rec_no->var_value()->set_is_receiver(); 4795 4796 std::string new_receiver_name(orig_fntype->receiver()->name()); 4797 if (new_receiver_name.empty()) 4798 { 4799 // Find the receiver. It was named "r.NNN" in 4800 // Gogo::start_function. 4801 for (Bindings::const_definitions_iterator p = 4802 new_bindings->begin_definitions(); 4803 p != new_bindings->end_definitions(); 4804 ++p) 4805 { 4806 const std::string& pname((*p)->name()); 4807 if (pname[0] == 'r' && pname[1] == '.') 4808 { 4809 new_receiver_name = pname; 4810 break; 4811 } 4812 } 4813 go_assert(!new_receiver_name.empty()); 4814 } 4815 Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name); 4816 if (new_rec_no == NULL) 4817 go_assert(saw_errors()); 4818 else 4819 { 4820 go_assert(new_rec_no->is_variable() 4821 && new_rec_no->var_value()->is_receiver()); 4822 new_rec_no->var_value()->set_is_not_receiver(); 4823 } 4824 } 4825 4826 // Because we flipped blocks but not types, the can_recover 4827 // parameter appears in the (now) old bindings as a parameter. 4828 // Change it to a local variable, whereupon it will be discarded. 4829 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name); 4830 go_assert(can_recover_no != NULL 4831 && can_recover_no->is_variable() 4832 && can_recover_no->var_value()->is_parameter()); 4833 orig_bindings->remove_binding(can_recover_no); 4834 4835 // Add the can_recover argument to the (now) new bindings, and 4836 // attach it to any recover statements. 4837 Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL, 4838 false, true, false, location); 4839 can_recover_no = new_bindings->add_variable(can_recover_name, NULL, 4840 can_recover_var); 4841 Convert_recover convert_recover(can_recover_no); 4842 new_func->traverse(&convert_recover); 4843 4844 // Update the function pointers in any named results. 4845 new_func->update_result_variables(); 4846 orig_func->update_result_variables(); 4847 4848 return TRAVERSE_CONTINUE; 4849 } 4850 4851 // Return the expression to pass for the .can_recover parameter to the 4852 // new function. This indicates whether a call to recover may return 4853 // non-nil. The expression is runtime.canrecover(__builtin_return_address()). 4854 4855 Expression* 4856 Build_recover_thunks::can_recover_arg(Location location) 4857 { 4858 Type* uintptr_type = Type::lookup_integer_type("uintptr"); 4859 static Named_object* can_recover; 4860 if (can_recover == NULL) 4861 { 4862 const Location bloc = Linemap::predeclared_location(); 4863 Typed_identifier_list* param_types = new Typed_identifier_list(); 4864 param_types->push_back(Typed_identifier("a", uintptr_type, bloc)); 4865 Type* boolean_type = Type::lookup_bool_type(); 4866 Typed_identifier_list* results = new Typed_identifier_list(); 4867 results->push_back(Typed_identifier("", boolean_type, bloc)); 4868 Function_type* fntype = Type::make_function_type(NULL, param_types, 4869 results, bloc); 4870 can_recover = 4871 Named_object::make_function_declaration("runtime_canrecover", 4872 NULL, fntype, bloc); 4873 can_recover->func_declaration_value()->set_asm_name("runtime.canrecover"); 4874 } 4875 4876 Expression* zexpr = Expression::make_integer_ul(0, NULL, location); 4877 Expression* call = Runtime::make_call(Runtime::BUILTIN_RETURN_ADDRESS, 4878 location, 1, zexpr); 4879 call = Expression::make_unsafe_cast(uintptr_type, call, location); 4880 4881 Expression_list* args = new Expression_list(); 4882 args->push_back(call); 4883 4884 Expression* fn = Expression::make_func_reference(can_recover, NULL, location); 4885 return Expression::make_call(fn, args, false, location); 4886 } 4887 4888 // Build thunks for functions which call recover. We build a new 4889 // function with an extra parameter, which is whether a call to 4890 // recover can succeed. We then move the body of this function to 4891 // that one. We then turn this function into a thunk which calls the 4892 // new one, passing the value of runtime.canrecover(__builtin_return_address()). 4893 // The function will be marked as not splitting the stack. This will 4894 // cooperate with the implementation of defer to make recover do the 4895 // right thing. 4896 4897 void 4898 Gogo::build_recover_thunks() 4899 { 4900 Build_recover_thunks build_recover_thunks(this); 4901 this->traverse(&build_recover_thunks); 4902 } 4903 4904 // Look for named types to see whether we need to create an interface 4905 // method table. 4906 4907 class Build_method_tables : public Traverse 4908 { 4909 public: 4910 Build_method_tables(Gogo* gogo, 4911 const std::vector<Interface_type*>& interfaces) 4912 : Traverse(traverse_types), 4913 gogo_(gogo), interfaces_(interfaces) 4914 { } 4915 4916 int 4917 type(Type*); 4918 4919 private: 4920 // The IR. 4921 Gogo* gogo_; 4922 // A list of locally defined interfaces which have hidden methods. 4923 const std::vector<Interface_type*>& interfaces_; 4924 }; 4925 4926 // Build all required interface method tables for types. We need to 4927 // ensure that we have an interface method table for every interface 4928 // which has a hidden method, for every named type which implements 4929 // that interface. Normally we can just build interface method tables 4930 // as we need them. However, in some cases we can require an 4931 // interface method table for an interface defined in a different 4932 // package for a type defined in that package. If that interface and 4933 // type both use a hidden method, that is OK. However, we will not be 4934 // able to build that interface method table when we need it, because 4935 // the type's hidden method will be static. So we have to build it 4936 // here, and just refer it from other packages as needed. 4937 4938 void 4939 Gogo::build_interface_method_tables() 4940 { 4941 if (saw_errors()) 4942 return; 4943 4944 std::vector<Interface_type*> hidden_interfaces; 4945 hidden_interfaces.reserve(this->interface_types_.size()); 4946 for (std::vector<Interface_type*>::const_iterator pi = 4947 this->interface_types_.begin(); 4948 pi != this->interface_types_.end(); 4949 ++pi) 4950 { 4951 const Typed_identifier_list* methods = (*pi)->methods(); 4952 if (methods == NULL) 4953 continue; 4954 for (Typed_identifier_list::const_iterator pm = methods->begin(); 4955 pm != methods->end(); 4956 ++pm) 4957 { 4958 if (Gogo::is_hidden_name(pm->name())) 4959 { 4960 hidden_interfaces.push_back(*pi); 4961 break; 4962 } 4963 } 4964 } 4965 4966 if (!hidden_interfaces.empty()) 4967 { 4968 // Now traverse the tree looking for all named types. 4969 Build_method_tables bmt(this, hidden_interfaces); 4970 this->traverse(&bmt); 4971 } 4972 4973 // We no longer need the list of interfaces. 4974 4975 this->interface_types_.clear(); 4976 } 4977 4978 // This is called for each type. For a named type, for each of the 4979 // interfaces with hidden methods that it implements, create the 4980 // method table. 4981 4982 int 4983 Build_method_tables::type(Type* type) 4984 { 4985 Named_type* nt = type->named_type(); 4986 Struct_type* st = type->struct_type(); 4987 if (nt != NULL || st != NULL) 4988 { 4989 Translate_context context(this->gogo_, NULL, NULL, NULL); 4990 for (std::vector<Interface_type*>::const_iterator p = 4991 this->interfaces_.begin(); 4992 p != this->interfaces_.end(); 4993 ++p) 4994 { 4995 // We ask whether a pointer to the named type implements the 4996 // interface, because a pointer can implement more methods 4997 // than a value. 4998 if (nt != NULL) 4999 { 5000 if ((*p)->implements_interface(Type::make_pointer_type(nt), 5001 NULL)) 5002 { 5003 nt->interface_method_table(*p, false)->get_backend(&context); 5004 nt->interface_method_table(*p, true)->get_backend(&context); 5005 } 5006 } 5007 else 5008 { 5009 if ((*p)->implements_interface(Type::make_pointer_type(st), 5010 NULL)) 5011 { 5012 st->interface_method_table(*p, false)->get_backend(&context); 5013 st->interface_method_table(*p, true)->get_backend(&context); 5014 } 5015 } 5016 } 5017 } 5018 return TRAVERSE_CONTINUE; 5019 } 5020 5021 // Return an expression which allocates memory to hold values of type TYPE. 5022 5023 Expression* 5024 Gogo::allocate_memory(Type* type, Location location) 5025 { 5026 Expression* td = Expression::make_type_descriptor(type, location); 5027 return Runtime::make_call(Runtime::NEW, location, 1, td); 5028 } 5029 5030 // Traversal class used to check for return statements. 5031 5032 class Check_return_statements_traverse : public Traverse 5033 { 5034 public: 5035 Check_return_statements_traverse() 5036 : Traverse(traverse_functions) 5037 { } 5038 5039 int 5040 function(Named_object*); 5041 }; 5042 5043 // Check that a function has a return statement if it needs one. 5044 5045 int 5046 Check_return_statements_traverse::function(Named_object* no) 5047 { 5048 Function* func = no->func_value(); 5049 const Function_type* fntype = func->type(); 5050 const Typed_identifier_list* results = fntype->results(); 5051 5052 // We only need a return statement if there is a return value. 5053 if (results == NULL || results->empty()) 5054 return TRAVERSE_CONTINUE; 5055 5056 if (func->block()->may_fall_through()) 5057 go_error_at(func->block()->end_location(), 5058 "missing return at end of function"); 5059 5060 return TRAVERSE_CONTINUE; 5061 } 5062 5063 // Check return statements. 5064 5065 void 5066 Gogo::check_return_statements() 5067 { 5068 Check_return_statements_traverse traverse; 5069 this->traverse(&traverse); 5070 } 5071 5072 // Traversal class to decide whether a function body is less than the 5073 // inlining budget. This adjusts *available as it goes, and stops the 5074 // traversal if it goes negative. 5075 5076 class Inline_within_budget : public Traverse 5077 { 5078 public: 5079 Inline_within_budget(int* available) 5080 : Traverse(traverse_statements 5081 | traverse_expressions), 5082 available_(available) 5083 { } 5084 5085 int 5086 statement(Block*, size_t*, Statement*); 5087 5088 int 5089 expression(Expression**); 5090 5091 private: 5092 // Pointer to remaining budget. 5093 int* available_; 5094 }; 5095 5096 // Adjust the budget for the inlining cost of a statement. 5097 5098 int 5099 Inline_within_budget::statement(Block*, size_t*, Statement* s) 5100 { 5101 if (*this->available_ < 0) 5102 return TRAVERSE_EXIT; 5103 *this->available_ -= s->inlining_cost(); 5104 return TRAVERSE_CONTINUE; 5105 } 5106 5107 // Adjust the budget for the inlining cost of an expression. 5108 5109 int 5110 Inline_within_budget::expression(Expression** pexpr) 5111 { 5112 if (*this->available_ < 0) 5113 return TRAVERSE_EXIT; 5114 *this->available_ -= (*pexpr)->inlining_cost(); 5115 return TRAVERSE_CONTINUE; 5116 } 5117 5118 // Traversal class to find functions whose body should be exported for 5119 // inlining by other packages. 5120 5121 class Mark_inline_candidates : public Traverse 5122 { 5123 public: 5124 Mark_inline_candidates(Unordered_set(Named_object*)* marked) 5125 : Traverse(traverse_functions 5126 | traverse_types), 5127 marked_functions_(marked) 5128 { } 5129 5130 int 5131 function(Named_object*); 5132 5133 int 5134 type(Type*); 5135 5136 private: 5137 // We traverse the function body trying to determine how expensive 5138 // it is for inlining. We start with a budget, and decrease that 5139 // budget for each statement and expression. If the budget goes 5140 // negative, we do not export the function body. The value of this 5141 // budget is a heuristic. In the usual GCC spirit, we could 5142 // consider setting this via a command line option. 5143 const int budget_heuristic = 80; 5144 5145 // Set of named objects that are marked as inline candidates. 5146 Unordered_set(Named_object*)* marked_functions_; 5147 }; 5148 5149 // Mark a function if it is an inline candidate. 5150 5151 int 5152 Mark_inline_candidates::function(Named_object* no) 5153 { 5154 Function* func = no->func_value(); 5155 if ((func->pragmas() & GOPRAGMA_NOINLINE) != 0) 5156 return TRAVERSE_CONTINUE; 5157 int budget = budget_heuristic; 5158 Inline_within_budget iwb(&budget); 5159 func->block()->traverse(&iwb); 5160 if (budget >= 0) 5161 { 5162 func->set_export_for_inlining(); 5163 this->marked_functions_->insert(no); 5164 } 5165 return TRAVERSE_CONTINUE; 5166 } 5167 5168 // Mark methods if they are inline candidates. 5169 5170 int 5171 Mark_inline_candidates::type(Type* t) 5172 { 5173 Named_type* nt = t->named_type(); 5174 if (nt == NULL || nt->is_alias()) 5175 return TRAVERSE_CONTINUE; 5176 const Bindings* methods = nt->local_methods(); 5177 if (methods == NULL) 5178 return TRAVERSE_CONTINUE; 5179 for (Bindings::const_definitions_iterator p = methods->begin_definitions(); 5180 p != methods->end_definitions(); 5181 ++p) 5182 { 5183 Named_object* no = *p; 5184 go_assert(no->is_function()); 5185 Function *func = no->func_value(); 5186 if ((func->pragmas() & GOPRAGMA_NOINLINE) != 0) 5187 continue; 5188 int budget = budget_heuristic; 5189 Inline_within_budget iwb(&budget); 5190 func->block()->traverse(&iwb); 5191 if (budget >= 0) 5192 { 5193 func->set_export_for_inlining(); 5194 this->marked_functions_->insert(no); 5195 } 5196 } 5197 return TRAVERSE_CONTINUE; 5198 } 5199 5200 // Export identifiers as requested. 5201 5202 void 5203 Gogo::do_exports() 5204 { 5205 if (saw_errors()) 5206 return; 5207 5208 // Mark any functions whose body should be exported for inlining by 5209 // other packages. 5210 Unordered_set(Named_object*) marked_functions; 5211 Mark_inline_candidates mic(&marked_functions); 5212 this->traverse(&mic); 5213 5214 // For now we always stream to a section. Later we may want to 5215 // support streaming to a separate file. 5216 Stream_to_section stream(this->backend()); 5217 5218 // Write out either the prefix or pkgpath depending on how we were 5219 // invoked. 5220 std::string prefix; 5221 std::string pkgpath; 5222 if (this->pkgpath_from_option_) 5223 pkgpath = this->pkgpath_; 5224 else if (this->prefix_from_option_) 5225 prefix = this->prefix_; 5226 else if (this->is_main_package()) 5227 pkgpath = "main"; 5228 else 5229 prefix = "go"; 5230 5231 std::string init_fn_name; 5232 if (this->is_main_package()) 5233 init_fn_name = ""; 5234 else if (this->need_init_fn_) 5235 init_fn_name = this->get_init_fn_name(); 5236 else 5237 init_fn_name = this->dummy_init_fn_name(); 5238 5239 Export exp(&stream); 5240 exp.register_builtin_types(this); 5241 exp.export_globals(this->package_name(), 5242 prefix, 5243 pkgpath, 5244 this->packages_, 5245 this->imports_, 5246 init_fn_name, 5247 this->imported_init_fns_, 5248 this->package_->bindings(), 5249 &marked_functions); 5250 5251 if (!this->c_header_.empty() && !saw_errors()) 5252 this->write_c_header(); 5253 } 5254 5255 // Write the top level named struct types in C format to a C header 5256 // file. This is used when building the runtime package, to share 5257 // struct definitions between C and Go. 5258 5259 void 5260 Gogo::write_c_header() 5261 { 5262 std::ofstream out; 5263 out.open(this->c_header_.c_str()); 5264 if (out.fail()) 5265 { 5266 go_error_at(Linemap::unknown_location(), 5267 "cannot open %s: %m", this->c_header_.c_str()); 5268 return; 5269 } 5270 5271 std::list<Named_object*> types; 5272 Bindings* top = this->package_->bindings(); 5273 for (Bindings::const_definitions_iterator p = top->begin_definitions(); 5274 p != top->end_definitions(); 5275 ++p) 5276 { 5277 Named_object* no = *p; 5278 5279 // Skip names that start with underscore followed by something 5280 // other than an uppercase letter, as when compiling the runtime 5281 // package they are mostly types defined by mkrsysinfo.sh based 5282 // on the C system header files. We don't need to translate 5283 // types to C and back to Go. But do accept the special cases 5284 // _defer, _panic, and _type. 5285 std::string name = Gogo::unpack_hidden_name(no->name()); 5286 if (name[0] == '_' 5287 && (name[1] < 'A' || name[1] > 'Z') 5288 && (name != "_defer" && name != "_panic" && name != "_type")) 5289 continue; 5290 5291 if (no->is_type() && no->type_value()->struct_type() != NULL) 5292 types.push_back(no); 5293 if (no->is_const() 5294 && no->const_value()->type()->integer_type() != NULL 5295 && !no->const_value()->is_sink()) 5296 { 5297 Numeric_constant nc; 5298 unsigned long val; 5299 if (no->const_value()->expr()->numeric_constant_value(&nc) 5300 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID) 5301 { 5302 out << "#define " << no->message_name() << ' ' << val 5303 << std::endl; 5304 } 5305 } 5306 } 5307 5308 std::vector<const Named_object*> written; 5309 int loop = 0; 5310 while (!types.empty()) 5311 { 5312 Named_object* no = types.front(); 5313 types.pop_front(); 5314 5315 std::vector<const Named_object*> needs; 5316 std::vector<const Named_object*> declare; 5317 if (!no->type_value()->struct_type()->can_write_to_c_header(&needs, 5318 &declare)) 5319 continue; 5320 5321 bool ok = true; 5322 for (std::vector<const Named_object*>::const_iterator pr 5323 = needs.begin(); 5324 pr != needs.end() && ok; 5325 ++pr) 5326 { 5327 for (std::list<Named_object*>::const_iterator pt = types.begin(); 5328 pt != types.end() && ok; 5329 ++pt) 5330 if (*pr == *pt) 5331 ok = false; 5332 } 5333 if (!ok) 5334 { 5335 ++loop; 5336 if (loop > 10000) 5337 { 5338 // This should be impossible since the code parsed and 5339 // type checked. 5340 go_unreachable(); 5341 } 5342 5343 types.push_back(no); 5344 continue; 5345 } 5346 5347 for (std::vector<const Named_object*>::const_iterator pd 5348 = declare.begin(); 5349 pd != declare.end(); 5350 ++pd) 5351 { 5352 if (*pd == no) 5353 continue; 5354 5355 std::vector<const Named_object*> dneeds; 5356 std::vector<const Named_object*> ddeclare; 5357 if (!(*pd)->type_value()->struct_type()-> 5358 can_write_to_c_header(&dneeds, &ddeclare)) 5359 continue; 5360 5361 bool done = false; 5362 for (std::vector<const Named_object*>::const_iterator pw 5363 = written.begin(); 5364 pw != written.end(); 5365 ++pw) 5366 { 5367 if (*pw == *pd) 5368 { 5369 done = true; 5370 break; 5371 } 5372 } 5373 if (!done) 5374 { 5375 out << std::endl; 5376 out << "struct " << (*pd)->message_name() << ";" << std::endl; 5377 written.push_back(*pd); 5378 } 5379 } 5380 5381 out << std::endl; 5382 out << "struct " << no->message_name() << " {" << std::endl; 5383 no->type_value()->struct_type()->write_to_c_header(out); 5384 out << "};" << std::endl; 5385 written.push_back(no); 5386 } 5387 5388 out.close(); 5389 if (out.fail()) 5390 go_error_at(Linemap::unknown_location(), 5391 "error writing to %s: %m", this->c_header_.c_str()); 5392 } 5393 5394 // Find the blocks in order to convert named types defined in blocks. 5395 5396 class Convert_named_types : public Traverse 5397 { 5398 public: 5399 Convert_named_types(Gogo* gogo) 5400 : Traverse(traverse_blocks), 5401 gogo_(gogo) 5402 { } 5403 5404 protected: 5405 int 5406 block(Block* block); 5407 5408 private: 5409 Gogo* gogo_; 5410 }; 5411 5412 int 5413 Convert_named_types::block(Block* block) 5414 { 5415 this->gogo_->convert_named_types_in_bindings(block->bindings()); 5416 return TRAVERSE_CONTINUE; 5417 } 5418 5419 // Convert all named types to the backend representation. Since named 5420 // types can refer to other types, this needs to be done in the right 5421 // sequence, which is handled by Named_type::convert. Here we arrange 5422 // to call that for each named type. 5423 5424 void 5425 Gogo::convert_named_types() 5426 { 5427 this->convert_named_types_in_bindings(this->globals_); 5428 for (Packages::iterator p = this->packages_.begin(); 5429 p != this->packages_.end(); 5430 ++p) 5431 { 5432 Package* package = p->second; 5433 this->convert_named_types_in_bindings(package->bindings()); 5434 } 5435 5436 Convert_named_types cnt(this); 5437 this->traverse(&cnt); 5438 5439 // Make all the builtin named types used for type descriptors, and 5440 // then convert them. They will only be written out if they are 5441 // needed. 5442 Type::make_type_descriptor_type(); 5443 Type::make_type_descriptor_ptr_type(); 5444 Function_type::make_function_type_descriptor_type(); 5445 Pointer_type::make_pointer_type_descriptor_type(); 5446 Struct_type::make_struct_type_descriptor_type(); 5447 Array_type::make_array_type_descriptor_type(); 5448 Array_type::make_slice_type_descriptor_type(); 5449 Map_type::make_map_type_descriptor_type(); 5450 Channel_type::make_chan_type_descriptor_type(); 5451 Interface_type::make_interface_type_descriptor_type(); 5452 Expression::make_func_descriptor_type(); 5453 Type::convert_builtin_named_types(this); 5454 5455 Runtime::convert_types(this); 5456 5457 this->named_types_are_converted_ = true; 5458 5459 Type::finish_pointer_types(this); 5460 } 5461 5462 // Convert all names types in a set of bindings. 5463 5464 void 5465 Gogo::convert_named_types_in_bindings(Bindings* bindings) 5466 { 5467 for (Bindings::const_definitions_iterator p = bindings->begin_definitions(); 5468 p != bindings->end_definitions(); 5469 ++p) 5470 { 5471 if ((*p)->is_type()) 5472 (*p)->type_value()->convert(this); 5473 } 5474 } 5475 5476 void 5477 debug_go_gogo(Gogo* gogo) 5478 { 5479 if (gogo != NULL) 5480 gogo->debug_dump(); 5481 } 5482 5483 void 5484 Gogo::debug_dump() 5485 { 5486 std::cerr << "Packages:\n"; 5487 for (Packages::const_iterator p = this->packages_.begin(); 5488 p != this->packages_.end(); 5489 ++p) 5490 { 5491 const char *tag = " "; 5492 if (p->second == this->package_) 5493 tag = "* "; 5494 std::cerr << tag << "'" << p->first << "' " 5495 << p->second->pkgpath() << " " << ((void*)p->second) << "\n"; 5496 } 5497 } 5498 5499 // Class Function. 5500 5501 Function::Function(Function_type* type, Named_object* enclosing, Block* block, 5502 Location location) 5503 : type_(type), enclosing_(enclosing), results_(NULL), 5504 closure_var_(NULL), block_(block), location_(location), labels_(), 5505 local_type_count_(0), descriptor_(NULL), fndecl_(NULL), defer_stack_(NULL), 5506 pragmas_(0), nested_functions_(0), is_sink_(false), 5507 results_are_named_(false), is_unnamed_type_stub_method_(false), 5508 calls_recover_(false), is_recover_thunk_(false), has_recover_thunk_(false), 5509 calls_defer_retaddr_(false), is_type_specific_function_(false), 5510 in_unique_section_(false), export_for_inlining_(false), 5511 is_inline_only_(false), is_referenced_by_inline_(false), 5512 is_exported_by_linkname_(false) 5513 { 5514 } 5515 5516 // Create the named result variables. 5517 5518 void 5519 Function::create_result_variables(Gogo* gogo) 5520 { 5521 const Typed_identifier_list* results = this->type_->results(); 5522 if (results == NULL || results->empty()) 5523 return; 5524 5525 if (!results->front().name().empty()) 5526 this->results_are_named_ = true; 5527 5528 this->results_ = new Results(); 5529 this->results_->reserve(results->size()); 5530 5531 Block* block = this->block_; 5532 int index = 0; 5533 for (Typed_identifier_list::const_iterator p = results->begin(); 5534 p != results->end(); 5535 ++p, ++index) 5536 { 5537 std::string name = p->name(); 5538 if (name.empty() || Gogo::is_sink_name(name)) 5539 { 5540 static int result_counter; 5541 char buf[100]; 5542 snprintf(buf, sizeof buf, "$ret%d", result_counter); 5543 ++result_counter; 5544 name = gogo->pack_hidden_name(buf, false); 5545 } 5546 Result_variable* result = new Result_variable(p->type(), this, index, 5547 p->location()); 5548 Named_object* no = block->bindings()->add_result_variable(name, result); 5549 if (no->is_result_variable()) 5550 this->results_->push_back(no); 5551 else 5552 { 5553 static int dummy_result_count; 5554 char buf[100]; 5555 snprintf(buf, sizeof buf, "$dret%d", dummy_result_count); 5556 ++dummy_result_count; 5557 name = gogo->pack_hidden_name(buf, false); 5558 no = block->bindings()->add_result_variable(name, result); 5559 go_assert(no->is_result_variable()); 5560 this->results_->push_back(no); 5561 } 5562 } 5563 } 5564 5565 // Update the named result variables when cloning a function which 5566 // calls recover. 5567 5568 void 5569 Function::update_result_variables() 5570 { 5571 if (this->results_ == NULL) 5572 return; 5573 5574 for (Results::iterator p = this->results_->begin(); 5575 p != this->results_->end(); 5576 ++p) 5577 (*p)->result_var_value()->set_function(this); 5578 } 5579 5580 // Whether this method should not be included in the type descriptor. 5581 5582 bool 5583 Function::nointerface() const 5584 { 5585 go_assert(this->is_method()); 5586 return (this->pragmas_ & GOPRAGMA_NOINTERFACE) != 0; 5587 } 5588 5589 // Record that this method should not be included in the type 5590 // descriptor. 5591 5592 void 5593 Function::set_nointerface() 5594 { 5595 this->pragmas_ |= GOPRAGMA_NOINTERFACE; 5596 } 5597 5598 // Return the closure variable, creating it if necessary. 5599 5600 Named_object* 5601 Function::closure_var() 5602 { 5603 if (this->closure_var_ == NULL) 5604 { 5605 go_assert(this->descriptor_ == NULL); 5606 // We don't know the type of the variable yet. We add fields as 5607 // we find them. 5608 Location loc = this->type_->location(); 5609 Struct_field_list* sfl = new Struct_field_list; 5610 Struct_type* struct_type = Type::make_struct_type(sfl, loc); 5611 struct_type->set_is_struct_incomparable(); 5612 Variable* var = new Variable(Type::make_pointer_type(struct_type), 5613 NULL, false, false, false, loc); 5614 var->set_is_used(); 5615 var->set_is_closure(); 5616 this->closure_var_ = Named_object::make_variable("$closure", NULL, var); 5617 // Note that the new variable is not in any binding contour. 5618 } 5619 return this->closure_var_; 5620 } 5621 5622 // Set the type of the closure variable. 5623 5624 void 5625 Function::set_closure_type() 5626 { 5627 if (this->closure_var_ == NULL) 5628 return; 5629 Named_object* closure = this->closure_var_; 5630 Struct_type* st = closure->var_value()->type()->deref()->struct_type(); 5631 5632 // The first field of a closure is always a pointer to the function 5633 // code. 5634 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type()); 5635 st->push_field(Struct_field(Typed_identifier(".f", voidptr_type, 5636 this->location_))); 5637 5638 unsigned int index = 1; 5639 for (Closure_fields::const_iterator p = this->closure_fields_.begin(); 5640 p != this->closure_fields_.end(); 5641 ++p, ++index) 5642 { 5643 Named_object* no = p->first; 5644 char buf[20]; 5645 snprintf(buf, sizeof buf, "%u", index); 5646 std::string n = no->name() + buf; 5647 Type* var_type; 5648 if (no->is_variable()) 5649 var_type = no->var_value()->type(); 5650 else 5651 var_type = no->result_var_value()->type(); 5652 Type* field_type = Type::make_pointer_type(var_type); 5653 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second))); 5654 } 5655 } 5656 5657 // Return whether this function is a method. 5658 5659 bool 5660 Function::is_method() const 5661 { 5662 return this->type_->is_method(); 5663 } 5664 5665 // Add a label definition. 5666 5667 Label* 5668 Function::add_label_definition(Gogo* gogo, const std::string& label_name, 5669 Location location) 5670 { 5671 Label* lnull = NULL; 5672 std::pair<Labels::iterator, bool> ins = 5673 this->labels_.insert(std::make_pair(label_name, lnull)); 5674 Label* label; 5675 if (label_name == "_") 5676 { 5677 label = Label::create_dummy_label(); 5678 if (ins.second) 5679 ins.first->second = label; 5680 } 5681 else if (ins.second) 5682 { 5683 // This is a new label. 5684 label = new Label(label_name); 5685 ins.first->second = label; 5686 } 5687 else 5688 { 5689 // The label was already in the hash table. 5690 label = ins.first->second; 5691 if (label->is_defined()) 5692 { 5693 go_error_at(location, "label %qs already defined", 5694 Gogo::message_name(label_name).c_str()); 5695 go_inform(label->location(), "previous definition of %qs was here", 5696 Gogo::message_name(label_name).c_str()); 5697 return new Label(label_name); 5698 } 5699 } 5700 5701 label->define(location, gogo->bindings_snapshot(location)); 5702 5703 // Issue any errors appropriate for any previous goto's to this 5704 // label. 5705 const std::vector<Bindings_snapshot*>& refs(label->refs()); 5706 for (std::vector<Bindings_snapshot*>::const_iterator p = refs.begin(); 5707 p != refs.end(); 5708 ++p) 5709 (*p)->check_goto_to(gogo->current_block()); 5710 label->clear_refs(); 5711 5712 return label; 5713 } 5714 5715 // Add a reference to a label. 5716 5717 Label* 5718 Function::add_label_reference(Gogo* gogo, const std::string& label_name, 5719 Location location, bool issue_goto_errors) 5720 { 5721 Label* lnull = NULL; 5722 std::pair<Labels::iterator, bool> ins = 5723 this->labels_.insert(std::make_pair(label_name, lnull)); 5724 Label* label; 5725 if (!ins.second) 5726 { 5727 // The label was already in the hash table. 5728 label = ins.first->second; 5729 } 5730 else 5731 { 5732 go_assert(ins.first->second == NULL); 5733 label = new Label(label_name); 5734 ins.first->second = label; 5735 } 5736 5737 label->set_is_used(); 5738 5739 if (issue_goto_errors) 5740 { 5741 Bindings_snapshot* snapshot = label->snapshot(); 5742 if (snapshot != NULL) 5743 snapshot->check_goto_from(gogo->current_block(), location); 5744 else 5745 label->add_snapshot_ref(gogo->bindings_snapshot(location)); 5746 } 5747 5748 return label; 5749 } 5750 5751 // Warn about labels that are defined but not used. 5752 5753 void 5754 Function::check_labels() const 5755 { 5756 for (Labels::const_iterator p = this->labels_.begin(); 5757 p != this->labels_.end(); 5758 p++) 5759 { 5760 Label* label = p->second; 5761 if (!label->is_used()) 5762 go_error_at(label->location(), "label %qs defined and not used", 5763 Gogo::message_name(label->name()).c_str()); 5764 } 5765 } 5766 5767 // Set the receiver type. This is used to remove aliases. 5768 5769 void 5770 Function::set_receiver_type(Type* rtype) 5771 { 5772 Function_type* oft = this->type_; 5773 Typed_identifier* rec = new Typed_identifier(oft->receiver()->name(), 5774 rtype, 5775 oft->receiver()->location()); 5776 Typed_identifier_list* parameters = NULL; 5777 if (oft->parameters() != NULL) 5778 parameters = oft->parameters()->copy(); 5779 Typed_identifier_list* results = NULL; 5780 if (oft->results() != NULL) 5781 results = oft->results()->copy(); 5782 Function_type* nft = Type::make_function_type(rec, parameters, results, 5783 oft->location()); 5784 this->type_ = nft; 5785 } 5786 5787 // Swap one function with another. This is used when building the 5788 // thunk we use to call a function which calls recover. It may not 5789 // work for any other case. 5790 5791 void 5792 Function::swap_for_recover(Function *x) 5793 { 5794 go_assert(this->enclosing_ == x->enclosing_); 5795 std::swap(this->results_, x->results_); 5796 std::swap(this->closure_var_, x->closure_var_); 5797 std::swap(this->block_, x->block_); 5798 go_assert(this->location_ == x->location_); 5799 go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL); 5800 go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL); 5801 } 5802 5803 // Traverse the tree. 5804 5805 int 5806 Function::traverse(Traverse* traverse) 5807 { 5808 unsigned int traverse_mask = traverse->traverse_mask(); 5809 5810 if ((traverse_mask 5811 & (Traverse::traverse_types | Traverse::traverse_expressions)) 5812 != 0) 5813 { 5814 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT) 5815 return TRAVERSE_EXIT; 5816 } 5817 5818 // FIXME: We should check traverse_functions here if nested 5819 // functions are stored in block bindings. 5820 if (this->block_ != NULL 5821 && (traverse_mask 5822 & (Traverse::traverse_variables 5823 | Traverse::traverse_constants 5824 | Traverse::traverse_blocks 5825 | Traverse::traverse_statements 5826 | Traverse::traverse_expressions 5827 | Traverse::traverse_types)) != 0) 5828 { 5829 if (this->block_->traverse(traverse) == TRAVERSE_EXIT) 5830 return TRAVERSE_EXIT; 5831 } 5832 5833 return TRAVERSE_CONTINUE; 5834 } 5835 5836 // Work out types for unspecified variables and constants. 5837 5838 void 5839 Function::determine_types() 5840 { 5841 if (this->block_ != NULL) 5842 this->block_->determine_types(); 5843 } 5844 5845 // Return the function descriptor, the value you get when you refer to 5846 // the function in Go code without calling it. 5847 5848 Expression* 5849 Function::descriptor(Gogo*, Named_object* no) 5850 { 5851 go_assert(!this->is_method()); 5852 go_assert(this->closure_var_ == NULL); 5853 if (this->descriptor_ == NULL) 5854 this->descriptor_ = Expression::make_func_descriptor(no); 5855 return this->descriptor_; 5856 } 5857 5858 // Get a pointer to the variable representing the defer stack for this 5859 // function, making it if necessary. The value of the variable is set 5860 // by the runtime routines to true if the function is returning, 5861 // rather than panicing through. A pointer to this variable is used 5862 // as a marker for the functions on the defer stack associated with 5863 // this function. A function-specific variable permits inlining a 5864 // function which uses defer. 5865 5866 Expression* 5867 Function::defer_stack(Location location) 5868 { 5869 if (this->defer_stack_ == NULL) 5870 { 5871 Type* t = Type::lookup_bool_type(); 5872 Expression* n = Expression::make_boolean(false, location); 5873 this->defer_stack_ = Statement::make_temporary(t, n, location); 5874 this->defer_stack_->set_is_address_taken(); 5875 } 5876 Expression* ref = Expression::make_temporary_reference(this->defer_stack_, 5877 location); 5878 return Expression::make_unary(OPERATOR_AND, ref, location); 5879 } 5880 5881 // Export the function. 5882 5883 void 5884 Function::export_func(Export* exp, const Named_object* no) const 5885 { 5886 Block* block = NULL; 5887 if (this->export_for_inlining()) 5888 block = this->block_; 5889 Function::export_func_with_type(exp, no, this->type_, this->results_, 5890 this->is_method() && this->nointerface(), 5891 this->asm_name(), block, this->location_); 5892 } 5893 5894 // Export a function with a type. 5895 5896 void 5897 Function::export_func_with_type(Export* exp, const Named_object* no, 5898 const Function_type* fntype, 5899 Function::Results* result_vars, 5900 bool nointerface, const std::string& asm_name, 5901 Block* block, Location loc) 5902 { 5903 exp->write_c_string("func "); 5904 5905 if (nointerface) 5906 { 5907 go_assert(fntype->is_method()); 5908 exp->write_c_string("/*nointerface*/ "); 5909 } 5910 5911 if (!asm_name.empty()) 5912 { 5913 exp->write_c_string("/*asm "); 5914 exp->write_string(asm_name); 5915 exp->write_c_string(" */ "); 5916 } 5917 5918 if (fntype->is_method()) 5919 { 5920 exp->write_c_string("("); 5921 const Typed_identifier* receiver = fntype->receiver(); 5922 exp->write_name(receiver->name()); 5923 exp->write_escape(receiver->note()); 5924 exp->write_c_string(" "); 5925 exp->write_type(receiver->type()->unalias()); 5926 exp->write_c_string(") "); 5927 } 5928 5929 if (no->package() != NULL && !fntype->is_method()) 5930 { 5931 char buf[50]; 5932 snprintf(buf, sizeof buf, "<p%d>", exp->package_index(no->package())); 5933 exp->write_c_string(buf); 5934 } 5935 5936 const std::string& name(no->name()); 5937 if (!Gogo::is_hidden_name(name)) 5938 exp->write_string(name); 5939 else 5940 { 5941 exp->write_c_string("."); 5942 exp->write_string(Gogo::unpack_hidden_name(name)); 5943 } 5944 5945 exp->write_c_string(" ("); 5946 const Typed_identifier_list* parameters = fntype->parameters(); 5947 if (parameters != NULL) 5948 { 5949 size_t i = 0; 5950 bool is_varargs = fntype->is_varargs(); 5951 bool first = true; 5952 for (Typed_identifier_list::const_iterator p = parameters->begin(); 5953 p != parameters->end(); 5954 ++p, ++i) 5955 { 5956 if (first) 5957 first = false; 5958 else 5959 exp->write_c_string(", "); 5960 exp->write_name(p->name()); 5961 exp->write_escape(p->note()); 5962 exp->write_c_string(" "); 5963 if (!is_varargs || p + 1 != parameters->end()) 5964 exp->write_type(p->type()); 5965 else 5966 { 5967 exp->write_c_string("..."); 5968 exp->write_type(p->type()->array_type()->element_type()); 5969 } 5970 } 5971 } 5972 exp->write_c_string(")"); 5973 5974 const Typed_identifier_list* result_decls = fntype->results(); 5975 if (result_decls != NULL) 5976 { 5977 if (result_decls->size() == 1 5978 && result_decls->begin()->name().empty() 5979 && block == NULL) 5980 { 5981 exp->write_c_string(" "); 5982 exp->write_type(result_decls->begin()->type()); 5983 } 5984 else 5985 { 5986 exp->write_c_string(" ("); 5987 bool first = true; 5988 Results::const_iterator pr; 5989 if (result_vars != NULL) 5990 pr = result_vars->begin(); 5991 for (Typed_identifier_list::const_iterator pd = result_decls->begin(); 5992 pd != result_decls->end(); 5993 ++pd) 5994 { 5995 if (first) 5996 first = false; 5997 else 5998 exp->write_c_string(", "); 5999 // We only use pr->name, which may be artificial, if 6000 // need it for inlining. 6001 if (block == NULL || result_vars == NULL) 6002 exp->write_name(pd->name()); 6003 else 6004 exp->write_name((*pr)->name()); 6005 exp->write_escape(pd->note()); 6006 exp->write_c_string(" "); 6007 exp->write_type(pd->type()); 6008 if (result_vars != NULL) 6009 ++pr; 6010 } 6011 if (result_vars != NULL) 6012 go_assert(pr == result_vars->end()); 6013 exp->write_c_string(")"); 6014 } 6015 } 6016 6017 if (block == NULL) 6018 exp->write_c_string("\n"); 6019 else 6020 { 6021 int indent = 1; 6022 if (fntype->is_method()) 6023 indent++; 6024 6025 Export_function_body efb(exp, indent); 6026 6027 efb.indent(); 6028 efb.write_c_string("// "); 6029 efb.write_string(Linemap::location_to_file(block->start_location())); 6030 efb.write_char(':'); 6031 char buf[100]; 6032 snprintf(buf, sizeof buf, "%d", Linemap::location_to_line(loc)); 6033 efb.write_c_string(buf); 6034 efb.write_char('\n'); 6035 block->export_block(&efb); 6036 6037 const std::string& body(efb.body()); 6038 6039 snprintf(buf, sizeof buf, " <inl:%lu>\n", 6040 static_cast<unsigned long>(body.length())); 6041 exp->write_c_string(buf); 6042 6043 exp->write_string(body); 6044 } 6045 } 6046 6047 // Import a function. 6048 6049 bool 6050 Function::import_func(Import* imp, std::string* pname, 6051 Package** ppkg, bool* pis_exported, 6052 Typed_identifier** preceiver, 6053 Typed_identifier_list** pparameters, 6054 Typed_identifier_list** presults, 6055 bool* is_varargs, 6056 bool* nointerface, 6057 std::string* asm_name, 6058 std::string* body) 6059 { 6060 imp->require_c_string("func "); 6061 6062 *nointerface = false; 6063 while (imp->match_c_string("/*")) 6064 { 6065 imp->advance(2); 6066 if (imp->match_c_string("nointerface")) 6067 { 6068 imp->require_c_string("nointerface*/ "); 6069 *nointerface = true; 6070 } 6071 else if (imp->match_c_string("asm")) 6072 { 6073 imp->require_c_string("asm "); 6074 *asm_name = imp->read_identifier(); 6075 imp->require_c_string(" */ "); 6076 } 6077 else 6078 { 6079 go_error_at(imp->location(), 6080 "import error at %d: unrecognized function comment", 6081 imp->pos()); 6082 return false; 6083 } 6084 } 6085 6086 if (*nointerface) 6087 { 6088 // Only a method can be nointerface. 6089 go_assert(imp->peek_char() == '('); 6090 } 6091 6092 *preceiver = NULL; 6093 if (imp->peek_char() == '(') 6094 { 6095 imp->require_c_string("("); 6096 std::string name = imp->read_name(); 6097 std::string escape_note = imp->read_escape(); 6098 imp->require_c_string(" "); 6099 Type* rtype = imp->read_type(); 6100 *preceiver = new Typed_identifier(name, rtype, imp->location()); 6101 (*preceiver)->set_note(escape_note); 6102 imp->require_c_string(") "); 6103 } 6104 6105 if (!Import::read_qualified_identifier(imp, pname, ppkg, pis_exported)) 6106 { 6107 go_error_at(imp->location(), 6108 "import error at %d: bad function name in export data", 6109 imp->pos()); 6110 return false; 6111 } 6112 6113 Typed_identifier_list* parameters; 6114 *is_varargs = false; 6115 imp->require_c_string(" ("); 6116 if (imp->peek_char() == ')') 6117 parameters = NULL; 6118 else 6119 { 6120 parameters = new Typed_identifier_list(); 6121 while (true) 6122 { 6123 std::string name = imp->read_name(); 6124 std::string escape_note = imp->read_escape(); 6125 imp->require_c_string(" "); 6126 6127 if (imp->match_c_string("...")) 6128 { 6129 imp->advance(3); 6130 *is_varargs = true; 6131 } 6132 6133 Type* ptype = imp->read_type(); 6134 if (*is_varargs) 6135 ptype = Type::make_array_type(ptype, NULL); 6136 Typed_identifier t = Typed_identifier(name, ptype, imp->location()); 6137 t.set_note(escape_note); 6138 parameters->push_back(t); 6139 if (imp->peek_char() != ',') 6140 break; 6141 go_assert(!*is_varargs); 6142 imp->require_c_string(", "); 6143 } 6144 } 6145 imp->require_c_string(")"); 6146 *pparameters = parameters; 6147 6148 Typed_identifier_list* results; 6149 if (imp->peek_char() != ' ' || imp->match_c_string(" <inl")) 6150 results = NULL; 6151 else 6152 { 6153 results = new Typed_identifier_list(); 6154 imp->require_c_string(" "); 6155 if (imp->peek_char() != '(') 6156 { 6157 Type* rtype = imp->read_type(); 6158 results->push_back(Typed_identifier("", rtype, imp->location())); 6159 } 6160 else 6161 { 6162 imp->require_c_string("("); 6163 while (true) 6164 { 6165 std::string name = imp->read_name(); 6166 std::string note = imp->read_escape(); 6167 imp->require_c_string(" "); 6168 Type* rtype = imp->read_type(); 6169 Typed_identifier t = Typed_identifier(name, rtype, 6170 imp->location()); 6171 t.set_note(note); 6172 results->push_back(t); 6173 if (imp->peek_char() != ',') 6174 break; 6175 imp->require_c_string(", "); 6176 } 6177 imp->require_c_string(")"); 6178 } 6179 } 6180 *presults = results; 6181 6182 if (!imp->match_c_string(" <inl:")) 6183 { 6184 imp->require_semicolon_if_old_version(); 6185 imp->require_c_string("\n"); 6186 body->clear(); 6187 } 6188 else 6189 { 6190 imp->require_c_string(" <inl:"); 6191 std::string lenstr; 6192 int c; 6193 while (true) 6194 { 6195 c = imp->peek_char(); 6196 if (c < '0' || c > '9') 6197 break; 6198 lenstr += c; 6199 imp->get_char(); 6200 } 6201 imp->require_c_string(">\n"); 6202 6203 errno = 0; 6204 char* end; 6205 long llen = strtol(lenstr.c_str(), &end, 10); 6206 if (*end != '\0' 6207 || llen < 0 6208 || (llen == LONG_MAX && errno == ERANGE)) 6209 { 6210 go_error_at(imp->location(), "invalid inline function length %s", 6211 lenstr.c_str()); 6212 return false; 6213 } 6214 6215 imp->read(static_cast<size_t>(llen), body); 6216 } 6217 6218 return true; 6219 } 6220 6221 // Get the backend name. 6222 6223 void 6224 Function::backend_name(Gogo* gogo, Named_object* no, Backend_name *bname) 6225 { 6226 if (!this->asm_name_.empty()) 6227 bname->set_asm_name(this->asm_name_); 6228 else if (no->package() == NULL && no->name() == gogo->get_init_fn_name()) 6229 { 6230 // These names appear in the export data and are used 6231 // directly in the assembler code. If we change this here 6232 // we need to change Gogo::init_imports. 6233 bname->set_asm_name(no->name()); 6234 } 6235 else if (this->enclosing_ != NULL) 6236 { 6237 // Rewrite the nested name to use the enclosing function name. 6238 // We don't do this earlier because we just store simple names 6239 // in a Named_object, not Backend_names. 6240 6241 // The name was set by nested_function_name, which always 6242 // appends ..funcNNN. We want that to be our suffix. 6243 size_t pos = no->name().find("..func"); 6244 go_assert(pos != std::string::npos); 6245 6246 Named_object* enclosing = this->enclosing_; 6247 while (true) 6248 { 6249 Named_object* parent = enclosing->func_value()->enclosing(); 6250 if (parent == NULL) 6251 break; 6252 enclosing = parent; 6253 } 6254 6255 Type* rtype = NULL; 6256 if (enclosing->func_value()->type()->is_method()) 6257 rtype = enclosing->func_value()->type()->receiver()->type(); 6258 gogo->function_backend_name(enclosing->name(), enclosing->package(), 6259 rtype, bname); 6260 bname->append_suffix(no->name().substr(pos)); 6261 } 6262 else 6263 { 6264 Type* rtype = NULL; 6265 if (this->type_->is_method()) 6266 rtype = this->type_->receiver()->type(); 6267 gogo->function_backend_name(no->name(), no->package(), rtype, bname); 6268 } 6269 } 6270 6271 // Get the backend representation. 6272 6273 Bfunction* 6274 Function::get_or_make_decl(Gogo* gogo, Named_object* no) 6275 { 6276 if (this->fndecl_ == NULL) 6277 { 6278 unsigned int flags = 0; 6279 if (no->package() != NULL) 6280 { 6281 // Functions defined in other packages must be visible. 6282 flags |= Backend::function_is_visible; 6283 } 6284 else if (this->enclosing_ != NULL || Gogo::is_thunk(no)) 6285 ; 6286 else if (Gogo::unpack_hidden_name(no->name()) == "init" 6287 && !this->type_->is_method()) 6288 ; 6289 else if (no->name() == gogo->get_init_fn_name()) 6290 flags |= Backend::function_is_visible; 6291 else if (Gogo::unpack_hidden_name(no->name()) == "main" 6292 && gogo->is_main_package()) 6293 flags |= Backend::function_is_visible; 6294 // Methods have to be public even if they are hidden because 6295 // they can be pulled into type descriptors when using 6296 // anonymous fields. 6297 else if (!Gogo::is_hidden_name(no->name()) 6298 || this->type_->is_method()) 6299 { 6300 if (!this->is_unnamed_type_stub_method_) 6301 flags |= Backend::function_is_visible; 6302 } 6303 6304 if (!this->asm_name_.empty()) 6305 { 6306 // If an assembler name is explicitly specified, there must 6307 // be some reason to refer to the symbol from a different 6308 // object file. 6309 flags |= Backend::function_is_visible; 6310 } 6311 6312 // If an inline body refers to this function, then it 6313 // needs to be visible in the symbol table. 6314 if (this->is_referenced_by_inline_) 6315 flags |= Backend::function_is_visible; 6316 6317 // A go:linkname directive can be used to force a function to be 6318 // visible. 6319 if (this->is_exported_by_linkname_) 6320 flags |= Backend::function_is_visible; 6321 6322 // If a function calls the predeclared recover function, we 6323 // can't inline it, because recover behaves differently in a 6324 // function passed directly to defer. If this is a recover 6325 // thunk that we built to test whether a function can be 6326 // recovered, we can't inline it, because that will mess up 6327 // our return address comparison. 6328 bool is_inlinable = !(this->calls_recover_ || this->is_recover_thunk_); 6329 6330 // If a function calls __go_set_defer_retaddr, then mark it as 6331 // uninlinable. This prevents the GCC backend from splitting 6332 // the function; splitting the function is a bad idea because we 6333 // want the return address label to be in the same function as 6334 // the call. 6335 if (this->calls_defer_retaddr_) 6336 is_inlinable = false; 6337 6338 // Check the //go:noinline compiler directive. 6339 if ((this->pragmas_ & GOPRAGMA_NOINLINE) != 0) 6340 is_inlinable = false; 6341 6342 if (is_inlinable) 6343 flags |= Backend::function_is_inlinable; 6344 6345 // If this is a thunk created to call a function which calls 6346 // the predeclared recover function, we need to disable 6347 // stack splitting for the thunk. 6348 bool disable_split_stack = this->is_recover_thunk_; 6349 6350 // Check the //go:nosplit compiler directive. 6351 if ((this->pragmas_ & GOPRAGMA_NOSPLIT) != 0) 6352 disable_split_stack = true; 6353 6354 if (disable_split_stack) 6355 flags |= Backend::function_no_split_stack; 6356 6357 // This should go into a unique section if that has been 6358 // requested elsewhere, or if this is a nointerface function. 6359 // We want to put a nointerface function into a unique section 6360 // because there is a good chance that the linker garbage 6361 // collection can discard it. 6362 if (this->in_unique_section_ 6363 || (this->is_method() && this->nointerface())) 6364 flags |= Backend::function_in_unique_section; 6365 6366 if (this->is_inline_only_) 6367 flags |= Backend::function_only_inline; 6368 6369 Btype* functype = this->type_->get_backend_fntype(gogo); 6370 6371 Backend_name bname; 6372 this->backend_name(gogo, no, &bname); 6373 6374 this->fndecl_ = gogo->backend()->function(functype, 6375 bname.name(), 6376 bname.optional_asm_name(), 6377 flags, 6378 this->location()); 6379 } 6380 return this->fndecl_; 6381 } 6382 6383 // Get the backend name. 6384 6385 void 6386 Function_declaration::backend_name(Gogo* gogo, Named_object* no, 6387 Backend_name* bname) 6388 { 6389 if (!this->asm_name_.empty()) 6390 bname->set_asm_name(this->asm_name_); 6391 else 6392 { 6393 Type* rtype = NULL; 6394 if (this->fntype_->is_method()) 6395 rtype = this->fntype_->receiver()->type(); 6396 gogo->function_backend_name(no->name(), no->package(), rtype, bname); 6397 } 6398 } 6399 6400 // Get the backend representation. 6401 6402 Bfunction* 6403 Function_declaration::get_or_make_decl(Gogo* gogo, Named_object* no) 6404 { 6405 if (this->fndecl_ == NULL) 6406 { 6407 unsigned int flags = 6408 (Backend::function_is_visible 6409 | Backend::function_is_declaration 6410 | Backend::function_is_inlinable); 6411 6412 // Let Go code use an asm declaration to pick up a builtin 6413 // function. 6414 if (!this->asm_name_.empty()) 6415 { 6416 Bfunction* builtin_decl = 6417 gogo->backend()->lookup_builtin(this->asm_name_); 6418 if (builtin_decl != NULL) 6419 { 6420 this->fndecl_ = builtin_decl; 6421 return this->fndecl_; 6422 } 6423 6424 if (this->asm_name_ == "runtime.gopanic" 6425 || this->asm_name_.compare(0, 13, "runtime.panic") == 0 6426 || this->asm_name_.compare(0, 15, "runtime.goPanic") == 0 6427 || this->asm_name_ == "runtime.block") 6428 flags |= Backend::function_does_not_return; 6429 } 6430 6431 Btype* functype = this->fntype_->get_backend_fntype(gogo); 6432 6433 Backend_name bname; 6434 this->backend_name(gogo, no, &bname); 6435 6436 this->fndecl_ = gogo->backend()->function(functype, 6437 bname.name(), 6438 bname.optional_asm_name(), 6439 flags, 6440 this->location()); 6441 } 6442 6443 return this->fndecl_; 6444 } 6445 6446 // Build the descriptor for a function declaration. This won't 6447 // necessarily happen if the package has just a declaration for the 6448 // function and no other reference to it, but we may still need the 6449 // descriptor for references from other packages. 6450 void 6451 Function_declaration::build_backend_descriptor(Gogo* gogo) 6452 { 6453 if (this->descriptor_ != NULL) 6454 { 6455 Translate_context context(gogo, NULL, NULL, NULL); 6456 this->descriptor_->get_backend(&context); 6457 } 6458 } 6459 6460 // Check that the types used in this declaration's signature are defined. 6461 // Reports errors for any undefined type. 6462 6463 void 6464 Function_declaration::check_types() const 6465 { 6466 // Calling Type::base will give errors for any undefined types. 6467 Function_type* fntype = this->type(); 6468 if (fntype->receiver() != NULL) 6469 fntype->receiver()->type()->base(); 6470 if (fntype->parameters() != NULL) 6471 { 6472 const Typed_identifier_list* params = fntype->parameters(); 6473 for (Typed_identifier_list::const_iterator p = params->begin(); 6474 p != params->end(); 6475 ++p) 6476 p->type()->base(); 6477 } 6478 } 6479 6480 // Return the function's decl after it has been built. 6481 6482 Bfunction* 6483 Function::get_decl() const 6484 { 6485 go_assert(this->fndecl_ != NULL); 6486 return this->fndecl_; 6487 } 6488 6489 // Build the backend representation for the function code. 6490 6491 void 6492 Function::build(Gogo* gogo, Named_object* named_function) 6493 { 6494 Translate_context context(gogo, named_function, NULL, NULL); 6495 6496 // A list of parameter variables for this function. 6497 std::vector<Bvariable*> param_vars; 6498 6499 // Variables that need to be declared for this function and their 6500 // initial values. 6501 std::vector<Bvariable*> vars; 6502 std::vector<Expression*> var_inits; 6503 std::vector<Statement*> var_decls_stmts; 6504 for (Bindings::const_definitions_iterator p = 6505 this->block_->bindings()->begin_definitions(); 6506 p != this->block_->bindings()->end_definitions(); 6507 ++p) 6508 { 6509 Location loc = (*p)->location(); 6510 if ((*p)->is_variable() && (*p)->var_value()->is_parameter()) 6511 { 6512 Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function); 6513 Bvariable* parm_bvar = bvar; 6514 6515 // We always pass the receiver to a method as a pointer. If 6516 // the receiver is declared as a non-pointer type, then we 6517 // copy the value into a local variable. For direct interface 6518 // type we pack the pointer into the type. 6519 if ((*p)->var_value()->is_receiver() 6520 && (*p)->var_value()->type()->points_to() == NULL) 6521 { 6522 std::string name = (*p)->name() + ".pointer"; 6523 Type* var_type = (*p)->var_value()->type(); 6524 Variable* parm_var = 6525 new Variable(Type::make_pointer_type(var_type), NULL, false, 6526 true, false, loc); 6527 Named_object* parm_no = 6528 Named_object::make_variable(name, NULL, parm_var); 6529 parm_bvar = parm_no->get_backend_variable(gogo, named_function); 6530 6531 vars.push_back(bvar); 6532 6533 Expression* parm_ref = 6534 Expression::make_var_reference(parm_no, loc); 6535 Type* recv_type = (*p)->var_value()->type(); 6536 if (recv_type->is_direct_iface_type()) 6537 parm_ref = Expression::pack_direct_iface(recv_type, parm_ref, loc); 6538 else 6539 parm_ref = 6540 Expression::make_dereference(parm_ref, 6541 Expression::NIL_CHECK_NEEDED, 6542 loc); 6543 if ((*p)->var_value()->is_in_heap()) 6544 parm_ref = Expression::make_heap_expression(parm_ref, loc); 6545 var_inits.push_back(parm_ref); 6546 } 6547 else if ((*p)->var_value()->is_in_heap()) 6548 { 6549 // If we take the address of a parameter, then we need 6550 // to copy it into the heap. 6551 std::string parm_name = (*p)->name() + ".param"; 6552 Variable* parm_var = new Variable((*p)->var_value()->type(), NULL, 6553 false, true, false, loc); 6554 Named_object* parm_no = 6555 Named_object::make_variable(parm_name, NULL, parm_var); 6556 parm_bvar = parm_no->get_backend_variable(gogo, named_function); 6557 6558 vars.push_back(bvar); 6559 Expression* var_ref = 6560 Expression::make_var_reference(parm_no, loc); 6561 var_ref = Expression::make_heap_expression(var_ref, loc); 6562 var_inits.push_back(var_ref); 6563 } 6564 param_vars.push_back(parm_bvar); 6565 } 6566 else if ((*p)->is_result_variable()) 6567 { 6568 Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function); 6569 6570 Type* type = (*p)->result_var_value()->type(); 6571 Expression* init; 6572 if (!(*p)->result_var_value()->is_in_heap()) 6573 { 6574 Btype* btype = type->get_backend(gogo); 6575 Bexpression* binit = gogo->backend()->zero_expression(btype); 6576 init = Expression::make_backend(binit, type, loc); 6577 } 6578 else 6579 init = Expression::make_allocation(type, loc); 6580 6581 vars.push_back(bvar); 6582 var_inits.push_back(init); 6583 } 6584 else if (this->defer_stack_ != NULL 6585 && (*p)->is_variable() 6586 && (*p)->var_value()->is_non_escaping_address_taken() 6587 && !(*p)->var_value()->is_in_heap()) 6588 { 6589 // Local variable captured by deferred closure needs to be live 6590 // until the end of the function. We create a top-level 6591 // declaration for it. 6592 // TODO: we don't need to do this if the variable is not captured 6593 // by the defer closure. There is no easy way to check it here, 6594 // so we do this for all address-taken variables for now. 6595 Variable* var = (*p)->var_value(); 6596 Temporary_statement* ts = 6597 Statement::make_temporary(var->type(), NULL, var->location()); 6598 ts->set_is_address_taken(); 6599 var->set_toplevel_decl(ts); 6600 var_decls_stmts.push_back(ts); 6601 } 6602 } 6603 if (!gogo->backend()->function_set_parameters(this->fndecl_, param_vars)) 6604 { 6605 go_assert(saw_errors()); 6606 return; 6607 } 6608 6609 // If we need a closure variable, make sure to create it. 6610 // It gets installed in the function as a side effect of creation. 6611 if (this->closure_var_ != NULL) 6612 { 6613 go_assert(this->closure_var_->var_value()->is_closure()); 6614 this->closure_var_->get_backend_variable(gogo, named_function); 6615 } 6616 6617 if (this->block_ != NULL) 6618 { 6619 // Declare variables if necessary. 6620 Bblock* var_decls = NULL; 6621 std::vector<Bstatement*> var_decls_bstmt_list; 6622 Bstatement* defer_init = NULL; 6623 if (!vars.empty() || this->defer_stack_ != NULL) 6624 { 6625 var_decls = 6626 gogo->backend()->block(this->fndecl_, NULL, vars, 6627 this->block_->start_location(), 6628 this->block_->end_location()); 6629 6630 if (this->defer_stack_ != NULL) 6631 { 6632 Translate_context dcontext(gogo, named_function, this->block_, 6633 var_decls); 6634 defer_init = this->defer_stack_->get_backend(&dcontext); 6635 var_decls_bstmt_list.push_back(defer_init); 6636 for (std::vector<Statement*>::iterator p = var_decls_stmts.begin(); 6637 p != var_decls_stmts.end(); 6638 ++p) 6639 { 6640 Bstatement* bstmt = (*p)->get_backend(&dcontext); 6641 var_decls_bstmt_list.push_back(bstmt); 6642 } 6643 } 6644 } 6645 6646 // Build the backend representation for all the statements in the 6647 // function. 6648 Translate_context bcontext(gogo, named_function, NULL, NULL); 6649 Bblock* code_block = this->block_->get_backend(&bcontext); 6650 6651 // Initialize variables if necessary. 6652 Translate_context icontext(gogo, named_function, this->block_, 6653 var_decls); 6654 std::vector<Bstatement*> init; 6655 go_assert(vars.size() == var_inits.size()); 6656 for (size_t i = 0; i < vars.size(); ++i) 6657 { 6658 Bexpression* binit = var_inits[i]->get_backend(&icontext); 6659 Bstatement* init_stmt = 6660 gogo->backend()->init_statement(this->fndecl_, vars[i], 6661 binit); 6662 init.push_back(init_stmt); 6663 } 6664 Bstatement* var_init = gogo->backend()->statement_list(init); 6665 6666 // Initialize all variables before executing this code block. 6667 Bstatement* code_stmt = gogo->backend()->block_statement(code_block); 6668 code_stmt = gogo->backend()->compound_statement(var_init, code_stmt); 6669 6670 // If we have a defer stack, initialize it at the start of a 6671 // function. 6672 Bstatement* except = NULL; 6673 Bstatement* fini = NULL; 6674 if (defer_init != NULL) 6675 { 6676 // Clean up the defer stack when we leave the function. 6677 this->build_defer_wrapper(gogo, named_function, &except, &fini); 6678 6679 // Wrap the code for this function in an exception handler to handle 6680 // defer calls. 6681 code_stmt = 6682 gogo->backend()->exception_handler_statement(code_stmt, 6683 except, fini, 6684 this->location_); 6685 } 6686 6687 // Stick the code into the block we built for the receiver, if 6688 // we built one. 6689 if (var_decls != NULL) 6690 { 6691 var_decls_bstmt_list.push_back(code_stmt); 6692 gogo->backend()->block_add_statements(var_decls, var_decls_bstmt_list); 6693 code_stmt = gogo->backend()->block_statement(var_decls); 6694 } 6695 6696 if (!gogo->backend()->function_set_body(this->fndecl_, code_stmt)) 6697 { 6698 go_assert(saw_errors()); 6699 return; 6700 } 6701 } 6702 6703 // If we created a descriptor for the function, make sure we emit it. 6704 if (this->descriptor_ != NULL) 6705 { 6706 Translate_context dcontext(gogo, NULL, NULL, NULL); 6707 this->descriptor_->get_backend(&dcontext); 6708 } 6709 } 6710 6711 // Build the wrappers around function code needed if the function has 6712 // any defer statements. This sets *EXCEPT to an exception handler 6713 // and *FINI to a finally handler. 6714 6715 void 6716 Function::build_defer_wrapper(Gogo* gogo, Named_object* named_function, 6717 Bstatement** except, Bstatement** fini) 6718 { 6719 Location end_loc = this->block_->end_location(); 6720 6721 // Add an exception handler. This is used if a panic occurs. Its 6722 // purpose is to stop the stack unwinding if a deferred function 6723 // calls recover. There are more details in 6724 // libgo/runtime/go-unwind.c. 6725 6726 std::vector<Bstatement*> stmts; 6727 Expression* call = Runtime::make_call(Runtime::CHECKDEFER, end_loc, 1, 6728 this->defer_stack(end_loc)); 6729 Translate_context context(gogo, named_function, NULL, NULL); 6730 Bexpression* defer = call->get_backend(&context); 6731 stmts.push_back(gogo->backend()->expression_statement(this->fndecl_, defer)); 6732 6733 Bstatement* ret_bstmt = this->return_value(gogo, named_function, end_loc); 6734 if (ret_bstmt != NULL) 6735 stmts.push_back(ret_bstmt); 6736 6737 go_assert(*except == NULL); 6738 *except = gogo->backend()->statement_list(stmts); 6739 6740 call = Runtime::make_call(Runtime::CHECKDEFER, end_loc, 1, 6741 this->defer_stack(end_loc)); 6742 defer = call->get_backend(&context); 6743 6744 call = Runtime::make_call(Runtime::DEFERRETURN, end_loc, 1, 6745 this->defer_stack(end_loc)); 6746 Bexpression* undefer = call->get_backend(&context); 6747 Bstatement* function_defer = 6748 gogo->backend()->function_defer_statement(this->fndecl_, undefer, defer, 6749 end_loc); 6750 stmts = std::vector<Bstatement*>(1, function_defer); 6751 if (this->type_->results() != NULL 6752 && !this->type_->results()->empty() 6753 && !this->type_->results()->front().name().empty()) 6754 { 6755 // If the result variables are named, and we are returning from 6756 // this function rather than panicing through it, we need to 6757 // return them again, because they might have been changed by a 6758 // defer function. The runtime routines set the defer_stack 6759 // variable to true if we are returning from this function. 6760 6761 ret_bstmt = this->return_value(gogo, named_function, end_loc); 6762 Bexpression* nil = Expression::make_nil(end_loc)->get_backend(&context); 6763 Bexpression* ret = 6764 gogo->backend()->compound_expression(ret_bstmt, nil, end_loc); 6765 Expression* ref = 6766 Expression::make_temporary_reference(this->defer_stack_, end_loc); 6767 Bexpression* bref = ref->get_backend(&context); 6768 ret = gogo->backend()->conditional_expression(this->fndecl_, 6769 NULL, bref, ret, NULL, 6770 end_loc); 6771 stmts.push_back(gogo->backend()->expression_statement(this->fndecl_, ret)); 6772 } 6773 6774 go_assert(*fini == NULL); 6775 *fini = gogo->backend()->statement_list(stmts); 6776 } 6777 6778 // Return the statement that assigns values to this function's result struct. 6779 6780 Bstatement* 6781 Function::return_value(Gogo* gogo, Named_object* named_function, 6782 Location location) const 6783 { 6784 const Typed_identifier_list* results = this->type_->results(); 6785 if (results == NULL || results->empty()) 6786 return NULL; 6787 6788 go_assert(this->results_ != NULL); 6789 if (this->results_->size() != results->size()) 6790 { 6791 go_assert(saw_errors()); 6792 return gogo->backend()->error_statement(); 6793 } 6794 6795 std::vector<Bexpression*> vals(results->size()); 6796 for (size_t i = 0; i < vals.size(); ++i) 6797 { 6798 Named_object* no = (*this->results_)[i]; 6799 Bvariable* bvar = no->get_backend_variable(gogo, named_function); 6800 Bexpression* val = gogo->backend()->var_expression(bvar, location); 6801 if (no->result_var_value()->is_in_heap()) 6802 { 6803 Btype* bt = no->result_var_value()->type()->get_backend(gogo); 6804 val = gogo->backend()->indirect_expression(bt, val, true, location); 6805 } 6806 vals[i] = val; 6807 } 6808 return gogo->backend()->return_statement(this->fndecl_, vals, location); 6809 } 6810 6811 // Class Block. 6812 6813 Block::Block(Block* enclosing, Location location) 6814 : enclosing_(enclosing), statements_(), 6815 bindings_(new Bindings(enclosing == NULL 6816 ? NULL 6817 : enclosing->bindings())), 6818 start_location_(location), 6819 end_location_(Linemap::unknown_location()) 6820 { 6821 } 6822 6823 // Add a statement to a block. 6824 6825 void 6826 Block::add_statement(Statement* statement) 6827 { 6828 this->statements_.push_back(statement); 6829 } 6830 6831 // Add a statement to the front of a block. This is slow but is only 6832 // used for reference counts of parameters. 6833 6834 void 6835 Block::add_statement_at_front(Statement* statement) 6836 { 6837 this->statements_.insert(this->statements_.begin(), statement); 6838 } 6839 6840 // Replace a statement in a block. 6841 6842 void 6843 Block::replace_statement(size_t index, Statement* s) 6844 { 6845 go_assert(index < this->statements_.size()); 6846 this->statements_[index] = s; 6847 } 6848 6849 // Add a statement before another statement. 6850 6851 void 6852 Block::insert_statement_before(size_t index, Statement* s) 6853 { 6854 go_assert(index < this->statements_.size()); 6855 this->statements_.insert(this->statements_.begin() + index, s); 6856 } 6857 6858 // Add a statement after another statement. 6859 6860 void 6861 Block::insert_statement_after(size_t index, Statement* s) 6862 { 6863 go_assert(index < this->statements_.size()); 6864 this->statements_.insert(this->statements_.begin() + index + 1, s); 6865 } 6866 6867 // Traverse the tree. 6868 6869 int 6870 Block::traverse(Traverse* traverse) 6871 { 6872 unsigned int traverse_mask = traverse->traverse_mask(); 6873 6874 if ((traverse_mask & Traverse::traverse_blocks) != 0) 6875 { 6876 int t = traverse->block(this); 6877 if (t == TRAVERSE_EXIT) 6878 return TRAVERSE_EXIT; 6879 else if (t == TRAVERSE_SKIP_COMPONENTS) 6880 return TRAVERSE_CONTINUE; 6881 } 6882 6883 if ((traverse_mask 6884 & (Traverse::traverse_variables 6885 | Traverse::traverse_constants 6886 | Traverse::traverse_expressions 6887 | Traverse::traverse_types)) != 0) 6888 { 6889 for (Bindings::const_definitions_iterator pb = 6890 this->bindings_->begin_definitions(); 6891 pb != this->bindings_->end_definitions(); 6892 ++pb) 6893 { 6894 if ((*pb)->traverse(traverse, false) == TRAVERSE_EXIT) 6895 return TRAVERSE_EXIT; 6896 } 6897 } 6898 6899 // No point in checking traverse_mask here--if we got here we always 6900 // want to walk the statements. The traversal can insert new 6901 // statements before or after the current statement. Inserting 6902 // statements before the current statement requires updating I via 6903 // the pointer; those statements will not be traversed. Any new 6904 // statements inserted after the current statement will be traversed 6905 // in their turn. 6906 for (size_t i = 0; i < this->statements_.size(); ++i) 6907 { 6908 if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT) 6909 return TRAVERSE_EXIT; 6910 } 6911 6912 return TRAVERSE_CONTINUE; 6913 } 6914 6915 // Work out types for unspecified variables and constants. 6916 6917 void 6918 Block::determine_types() 6919 { 6920 for (Bindings::const_definitions_iterator pb = 6921 this->bindings_->begin_definitions(); 6922 pb != this->bindings_->end_definitions(); 6923 ++pb) 6924 { 6925 if ((*pb)->is_variable()) 6926 (*pb)->var_value()->determine_type(); 6927 else if ((*pb)->is_const()) 6928 (*pb)->const_value()->determine_type(); 6929 } 6930 6931 for (std::vector<Statement*>::const_iterator ps = this->statements_.begin(); 6932 ps != this->statements_.end(); 6933 ++ps) 6934 (*ps)->determine_types(); 6935 } 6936 6937 // Return true if the statements in this block may fall through. 6938 6939 bool 6940 Block::may_fall_through() const 6941 { 6942 if (this->statements_.empty()) 6943 return true; 6944 return this->statements_.back()->may_fall_through(); 6945 } 6946 6947 // Write export data for a block. 6948 6949 void 6950 Block::export_block(Export_function_body* efb) 6951 { 6952 for (Block::iterator p = this->begin(); 6953 p != this->end(); 6954 ++p) 6955 { 6956 efb->indent(); 6957 6958 efb->increment_indent(); 6959 (*p)->export_statement(efb); 6960 efb->decrement_indent(); 6961 6962 Location loc = (*p)->location(); 6963 if ((*p)->is_block_statement()) 6964 { 6965 // For a block we put the start location on the first brace 6966 // in Block_statement::do_export_statement. Here we put the 6967 // end location on the final brace. 6968 loc = (*p)->block_statement()->block()->end_location(); 6969 } 6970 char buf[50]; 6971 snprintf(buf, sizeof buf, " //%d\n", Linemap::location_to_line(loc)); 6972 efb->write_c_string(buf); 6973 } 6974 } 6975 6976 // Add exported block data to SET, reading from BODY starting at OFF. 6977 // Returns whether the import succeeded. 6978 6979 bool 6980 Block::import_block(Block* set, Import_function_body *ifb, Location loc) 6981 { 6982 Location eloc = ifb->location(); 6983 Location sloc = loc; 6984 const std::string& body(ifb->body()); 6985 size_t off = ifb->off(); 6986 while (off < body.length()) 6987 { 6988 int indent = ifb->indent(); 6989 if (off + indent >= body.length()) 6990 { 6991 go_error_at(eloc, 6992 "invalid export data for %qs: insufficient indentation", 6993 ifb->name().c_str()); 6994 return false; 6995 } 6996 for (int i = 0; i < indent - 1; i++) 6997 { 6998 if (body[off + i] != ' ') 6999 { 7000 go_error_at(eloc, 7001 "invalid export data for %qs: bad indentation", 7002 ifb->name().c_str()); 7003 return false; 7004 } 7005 } 7006 7007 bool at_end = false; 7008 if (body[off + indent - 1] == '}') 7009 at_end = true; 7010 else if (body[off + indent - 1] != ' ') 7011 { 7012 go_error_at(eloc, 7013 "invalid export data for %qs: bad indentation", 7014 ifb->name().c_str()); 7015 return false; 7016 } 7017 7018 off += indent; 7019 7020 size_t nl = body.find('\n', off); 7021 if (nl == std::string::npos) 7022 { 7023 go_error_at(eloc, "invalid export data for %qs: missing newline", 7024 ifb->name().c_str()); 7025 return false; 7026 } 7027 7028 size_t lineno_pos = body.find(" //", off); 7029 if (lineno_pos == std::string::npos || lineno_pos >= nl) 7030 { 7031 go_error_at(eloc, "invalid export data for %qs: missing line number", 7032 ifb->name().c_str()); 7033 return false; 7034 } 7035 7036 unsigned int lineno = 0; 7037 for (size_t i = lineno_pos + 3; i < nl; ++i) 7038 { 7039 char c = body[i]; 7040 if (c < '0' || c > '9') 7041 { 7042 go_error_at(loc, 7043 "invalid export data for %qs: invalid line number", 7044 ifb->name().c_str()); 7045 return false; 7046 } 7047 lineno = lineno * 10 + c - '0'; 7048 } 7049 7050 ifb->gogo()->linemap()->start_line(lineno, 1); 7051 sloc = ifb->gogo()->linemap()->get_location(0); 7052 7053 if (at_end) 7054 { 7055 // An if statement can have an "else" following the "}", in 7056 // which case we want to leave the offset where it is, just 7057 // after the "}". We don't get the block ending location 7058 // quite right for if statements. 7059 if (body.compare(off, 6, " else ") != 0) 7060 off = nl + 1; 7061 break; 7062 } 7063 7064 ifb->set_off(off); 7065 Statement* s = Statement::import_statement(ifb, sloc); 7066 if (s == NULL) 7067 return false; 7068 7069 set->add_statement(s); 7070 7071 size_t at = ifb->off(); 7072 if (at < nl + 1) 7073 off = nl + 1; 7074 else 7075 off = at; 7076 } 7077 7078 ifb->set_off(off); 7079 set->set_end_location(sloc); 7080 return true; 7081 } 7082 7083 // Convert a block to the backend representation. 7084 7085 Bblock* 7086 Block::get_backend(Translate_context* context) 7087 { 7088 Gogo* gogo = context->gogo(); 7089 Named_object* function = context->function(); 7090 std::vector<Bvariable*> vars; 7091 vars.reserve(this->bindings_->size_definitions()); 7092 for (Bindings::const_definitions_iterator pv = 7093 this->bindings_->begin_definitions(); 7094 pv != this->bindings_->end_definitions(); 7095 ++pv) 7096 { 7097 if ((*pv)->is_variable() && !(*pv)->var_value()->is_parameter()) 7098 vars.push_back((*pv)->get_backend_variable(gogo, function)); 7099 } 7100 7101 go_assert(function != NULL); 7102 Bfunction* bfunction = 7103 function->func_value()->get_or_make_decl(gogo, function); 7104 Bblock* ret = context->backend()->block(bfunction, context->bblock(), 7105 vars, this->start_location_, 7106 this->end_location_); 7107 7108 Translate_context subcontext(gogo, function, this, ret); 7109 std::vector<Bstatement*> bstatements; 7110 bstatements.reserve(this->statements_.size()); 7111 for (std::vector<Statement*>::const_iterator p = this->statements_.begin(); 7112 p != this->statements_.end(); 7113 ++p) 7114 bstatements.push_back((*p)->get_backend(&subcontext)); 7115 7116 context->backend()->block_add_statements(ret, bstatements); 7117 7118 return ret; 7119 } 7120 7121 // Class Bindings_snapshot. 7122 7123 Bindings_snapshot::Bindings_snapshot(const Block* b, Location location) 7124 : block_(b), counts_(), location_(location) 7125 { 7126 while (b != NULL) 7127 { 7128 this->counts_.push_back(b->bindings()->size_definitions()); 7129 b = b->enclosing(); 7130 } 7131 } 7132 7133 // Report errors appropriate for a goto from B to this. 7134 7135 void 7136 Bindings_snapshot::check_goto_from(const Block* b, Location loc) 7137 { 7138 size_t dummy; 7139 if (!this->check_goto_block(loc, b, this->block_, &dummy)) 7140 return; 7141 this->check_goto_defs(loc, this->block_, 7142 this->block_->bindings()->size_definitions(), 7143 this->counts_[0]); 7144 } 7145 7146 // Report errors appropriate for a goto from this to B. 7147 7148 void 7149 Bindings_snapshot::check_goto_to(const Block* b) 7150 { 7151 size_t index; 7152 if (!this->check_goto_block(this->location_, this->block_, b, &index)) 7153 return; 7154 this->check_goto_defs(this->location_, b, this->counts_[index], 7155 b->bindings()->size_definitions()); 7156 } 7157 7158 // Report errors appropriate for a goto at LOC from BFROM to BTO. 7159 // Return true if all is well, false if we reported an error. If this 7160 // returns true, it sets *PINDEX to the number of blocks BTO is above 7161 // BFROM. 7162 7163 bool 7164 Bindings_snapshot::check_goto_block(Location loc, const Block* bfrom, 7165 const Block* bto, size_t* pindex) 7166 { 7167 // It is an error if BTO is not either BFROM or above BFROM. 7168 size_t index = 0; 7169 for (const Block* pb = bfrom; pb != bto; pb = pb->enclosing(), ++index) 7170 { 7171 if (pb == NULL) 7172 { 7173 go_error_at(loc, "goto jumps into block"); 7174 go_inform(bto->start_location(), "goto target block starts here"); 7175 return false; 7176 } 7177 } 7178 *pindex = index; 7179 return true; 7180 } 7181 7182 // Report errors appropriate for a goto at LOC ending at BLOCK, where 7183 // CFROM is the number of names defined at the point of the goto and 7184 // CTO is the number of names defined at the point of the label. 7185 7186 void 7187 Bindings_snapshot::check_goto_defs(Location loc, const Block* block, 7188 size_t cfrom, size_t cto) 7189 { 7190 if (cfrom < cto) 7191 { 7192 Bindings::const_definitions_iterator p = 7193 block->bindings()->begin_definitions(); 7194 for (size_t i = 0; i < cfrom; ++i) 7195 { 7196 go_assert(p != block->bindings()->end_definitions()); 7197 ++p; 7198 } 7199 go_assert(p != block->bindings()->end_definitions()); 7200 7201 for (; p != block->bindings()->end_definitions(); ++p) 7202 { 7203 if ((*p)->is_variable()) 7204 { 7205 std::string n = (*p)->message_name(); 7206 go_error_at(loc, "goto jumps over declaration of %qs", n.c_str()); 7207 go_inform((*p)->location(), "%qs defined here", n.c_str()); 7208 } 7209 } 7210 } 7211 } 7212 7213 // Class Function_declaration. 7214 7215 // Whether this declares a method. 7216 7217 bool 7218 Function_declaration::is_method() const 7219 { 7220 return this->fntype_->is_method(); 7221 } 7222 7223 // Whether this method should not be included in the type descriptor. 7224 7225 bool 7226 Function_declaration::nointerface() const 7227 { 7228 go_assert(this->is_method()); 7229 return (this->pragmas_ & GOPRAGMA_NOINTERFACE) != 0; 7230 } 7231 7232 // Record that this method should not be included in the type 7233 // descriptor. 7234 7235 void 7236 Function_declaration::set_nointerface() 7237 { 7238 this->pragmas_ |= GOPRAGMA_NOINTERFACE; 7239 } 7240 7241 // Set the receiver type. This is used to remove aliases. 7242 7243 void 7244 Function_declaration::set_receiver_type(Type* rtype) 7245 { 7246 Function_type* oft = this->fntype_; 7247 Typed_identifier* rec = new Typed_identifier(oft->receiver()->name(), 7248 rtype, 7249 oft->receiver()->location()); 7250 Typed_identifier_list* parameters = NULL; 7251 if (oft->parameters() != NULL) 7252 parameters = oft->parameters()->copy(); 7253 Typed_identifier_list* results = NULL; 7254 if (oft->results() != NULL) 7255 results = oft->results()->copy(); 7256 Function_type* nft = Type::make_function_type(rec, parameters, results, 7257 oft->location()); 7258 this->fntype_ = nft; 7259 } 7260 7261 // Import an inlinable function. This is used for an inlinable 7262 // function whose body is recorded in the export data. Parse the 7263 // export data into a Block and create a regular function using that 7264 // Block as its body. Redeclare this function declaration as the 7265 // function. 7266 7267 void 7268 Function_declaration::import_function_body(Gogo* gogo, Named_object* no) 7269 { 7270 go_assert(no->func_declaration_value() == this); 7271 go_assert(no->package() != NULL); 7272 const std::string& body(this->imported_body_); 7273 go_assert(!body.empty()); 7274 7275 // Read the "//FILE:LINE" comment starts the export data. 7276 7277 size_t indent = 1; 7278 if (this->is_method()) 7279 indent = 2; 7280 size_t i = 0; 7281 for (; i < indent; i++) 7282 { 7283 if (body.at(i) != ' ') 7284 { 7285 go_error_at(this->location_, 7286 "invalid export body for %qs: bad initial indentation", 7287 no->message_name().c_str()); 7288 return; 7289 } 7290 } 7291 7292 if (body.substr(i, 2) != "//") 7293 { 7294 go_error_at(this->location_, 7295 "invalid export body for %qs: missing file comment", 7296 no->message_name().c_str()); 7297 return; 7298 } 7299 7300 size_t colon = body.find(':', i + 2); 7301 size_t nl = body.find('\n', i + 2); 7302 if (nl == std::string::npos) 7303 { 7304 go_error_at(this->location_, 7305 "invalid export body for %qs: missing file name", 7306 no->message_name().c_str()); 7307 return; 7308 } 7309 if (colon == std::string::npos || nl < colon) 7310 { 7311 go_error_at(this->location_, 7312 "invalid export body for %qs: missing initial line number", 7313 no->message_name().c_str()); 7314 return; 7315 } 7316 7317 std::string file = body.substr(i + 2, colon - (i + 2)); 7318 std::string linestr = body.substr(colon + 1, nl - (colon + 1)); 7319 char* end; 7320 long linenol = strtol(linestr.c_str(), &end, 10); 7321 if (*end != '\0') 7322 { 7323 go_error_at(this->location_, 7324 "invalid export body for %qs: invalid initial line number", 7325 no->message_name().c_str()); 7326 return; 7327 } 7328 unsigned int lineno = static_cast<unsigned int>(linenol); 7329 7330 // Turn the file/line into a location. 7331 7332 char* alc = new char[file.length() + 1]; 7333 memcpy(alc, file.data(), file.length()); 7334 alc[file.length()] = '\0'; 7335 gogo->linemap()->start_file(alc, lineno); 7336 gogo->linemap()->start_line(lineno, 1); 7337 Location start_loc = gogo->linemap()->get_location(0); 7338 7339 // Define the function with an outer block that declares the 7340 // parameters. 7341 7342 Function_type* fntype = this->fntype_; 7343 7344 Block* outer = new Block(NULL, start_loc); 7345 7346 Function* fn = new Function(fntype, NULL, outer, start_loc); 7347 fn->set_is_inline_only(); 7348 7349 if (fntype->is_method()) 7350 { 7351 if (this->nointerface()) 7352 fn->set_nointerface(); 7353 const Typed_identifier* receiver = fntype->receiver(); 7354 Variable* recv_param = new Variable(receiver->type(), NULL, false, 7355 true, true, start_loc); 7356 7357 std::string rname = receiver->name(); 7358 unsigned rcounter = 0; 7359 7360 // We need to give a nameless receiver a name to avoid having it 7361 // clash with some other nameless param. FIXME. 7362 Gogo::rename_if_empty(&rname, "r", &rcounter); 7363 7364 outer->bindings()->add_variable(rname, NULL, recv_param); 7365 } 7366 7367 const Typed_identifier_list* params = fntype->parameters(); 7368 bool is_varargs = fntype->is_varargs(); 7369 unsigned pcounter = 0; 7370 if (params != NULL) 7371 { 7372 for (Typed_identifier_list::const_iterator p = params->begin(); 7373 p != params->end(); 7374 ++p) 7375 { 7376 Variable* param = new Variable(p->type(), NULL, false, true, false, 7377 start_loc); 7378 if (is_varargs && p + 1 == params->end()) 7379 param->set_is_varargs_parameter(); 7380 7381 std::string pname = p->name(); 7382 7383 // We need to give each nameless parameter a non-empty name to avoid 7384 // having it clash with some other nameless param. FIXME. 7385 Gogo::rename_if_empty(&pname, "p", &pcounter); 7386 7387 outer->bindings()->add_variable(pname, NULL, param); 7388 } 7389 } 7390 7391 fn->create_result_variables(gogo); 7392 7393 if (!fntype->is_method()) 7394 { 7395 const Package* package = no->package(); 7396 no = package->bindings()->add_function(no->name(), package, fn); 7397 } 7398 else 7399 { 7400 Named_type* rtype = fntype->receiver()->type()->deref()->named_type(); 7401 go_assert(rtype != NULL); 7402 no = rtype->add_method(no->name(), fn); 7403 const Package* package = rtype->named_object()->package(); 7404 package->bindings()->add_method(no); 7405 } 7406 7407 Import_function_body ifb(gogo, this->imp_, no, body, nl + 1, outer, indent); 7408 7409 if (!Block::import_block(outer, &ifb, start_loc)) 7410 return; 7411 7412 gogo->lower_block(no, outer); 7413 outer->determine_types(); 7414 7415 gogo->add_imported_inline_function(no); 7416 } 7417 7418 // Return the function descriptor. 7419 7420 Expression* 7421 Function_declaration::descriptor(Gogo*, Named_object* no) 7422 { 7423 go_assert(!this->fntype_->is_method()); 7424 if (this->descriptor_ == NULL) 7425 this->descriptor_ = Expression::make_func_descriptor(no); 7426 return this->descriptor_; 7427 } 7428 7429 // Class Variable. 7430 7431 Variable::Variable(Type* type, Expression* init, bool is_global, 7432 bool is_parameter, bool is_receiver, 7433 Location location) 7434 : type_(type), init_(init), preinit_(NULL), location_(location), 7435 toplevel_decl_(NULL), init_refs_(NULL), embeds_(NULL), backend_(NULL), 7436 is_global_(is_global), is_parameter_(is_parameter), is_closure_(false), 7437 is_receiver_(is_receiver), is_varargs_parameter_(false), 7438 is_global_sink_(false), is_used_(false), is_address_taken_(false), 7439 is_non_escaping_address_taken_(false), seen_(false), 7440 init_is_lowered_(false), init_is_flattened_(false), 7441 type_from_init_tuple_(false), type_from_range_index_(false), 7442 type_from_range_value_(false), type_from_chan_element_(false), 7443 is_type_switch_var_(false), determined_type_(false), 7444 in_unique_section_(false), is_referenced_by_inline_(false) 7445 { 7446 go_assert(type != NULL || init != NULL); 7447 go_assert(!is_parameter || init == NULL); 7448 } 7449 7450 // Traverse the initializer expression. 7451 7452 int 7453 Variable::traverse_expression(Traverse* traverse, unsigned int traverse_mask) 7454 { 7455 if (this->preinit_ != NULL) 7456 { 7457 if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT) 7458 return TRAVERSE_EXIT; 7459 } 7460 if (this->init_ != NULL 7461 && ((traverse_mask 7462 & (Traverse::traverse_expressions | Traverse::traverse_types)) 7463 != 0)) 7464 { 7465 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT) 7466 return TRAVERSE_EXIT; 7467 } 7468 return TRAVERSE_CONTINUE; 7469 } 7470 7471 // Lower the initialization expression after parsing is complete. 7472 7473 void 7474 Variable::lower_init_expression(Gogo* gogo, Named_object* function, 7475 Statement_inserter* inserter) 7476 { 7477 Named_object* dep = gogo->var_depends_on(this); 7478 if (dep != NULL && dep->is_variable()) 7479 dep->var_value()->lower_init_expression(gogo, function, inserter); 7480 7481 if (this->embeds_ != NULL) 7482 { 7483 // Now that we have seen any possible type aliases, convert the 7484 // go:embed directives into an initializer. 7485 go_assert(this->init_ == NULL && this->type_ != NULL); 7486 this->init_ = gogo->initializer_for_embeds(this->type_, this->embeds_, 7487 this->location_); 7488 delete this->embeds_; 7489 this->embeds_ = NULL; 7490 } 7491 7492 if (this->init_ != NULL && !this->init_is_lowered_) 7493 { 7494 if (this->seen_) 7495 { 7496 // We will give an error elsewhere, this is just to prevent 7497 // an infinite loop. 7498 return; 7499 } 7500 this->seen_ = true; 7501 7502 Statement_inserter global_inserter; 7503 if (this->is_global_) 7504 { 7505 global_inserter = Statement_inserter(gogo, this); 7506 inserter = &global_inserter; 7507 } 7508 7509 gogo->lower_expression(function, inserter, &this->init_); 7510 7511 this->seen_ = false; 7512 7513 this->init_is_lowered_ = true; 7514 } 7515 } 7516 7517 // Flatten the initialization expression after ordering evaluations. 7518 7519 void 7520 Variable::flatten_init_expression(Gogo* gogo, Named_object* function, 7521 Statement_inserter* inserter) 7522 { 7523 Named_object* dep = gogo->var_depends_on(this); 7524 if (dep != NULL && dep->is_variable()) 7525 dep->var_value()->flatten_init_expression(gogo, function, inserter); 7526 7527 if (this->init_ != NULL && !this->init_is_flattened_) 7528 { 7529 if (this->seen_) 7530 { 7531 // We will give an error elsewhere, this is just to prevent 7532 // an infinite loop. 7533 return; 7534 } 7535 this->seen_ = true; 7536 7537 Statement_inserter global_inserter; 7538 if (this->is_global_) 7539 { 7540 global_inserter = Statement_inserter(gogo, this); 7541 inserter = &global_inserter; 7542 } 7543 7544 gogo->flatten_expression(function, inserter, &this->init_); 7545 7546 // If an interface conversion is needed, we need a temporary 7547 // variable. 7548 if (this->type_ != NULL 7549 && !Type::are_identical(this->type_, this->init_->type(), 7550 Type::COMPARE_ERRORS | Type::COMPARE_TAGS, 7551 NULL) 7552 && this->init_->type()->interface_type() != NULL 7553 && !this->init_->is_multi_eval_safe()) 7554 { 7555 Temporary_statement* temp = 7556 Statement::make_temporary(NULL, this->init_, this->location_); 7557 inserter->insert(temp); 7558 this->init_ = Expression::make_temporary_reference(temp, 7559 this->location_); 7560 } 7561 7562 this->seen_ = false; 7563 this->init_is_flattened_ = true; 7564 } 7565 } 7566 7567 // Get the preinit block. 7568 7569 Block* 7570 Variable::preinit_block(Gogo* gogo) 7571 { 7572 go_assert(this->is_global_); 7573 if (this->preinit_ == NULL) 7574 this->preinit_ = new Block(NULL, this->location()); 7575 7576 // If a global variable has a preinitialization statement, then we 7577 // need to have an initialization function. 7578 gogo->set_need_init_fn(); 7579 7580 return this->preinit_; 7581 } 7582 7583 // Add a statement to be run before the initialization expression. 7584 7585 void 7586 Variable::add_preinit_statement(Gogo* gogo, Statement* s) 7587 { 7588 Block* b = this->preinit_block(gogo); 7589 b->add_statement(s); 7590 b->set_end_location(s->location()); 7591 } 7592 7593 // Whether this variable has a type. 7594 7595 bool 7596 Variable::has_type() const 7597 { 7598 if (this->type_ == NULL) 7599 return false; 7600 7601 // A variable created in a type switch case nil does not actually 7602 // have a type yet. It will be changed to use the initializer's 7603 // type in determine_type. 7604 if (this->is_type_switch_var_ 7605 && this->type_->is_nil_constant_as_type()) 7606 return false; 7607 7608 return true; 7609 } 7610 7611 // In an assignment which sets a variable to a tuple of EXPR, return 7612 // the type of the first element of the tuple. 7613 7614 Type* 7615 Variable::type_from_tuple(Expression* expr, bool report_error) const 7616 { 7617 if (expr->map_index_expression() != NULL) 7618 { 7619 Map_type* mt = expr->map_index_expression()->get_map_type(); 7620 if (mt == NULL) 7621 return Type::make_error_type(); 7622 return mt->val_type(); 7623 } 7624 else if (expr->receive_expression() != NULL) 7625 { 7626 Expression* channel = expr->receive_expression()->channel(); 7627 Type* channel_type = channel->type(); 7628 if (channel_type->channel_type() == NULL) 7629 return Type::make_error_type(); 7630 return channel_type->channel_type()->element_type(); 7631 } 7632 else 7633 { 7634 if (report_error) 7635 go_error_at(this->location(), "invalid tuple definition"); 7636 return Type::make_error_type(); 7637 } 7638 } 7639 7640 // Given EXPR used in a range clause, return either the index type or 7641 // the value type of the range, depending upon GET_INDEX_TYPE. 7642 7643 Type* 7644 Variable::type_from_range(Expression* expr, bool get_index_type, 7645 bool report_error) const 7646 { 7647 Type* t = expr->type(); 7648 if (t->array_type() != NULL 7649 || (t->points_to() != NULL 7650 && t->points_to()->array_type() != NULL 7651 && !t->points_to()->is_slice_type())) 7652 { 7653 if (get_index_type) 7654 return Type::lookup_integer_type("int"); 7655 else 7656 return t->deref()->array_type()->element_type(); 7657 } 7658 else if (t->is_string_type()) 7659 { 7660 if (get_index_type) 7661 return Type::lookup_integer_type("int"); 7662 else 7663 return Type::lookup_integer_type("int32"); 7664 } 7665 else if (t->map_type() != NULL) 7666 { 7667 if (get_index_type) 7668 return t->map_type()->key_type(); 7669 else 7670 return t->map_type()->val_type(); 7671 } 7672 else if (t->channel_type() != NULL) 7673 { 7674 if (get_index_type) 7675 return t->channel_type()->element_type(); 7676 else 7677 { 7678 if (report_error) 7679 go_error_at(this->location(), 7680 ("invalid definition of value variable " 7681 "for channel range")); 7682 return Type::make_error_type(); 7683 } 7684 } 7685 else 7686 { 7687 if (report_error) 7688 go_error_at(this->location(), "invalid type for range clause"); 7689 return Type::make_error_type(); 7690 } 7691 } 7692 7693 // EXPR should be a channel. Return the channel's element type. 7694 7695 Type* 7696 Variable::type_from_chan_element(Expression* expr, bool report_error) const 7697 { 7698 Type* t = expr->type(); 7699 if (t->channel_type() != NULL) 7700 return t->channel_type()->element_type(); 7701 else 7702 { 7703 if (report_error) 7704 go_error_at(this->location(), "expected channel"); 7705 return Type::make_error_type(); 7706 } 7707 } 7708 7709 // Return the type of the Variable. This may be called before 7710 // Variable::determine_type is called, which means that we may need to 7711 // get the type from the initializer. FIXME: If we combine lowering 7712 // with type determination, then this should be unnecessary. 7713 7714 Type* 7715 Variable::type() 7716 { 7717 // A variable in a type switch with a nil case will have the wrong 7718 // type here. This gets fixed up in determine_type, below. 7719 Type* type = this->type_; 7720 Expression* init = this->init_; 7721 if (this->is_type_switch_var_ 7722 && type != NULL 7723 && this->type_->is_nil_constant_as_type()) 7724 { 7725 Type_guard_expression* tge = this->init_->type_guard_expression(); 7726 go_assert(tge != NULL); 7727 init = tge->expr(); 7728 type = NULL; 7729 } 7730 7731 if (this->seen_) 7732 { 7733 if (this->type_ == NULL || !this->type_->is_error_type()) 7734 { 7735 go_error_at(this->location_, "variable initializer refers to itself"); 7736 this->type_ = Type::make_error_type(); 7737 } 7738 return this->type_; 7739 } 7740 7741 this->seen_ = true; 7742 7743 if (type != NULL) 7744 ; 7745 else if (this->type_from_init_tuple_) 7746 type = this->type_from_tuple(init, false); 7747 else if (this->type_from_range_index_ || this->type_from_range_value_) 7748 type = this->type_from_range(init, this->type_from_range_index_, false); 7749 else if (this->type_from_chan_element_) 7750 type = this->type_from_chan_element(init, false); 7751 else 7752 { 7753 go_assert(init != NULL); 7754 type = init->type(); 7755 go_assert(type != NULL); 7756 7757 // Variables should not have abstract types. 7758 if (type->is_abstract()) 7759 type = type->make_non_abstract_type(); 7760 7761 if (type->is_void_type()) 7762 type = Type::make_error_type(); 7763 } 7764 7765 this->seen_ = false; 7766 7767 return type; 7768 } 7769 7770 // Fetch the type from a const pointer, in which case it should have 7771 // been set already. 7772 7773 Type* 7774 Variable::type() const 7775 { 7776 go_assert(this->type_ != NULL); 7777 return this->type_; 7778 } 7779 7780 // Set the type if necessary. 7781 7782 void 7783 Variable::determine_type() 7784 { 7785 if (this->determined_type_) 7786 return; 7787 this->determined_type_ = true; 7788 7789 if (this->preinit_ != NULL) 7790 this->preinit_->determine_types(); 7791 7792 // A variable in a type switch with a nil case will have the wrong 7793 // type here. It will have an initializer which is a type guard. 7794 // We want to initialize it to the value without the type guard, and 7795 // use the type of that value as well. 7796 if (this->is_type_switch_var_ 7797 && this->type_ != NULL 7798 && this->type_->is_nil_constant_as_type()) 7799 { 7800 Type_guard_expression* tge = this->init_->type_guard_expression(); 7801 go_assert(tge != NULL); 7802 this->type_ = NULL; 7803 this->init_ = tge->expr(); 7804 } 7805 7806 if (this->init_ == NULL) 7807 go_assert(this->type_ != NULL && !this->type_->is_abstract()); 7808 else if (this->type_from_init_tuple_) 7809 { 7810 Expression *init = this->init_; 7811 init->determine_type_no_context(); 7812 this->type_ = this->type_from_tuple(init, true); 7813 this->init_ = NULL; 7814 } 7815 else if (this->type_from_range_index_ || this->type_from_range_value_) 7816 { 7817 Expression* init = this->init_; 7818 init->determine_type_no_context(); 7819 this->type_ = this->type_from_range(init, this->type_from_range_index_, 7820 true); 7821 this->init_ = NULL; 7822 } 7823 else if (this->type_from_chan_element_) 7824 { 7825 Expression* init = this->init_; 7826 init->determine_type_no_context(); 7827 this->type_ = this->type_from_chan_element(init, true); 7828 this->init_ = NULL; 7829 } 7830 else 7831 { 7832 Type_context context(this->type_, false); 7833 this->init_->determine_type(&context); 7834 if (this->type_ == NULL) 7835 { 7836 Type* type = this->init_->type(); 7837 go_assert(type != NULL); 7838 if (type->is_abstract()) 7839 type = type->make_non_abstract_type(); 7840 7841 if (type->is_void_type()) 7842 { 7843 go_error_at(this->location_, "variable has no type"); 7844 type = Type::make_error_type(); 7845 } 7846 else if (type->is_nil_type()) 7847 { 7848 go_error_at(this->location_, "variable defined to nil type"); 7849 type = Type::make_error_type(); 7850 } 7851 else if (type->is_call_multiple_result_type()) 7852 { 7853 go_error_at(this->location_, 7854 "single variable set to multiple-value function call"); 7855 type = Type::make_error_type(); 7856 } 7857 7858 this->type_ = type; 7859 } 7860 } 7861 } 7862 7863 // Get the initial value of a variable. This does not 7864 // consider whether the variable is in the heap--it returns the 7865 // initial value as though it were always stored in the stack. 7866 7867 Bexpression* 7868 Variable::get_init(Gogo* gogo, Named_object* function) 7869 { 7870 go_assert(this->preinit_ == NULL); 7871 Location loc = this->location(); 7872 if (this->init_ == NULL) 7873 { 7874 go_assert(!this->is_parameter_); 7875 if (this->is_global_ || this->is_in_heap()) 7876 return NULL; 7877 Btype* btype = this->type()->get_backend(gogo); 7878 return gogo->backend()->zero_expression(btype); 7879 } 7880 else 7881 { 7882 Translate_context context(gogo, function, NULL, NULL); 7883 Expression* init = Expression::make_cast(this->type(), this->init_, loc); 7884 return init->get_backend(&context); 7885 } 7886 } 7887 7888 // Get the initial value of a variable when a block is required. 7889 // VAR_DECL is the decl to set; it may be NULL for a sink variable. 7890 7891 Bstatement* 7892 Variable::get_init_block(Gogo* gogo, Named_object* function, 7893 Bvariable* var_decl) 7894 { 7895 go_assert(this->preinit_ != NULL); 7896 7897 // We want to add the variable assignment to the end of the preinit 7898 // block. 7899 7900 Translate_context context(gogo, function, NULL, NULL); 7901 Bblock* bblock = this->preinit_->get_backend(&context); 7902 Bfunction* bfunction = 7903 function->func_value()->get_or_make_decl(gogo, function); 7904 7905 // It's possible to have pre-init statements without an initializer 7906 // if the pre-init statements set the variable. 7907 Bstatement* decl_init = NULL; 7908 if (this->init_ != NULL) 7909 { 7910 if (var_decl == NULL) 7911 { 7912 Bexpression* init_bexpr = this->init_->get_backend(&context); 7913 decl_init = gogo->backend()->expression_statement(bfunction, 7914 init_bexpr); 7915 } 7916 else 7917 { 7918 Location loc = this->location(); 7919 Expression* val_expr = 7920 Expression::make_cast(this->type(), this->init_, loc); 7921 Bexpression* val = val_expr->get_backend(&context); 7922 Bexpression* var_ref = 7923 gogo->backend()->var_expression(var_decl, loc); 7924 decl_init = gogo->backend()->assignment_statement(bfunction, var_ref, 7925 val, loc); 7926 } 7927 } 7928 Bstatement* block_stmt = gogo->backend()->block_statement(bblock); 7929 if (decl_init != NULL) 7930 block_stmt = gogo->backend()->compound_statement(block_stmt, decl_init); 7931 return block_stmt; 7932 } 7933 7934 // Add an initializer reference. 7935 7936 void 7937 Variable::add_init_ref(Named_object* var) 7938 { 7939 if (this->init_refs_ == NULL) 7940 this->init_refs_ = new std::vector<Named_object*>; 7941 this->init_refs_->push_back(var); 7942 } 7943 7944 // Export the variable 7945 7946 void 7947 Variable::export_var(Export* exp, const Named_object* no) const 7948 { 7949 go_assert(this->is_global_); 7950 exp->write_c_string("var "); 7951 if (no->package() != NULL) 7952 { 7953 char buf[50]; 7954 snprintf(buf, sizeof buf, "<p%d>", exp->package_index(no->package())); 7955 exp->write_c_string(buf); 7956 } 7957 7958 if (!Gogo::is_hidden_name(no->name())) 7959 exp->write_string(no->name()); 7960 else 7961 { 7962 exp->write_c_string("."); 7963 exp->write_string(Gogo::unpack_hidden_name(no->name())); 7964 } 7965 7966 exp->write_c_string(" "); 7967 exp->write_type(this->type()); 7968 exp->write_c_string("\n"); 7969 } 7970 7971 // Import a variable. 7972 7973 bool 7974 Variable::import_var(Import* imp, std::string* pname, Package** ppkg, 7975 bool* pis_exported, Type** ptype) 7976 { 7977 imp->require_c_string("var "); 7978 if (!Import::read_qualified_identifier(imp, pname, ppkg, pis_exported)) 7979 { 7980 go_error_at(imp->location(), 7981 "import error at %d: bad variable name in export data", 7982 imp->pos()); 7983 return false; 7984 } 7985 imp->require_c_string(" "); 7986 *ptype = imp->read_type(); 7987 imp->require_semicolon_if_old_version(); 7988 imp->require_c_string("\n"); 7989 return true; 7990 } 7991 7992 // Convert a variable to the backend representation. 7993 7994 Bvariable* 7995 Variable::get_backend_variable(Gogo* gogo, Named_object* function, 7996 const Package* package, const std::string& name) 7997 { 7998 if (this->backend_ == NULL) 7999 { 8000 Backend* backend = gogo->backend(); 8001 Type* type = this->type_; 8002 if (type->is_error_type() 8003 || (type->is_undefined() 8004 && (!this->is_global_ || package == NULL))) 8005 this->backend_ = backend->error_variable(); 8006 else 8007 { 8008 bool is_parameter = this->is_parameter_; 8009 if (this->is_receiver_ && type->points_to() == NULL) 8010 is_parameter = false; 8011 if (this->is_in_heap()) 8012 { 8013 is_parameter = false; 8014 type = Type::make_pointer_type(type); 8015 } 8016 8017 Btype* btype = type->get_backend(gogo); 8018 8019 Bvariable* bvar; 8020 if (Map_type::is_zero_value(this)) 8021 bvar = Map_type::backend_zero_value(gogo); 8022 else if (this->is_global_) 8023 { 8024 Backend_name bname; 8025 gogo->global_var_backend_name(name, package, &bname); 8026 8027 bool is_hidden = Gogo::is_hidden_name(name); 8028 // Hack to export runtime.writeBarrier. FIXME. 8029 // This is because go:linkname doesn't work on variables. 8030 if (gogo->compiling_runtime() 8031 && bname.name() == "runtime.writeBarrier") 8032 is_hidden = false; 8033 8034 // If an inline body refers to this variable, then it 8035 // needs to be visible in the symbol table. 8036 if (this->is_referenced_by_inline_) 8037 is_hidden = false; 8038 8039 // If this variable is in a different package, then it 8040 // can't be treated as a hidden symbol. This case can 8041 // arise when an inlined function refers to a 8042 // package-scope unexported variable. 8043 if (package != NULL) 8044 is_hidden = false; 8045 8046 unsigned int flags = 0; 8047 if (this->is_address_taken_ 8048 || this->is_non_escaping_address_taken_) 8049 flags |= Backend::variable_address_is_taken; 8050 if (package != NULL) 8051 flags |= Backend::variable_is_external; 8052 if (is_hidden) 8053 flags |= Backend::variable_is_hidden; 8054 if (this->in_unique_section_) 8055 flags |= Backend::variable_in_unique_section; 8056 8057 // For some reason asm_name can't be the empty string 8058 // for global_variable, so we call asm_name rather than 8059 // optional_asm_name here. FIXME. 8060 8061 bvar = backend->global_variable(bname.name(), 8062 bname.asm_name(), 8063 btype, flags, 8064 this->location_); 8065 } 8066 else if (function == NULL) 8067 { 8068 go_assert(saw_errors()); 8069 bvar = backend->error_variable(); 8070 } 8071 else 8072 { 8073 const std::string n = Gogo::unpack_hidden_name(name); 8074 Bfunction* bfunction = function->func_value()->get_decl(); 8075 unsigned int flags = 0; 8076 if (this->is_non_escaping_address_taken_ 8077 && !this->is_in_heap()) 8078 flags |= Backend::variable_address_is_taken; 8079 if (this->is_closure()) 8080 bvar = backend->static_chain_variable(bfunction, n, btype, 8081 flags, this->location_); 8082 else if (is_parameter) 8083 bvar = backend->parameter_variable(bfunction, n, btype, 8084 flags, this->location_); 8085 else 8086 { 8087 Bvariable* bvar_decl = NULL; 8088 if (this->toplevel_decl_ != NULL) 8089 { 8090 Translate_context context(gogo, NULL, NULL, NULL); 8091 bvar_decl = this->toplevel_decl_->temporary_statement() 8092 ->get_backend_variable(&context); 8093 } 8094 bvar = backend->local_variable(bfunction, n, btype, 8095 bvar_decl, flags, 8096 this->location_); 8097 } 8098 } 8099 this->backend_ = bvar; 8100 } 8101 } 8102 return this->backend_; 8103 } 8104 8105 // Class Result_variable. 8106 8107 // Convert a result variable to the backend representation. 8108 8109 Bvariable* 8110 Result_variable::get_backend_variable(Gogo* gogo, Named_object* function, 8111 const std::string& name) 8112 { 8113 if (this->backend_ == NULL) 8114 { 8115 Backend* backend = gogo->backend(); 8116 Type* type = this->type_; 8117 if (type->is_error()) 8118 this->backend_ = backend->error_variable(); 8119 else 8120 { 8121 if (this->is_in_heap()) 8122 type = Type::make_pointer_type(type); 8123 Btype* btype = type->get_backend(gogo); 8124 Bfunction* bfunction = function->func_value()->get_decl(); 8125 std::string n = Gogo::unpack_hidden_name(name); 8126 unsigned int flags = 0; 8127 if (this->is_non_escaping_address_taken_ 8128 && !this->is_in_heap()) 8129 flags |= Backend::variable_address_is_taken; 8130 this->backend_ = backend->local_variable(bfunction, n, btype, 8131 NULL, flags, 8132 this->location_); 8133 } 8134 } 8135 return this->backend_; 8136 } 8137 8138 // Class Named_constant. 8139 8140 // Set the type of a named constant. This is only used to set the 8141 // type to an error type. 8142 8143 void 8144 Named_constant::set_type(Type* t) 8145 { 8146 go_assert(this->type_ == NULL || t->is_error_type()); 8147 this->type_ = t; 8148 } 8149 8150 // Traverse the initializer expression. 8151 8152 int 8153 Named_constant::traverse_expression(Traverse* traverse) 8154 { 8155 return Expression::traverse(&this->expr_, traverse); 8156 } 8157 8158 // Determine the type of the constant. 8159 8160 void 8161 Named_constant::determine_type() 8162 { 8163 if (this->type_ != NULL) 8164 { 8165 Type_context context(this->type_, false); 8166 this->expr_->determine_type(&context); 8167 } 8168 else 8169 { 8170 // A constant may have an abstract type. 8171 Type_context context(NULL, true); 8172 this->expr_->determine_type(&context); 8173 this->type_ = this->expr_->type(); 8174 go_assert(this->type_ != NULL); 8175 } 8176 } 8177 8178 // Indicate that we found and reported an error for this constant. 8179 8180 void 8181 Named_constant::set_error() 8182 { 8183 this->type_ = Type::make_error_type(); 8184 this->expr_ = Expression::make_error(this->location_); 8185 } 8186 8187 // Export a constant. 8188 8189 void 8190 Named_constant::export_const(Export* exp, const std::string& name) const 8191 { 8192 exp->write_c_string("const "); 8193 exp->write_string(name); 8194 exp->write_c_string(" "); 8195 if (!this->type_->is_abstract()) 8196 { 8197 exp->write_type(this->type_); 8198 exp->write_c_string(" "); 8199 } 8200 exp->write_c_string("= "); 8201 8202 Export_function_body efb(exp, 0); 8203 if (!this->type_->is_abstract()) 8204 efb.set_type_context(this->type_); 8205 this->expr()->export_expression(&efb); 8206 exp->write_string(efb.body()); 8207 8208 exp->write_c_string("\n"); 8209 } 8210 8211 // Import a constant. 8212 8213 void 8214 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype, 8215 Expression** pexpr) 8216 { 8217 imp->require_c_string("const "); 8218 *pname = imp->read_identifier(); 8219 imp->require_c_string(" "); 8220 if (imp->peek_char() == '=') 8221 *ptype = NULL; 8222 else 8223 { 8224 *ptype = imp->read_type(); 8225 imp->require_c_string(" "); 8226 } 8227 imp->require_c_string("= "); 8228 *pexpr = Expression::import_expression(imp, imp->location()); 8229 imp->require_semicolon_if_old_version(); 8230 imp->require_c_string("\n"); 8231 } 8232 8233 // Get the backend representation. 8234 8235 Bexpression* 8236 Named_constant::get_backend(Gogo* gogo, Named_object* const_no) 8237 { 8238 if (this->bconst_ == NULL) 8239 { 8240 Translate_context subcontext(gogo, NULL, NULL, NULL); 8241 Type* type = this->type(); 8242 Location loc = this->location(); 8243 8244 Expression* const_ref = Expression::make_const_reference(const_no, loc); 8245 Bexpression* const_decl = const_ref->get_backend(&subcontext); 8246 if (type != NULL && type->is_numeric_type()) 8247 { 8248 Btype* btype = type->get_backend(gogo); 8249 std::string name; 8250 if (const_no->package() == NULL) 8251 name = gogo->pkgpath(); 8252 else 8253 name = const_no->package()->pkgpath(); 8254 name.push_back('.'); 8255 name.append(Gogo::unpack_hidden_name(const_no->name())); 8256 const_decl = 8257 gogo->backend()->named_constant_expression(btype, name, 8258 const_decl, loc); 8259 } 8260 this->bconst_ = const_decl; 8261 } 8262 return this->bconst_; 8263 } 8264 8265 // Add a method. 8266 8267 Named_object* 8268 Type_declaration::add_method(const std::string& name, Function* function) 8269 { 8270 Named_object* ret = Named_object::make_function(name, NULL, function); 8271 this->methods_.push_back(ret); 8272 return ret; 8273 } 8274 8275 // Add a method declaration. 8276 8277 Named_object* 8278 Type_declaration::add_method_declaration(const std::string& name, 8279 Package* package, 8280 Function_type* type, 8281 Location location) 8282 { 8283 Named_object* ret = Named_object::make_function_declaration(name, package, 8284 type, location); 8285 this->methods_.push_back(ret); 8286 return ret; 8287 } 8288 8289 // Return whether any methods are defined. 8290 8291 bool 8292 Type_declaration::has_methods() const 8293 { 8294 return !this->methods_.empty(); 8295 } 8296 8297 // Define methods for the real type. 8298 8299 void 8300 Type_declaration::define_methods(Named_type* nt) 8301 { 8302 if (this->methods_.empty()) 8303 return; 8304 8305 while (nt->is_alias()) 8306 { 8307 Type *t = nt->real_type()->forwarded(); 8308 if (t->named_type() != NULL) 8309 nt = t->named_type(); 8310 else if (t->forward_declaration_type() != NULL) 8311 { 8312 Named_object* no = t->forward_declaration_type()->named_object(); 8313 Type_declaration* td = no->type_declaration_value(); 8314 td->methods_.insert(td->methods_.end(), this->methods_.begin(), 8315 this->methods_.end()); 8316 this->methods_.clear(); 8317 return; 8318 } 8319 else 8320 { 8321 for (std::vector<Named_object*>::const_iterator p = 8322 this->methods_.begin(); 8323 p != this->methods_.end(); 8324 ++p) 8325 go_error_at((*p)->location(), 8326 ("invalid receiver type " 8327 "(receiver must be a named type)")); 8328 return; 8329 } 8330 } 8331 8332 for (std::vector<Named_object*>::const_iterator p = this->methods_.begin(); 8333 p != this->methods_.end(); 8334 ++p) 8335 { 8336 if ((*p)->is_function_declaration() 8337 || !(*p)->func_value()->is_sink()) 8338 nt->add_existing_method(*p); 8339 } 8340 } 8341 8342 // We are using the type. Return true if we should issue a warning. 8343 8344 bool 8345 Type_declaration::using_type() 8346 { 8347 bool ret = !this->issued_warning_; 8348 this->issued_warning_ = true; 8349 return ret; 8350 } 8351 8352 // Class Unknown_name. 8353 8354 // Set the real named object. 8355 8356 void 8357 Unknown_name::set_real_named_object(Named_object* no) 8358 { 8359 go_assert(this->real_named_object_ == NULL); 8360 go_assert(!no->is_unknown()); 8361 this->real_named_object_ = no; 8362 } 8363 8364 // Class Named_object. 8365 8366 Named_object::Named_object(const std::string& name, 8367 const Package* package, 8368 Classification classification) 8369 : name_(name), package_(package), classification_(classification), 8370 is_redefinition_(false) 8371 { 8372 if (Gogo::is_sink_name(name)) 8373 go_assert(classification == NAMED_OBJECT_SINK); 8374 } 8375 8376 // Make an unknown name. This is used by the parser. The name must 8377 // be resolved later. Unknown names are only added in the current 8378 // package. 8379 8380 Named_object* 8381 Named_object::make_unknown_name(const std::string& name, 8382 Location location) 8383 { 8384 Named_object* named_object = new Named_object(name, NULL, 8385 NAMED_OBJECT_UNKNOWN); 8386 Unknown_name* value = new Unknown_name(location); 8387 named_object->u_.unknown_value = value; 8388 return named_object; 8389 } 8390 8391 // Make a constant. 8392 8393 Named_object* 8394 Named_object::make_constant(const Typed_identifier& tid, 8395 const Package* package, Expression* expr, 8396 int iota_value) 8397 { 8398 Named_object* named_object = new Named_object(tid.name(), package, 8399 NAMED_OBJECT_CONST); 8400 Named_constant* named_constant = new Named_constant(tid.type(), expr, 8401 iota_value, 8402 tid.location()); 8403 named_object->u_.const_value = named_constant; 8404 return named_object; 8405 } 8406 8407 // Make a named type. 8408 8409 Named_object* 8410 Named_object::make_type(const std::string& name, const Package* package, 8411 Type* type, Location location) 8412 { 8413 Named_object* named_object = new Named_object(name, package, 8414 NAMED_OBJECT_TYPE); 8415 Named_type* named_type = Type::make_named_type(named_object, type, location); 8416 named_object->u_.type_value = named_type; 8417 return named_object; 8418 } 8419 8420 // Make a type declaration. 8421 8422 Named_object* 8423 Named_object::make_type_declaration(const std::string& name, 8424 const Package* package, 8425 Location location) 8426 { 8427 Named_object* named_object = new Named_object(name, package, 8428 NAMED_OBJECT_TYPE_DECLARATION); 8429 Type_declaration* type_declaration = new Type_declaration(location); 8430 named_object->u_.type_declaration = type_declaration; 8431 return named_object; 8432 } 8433 8434 // Make a variable. 8435 8436 Named_object* 8437 Named_object::make_variable(const std::string& name, const Package* package, 8438 Variable* variable) 8439 { 8440 Named_object* named_object = new Named_object(name, package, 8441 NAMED_OBJECT_VAR); 8442 named_object->u_.var_value = variable; 8443 return named_object; 8444 } 8445 8446 // Make a result variable. 8447 8448 Named_object* 8449 Named_object::make_result_variable(const std::string& name, 8450 Result_variable* result) 8451 { 8452 Named_object* named_object = new Named_object(name, NULL, 8453 NAMED_OBJECT_RESULT_VAR); 8454 named_object->u_.result_var_value = result; 8455 return named_object; 8456 } 8457 8458 // Make a sink. This is used for the special blank identifier _. 8459 8460 Named_object* 8461 Named_object::make_sink() 8462 { 8463 return new Named_object("_", NULL, NAMED_OBJECT_SINK); 8464 } 8465 8466 // Make a named function. 8467 8468 Named_object* 8469 Named_object::make_function(const std::string& name, const Package* package, 8470 Function* function) 8471 { 8472 Named_object* named_object = new Named_object(name, package, 8473 NAMED_OBJECT_FUNC); 8474 named_object->u_.func_value = function; 8475 return named_object; 8476 } 8477 8478 // Make a function declaration. 8479 8480 Named_object* 8481 Named_object::make_function_declaration(const std::string& name, 8482 const Package* package, 8483 Function_type* fntype, 8484 Location location) 8485 { 8486 Named_object* named_object = new Named_object(name, package, 8487 NAMED_OBJECT_FUNC_DECLARATION); 8488 Function_declaration *func_decl = new Function_declaration(fntype, location); 8489 named_object->u_.func_declaration_value = func_decl; 8490 return named_object; 8491 } 8492 8493 // Make a package. 8494 8495 Named_object* 8496 Named_object::make_package(const std::string& alias, Package* package) 8497 { 8498 Named_object* named_object = new Named_object(alias, NULL, 8499 NAMED_OBJECT_PACKAGE); 8500 named_object->u_.package_value = package; 8501 return named_object; 8502 } 8503 8504 // Return the name to use in an error message. 8505 8506 std::string 8507 Named_object::message_name() const 8508 { 8509 if (this->package_ == NULL) 8510 return Gogo::message_name(this->name_); 8511 std::string ret; 8512 if (this->package_->has_package_name()) 8513 ret = this->package_->package_name(); 8514 else 8515 ret = this->package_->pkgpath(); 8516 ret = Gogo::message_name(ret); 8517 ret += '.'; 8518 ret += Gogo::message_name(this->name_); 8519 return ret; 8520 } 8521 8522 // Set the type when a declaration is defined. 8523 8524 void 8525 Named_object::set_type_value(Named_type* named_type) 8526 { 8527 go_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION); 8528 Type_declaration* td = this->u_.type_declaration; 8529 td->define_methods(named_type); 8530 unsigned int index; 8531 Named_object* in_function = td->in_function(&index); 8532 if (in_function != NULL) 8533 named_type->set_in_function(in_function, index); 8534 delete td; 8535 this->classification_ = NAMED_OBJECT_TYPE; 8536 this->u_.type_value = named_type; 8537 } 8538 8539 // Define a function which was previously declared. 8540 8541 void 8542 Named_object::set_function_value(Function* function) 8543 { 8544 go_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION); 8545 if (this->func_declaration_value()->has_descriptor()) 8546 { 8547 Expression* descriptor = 8548 this->func_declaration_value()->descriptor(NULL, NULL); 8549 function->set_descriptor(descriptor); 8550 } 8551 this->classification_ = NAMED_OBJECT_FUNC; 8552 // FIXME: We should free the old value. 8553 this->u_.func_value = function; 8554 } 8555 8556 // Declare an unknown object as a type declaration. 8557 8558 void 8559 Named_object::declare_as_type() 8560 { 8561 go_assert(this->classification_ == NAMED_OBJECT_UNKNOWN); 8562 Unknown_name* unk = this->u_.unknown_value; 8563 this->classification_ = NAMED_OBJECT_TYPE_DECLARATION; 8564 this->u_.type_declaration = new Type_declaration(unk->location()); 8565 delete unk; 8566 } 8567 8568 // Return the location of a named object. 8569 8570 Location 8571 Named_object::location() const 8572 { 8573 switch (this->classification_) 8574 { 8575 default: 8576 case NAMED_OBJECT_UNINITIALIZED: 8577 go_unreachable(); 8578 8579 case NAMED_OBJECT_ERRONEOUS: 8580 return Linemap::unknown_location(); 8581 8582 case NAMED_OBJECT_UNKNOWN: 8583 return this->unknown_value()->location(); 8584 8585 case NAMED_OBJECT_CONST: 8586 return this->const_value()->location(); 8587 8588 case NAMED_OBJECT_TYPE: 8589 return this->type_value()->location(); 8590 8591 case NAMED_OBJECT_TYPE_DECLARATION: 8592 return this->type_declaration_value()->location(); 8593 8594 case NAMED_OBJECT_VAR: 8595 return this->var_value()->location(); 8596 8597 case NAMED_OBJECT_RESULT_VAR: 8598 return this->result_var_value()->location(); 8599 8600 case NAMED_OBJECT_SINK: 8601 go_unreachable(); 8602 8603 case NAMED_OBJECT_FUNC: 8604 return this->func_value()->location(); 8605 8606 case NAMED_OBJECT_FUNC_DECLARATION: 8607 return this->func_declaration_value()->location(); 8608 8609 case NAMED_OBJECT_PACKAGE: 8610 return this->package_value()->location(); 8611 } 8612 } 8613 8614 // Traverse a Named_object. 8615 8616 int 8617 Named_object::traverse(Traverse* traverse, bool is_global) 8618 { 8619 const unsigned int traverse_mask = traverse->traverse_mask(); 8620 const unsigned int e_or_t = (Traverse::traverse_expressions 8621 | Traverse::traverse_types); 8622 const unsigned int e_or_t_or_s = (e_or_t 8623 | Traverse::traverse_statements); 8624 8625 int t = TRAVERSE_CONTINUE; 8626 switch (this->classification_) 8627 { 8628 case Named_object::NAMED_OBJECT_CONST: 8629 if ((traverse_mask & Traverse::traverse_constants) != 0) 8630 t = traverse->constant(this, is_global); 8631 if (t == TRAVERSE_CONTINUE 8632 && (traverse_mask & e_or_t) != 0) 8633 { 8634 Type* tc = this->const_value()->type(); 8635 if (tc != NULL) 8636 { 8637 if (Type::traverse(tc, traverse) == TRAVERSE_EXIT) 8638 return TRAVERSE_EXIT; 8639 } 8640 t = this->const_value()->traverse_expression(traverse); 8641 } 8642 break; 8643 8644 case Named_object::NAMED_OBJECT_VAR: 8645 case Named_object::NAMED_OBJECT_RESULT_VAR: 8646 if ((traverse_mask & Traverse::traverse_variables) != 0) 8647 t = traverse->variable(this); 8648 if (t == TRAVERSE_CONTINUE 8649 && (traverse_mask & e_or_t) != 0) 8650 { 8651 if (this->is_result_variable() || this->var_value()->has_type()) 8652 { 8653 Type* tv = (this->is_variable() 8654 ? this->var_value()->type() 8655 : this->result_var_value()->type()); 8656 if (tv != NULL) 8657 { 8658 if (Type::traverse(tv, traverse) == TRAVERSE_EXIT) 8659 return TRAVERSE_EXIT; 8660 } 8661 } 8662 } 8663 if (t == TRAVERSE_CONTINUE 8664 && (traverse_mask & e_or_t_or_s) != 0 8665 && this->is_variable()) 8666 t = this->var_value()->traverse_expression(traverse, 8667 traverse_mask); 8668 break; 8669 8670 case Named_object::NAMED_OBJECT_FUNC: 8671 if ((traverse_mask & Traverse::traverse_functions) != 0) 8672 t = traverse->function(this); 8673 if (t == TRAVERSE_CONTINUE 8674 && (traverse_mask 8675 & (Traverse::traverse_variables 8676 | Traverse::traverse_constants 8677 | Traverse::traverse_functions 8678 | Traverse::traverse_blocks 8679 | Traverse::traverse_statements 8680 | Traverse::traverse_expressions 8681 | Traverse::traverse_types)) != 0) 8682 t = this->func_value()->traverse(traverse); 8683 break; 8684 8685 case Named_object::NAMED_OBJECT_TYPE: 8686 if ((traverse_mask & e_or_t) != 0) 8687 t = Type::traverse(this->type_value(), traverse); 8688 break; 8689 8690 case Named_object::NAMED_OBJECT_PACKAGE: 8691 case Named_object::NAMED_OBJECT_FUNC_DECLARATION: 8692 case Named_object::NAMED_OBJECT_TYPE_DECLARATION: 8693 case Named_object::NAMED_OBJECT_UNKNOWN: 8694 case Named_object::NAMED_OBJECT_ERRONEOUS: 8695 break; 8696 8697 case Named_object::NAMED_OBJECT_SINK: 8698 go_unreachable(); 8699 8700 default: 8701 go_unreachable(); 8702 } 8703 8704 return t; 8705 } 8706 8707 // Export a named object. 8708 8709 void 8710 Named_object::export_named_object(Export* exp) const 8711 { 8712 switch (this->classification_) 8713 { 8714 default: 8715 case NAMED_OBJECT_UNINITIALIZED: 8716 case NAMED_OBJECT_UNKNOWN: 8717 go_unreachable(); 8718 8719 case NAMED_OBJECT_ERRONEOUS: 8720 break; 8721 8722 case NAMED_OBJECT_CONST: 8723 this->const_value()->export_const(exp, this->name_); 8724 break; 8725 8726 case NAMED_OBJECT_TYPE: 8727 // Types are handled by export::write_types. 8728 go_unreachable(); 8729 8730 case NAMED_OBJECT_TYPE_DECLARATION: 8731 go_error_at(this->type_declaration_value()->location(), 8732 "attempt to export %<%s%> which was declared but not defined", 8733 this->message_name().c_str()); 8734 break; 8735 8736 case NAMED_OBJECT_FUNC_DECLARATION: 8737 this->func_declaration_value()->export_func(exp, this); 8738 break; 8739 8740 case NAMED_OBJECT_VAR: 8741 this->var_value()->export_var(exp, this); 8742 break; 8743 8744 case NAMED_OBJECT_RESULT_VAR: 8745 case NAMED_OBJECT_SINK: 8746 go_unreachable(); 8747 8748 case NAMED_OBJECT_FUNC: 8749 this->func_value()->export_func(exp, this); 8750 break; 8751 } 8752 } 8753 8754 // Convert a variable to the backend representation. 8755 8756 Bvariable* 8757 Named_object::get_backend_variable(Gogo* gogo, Named_object* function) 8758 { 8759 if (this->classification_ == NAMED_OBJECT_VAR) 8760 return this->var_value()->get_backend_variable(gogo, function, 8761 this->package_, this->name_); 8762 else if (this->classification_ == NAMED_OBJECT_RESULT_VAR) 8763 return this->result_var_value()->get_backend_variable(gogo, function, 8764 this->name_); 8765 else 8766 go_unreachable(); 8767 } 8768 8769 void 8770 debug_go_named_object(Named_object* no) 8771 { 8772 if (no == NULL) 8773 { 8774 std::cerr << "<null>"; 8775 return; 8776 } 8777 std::cerr << "'" << no->name() << "': "; 8778 const char *tag; 8779 switch (no->classification()) 8780 { 8781 case Named_object::NAMED_OBJECT_UNINITIALIZED: 8782 tag = "uninitialized"; 8783 break; 8784 case Named_object::NAMED_OBJECT_ERRONEOUS: 8785 tag = "<error>"; 8786 break; 8787 case Named_object::NAMED_OBJECT_UNKNOWN: 8788 tag = "<unknown>"; 8789 break; 8790 case Named_object::NAMED_OBJECT_CONST: 8791 tag = "constant"; 8792 break; 8793 case Named_object::NAMED_OBJECT_TYPE: 8794 tag = "type"; 8795 break; 8796 case Named_object::NAMED_OBJECT_TYPE_DECLARATION: 8797 tag = "type_decl"; 8798 break; 8799 case Named_object::NAMED_OBJECT_VAR: 8800 tag = "var"; 8801 break; 8802 case Named_object::NAMED_OBJECT_RESULT_VAR: 8803 tag = "result_var"; 8804 break; 8805 case Named_object::NAMED_OBJECT_SINK: 8806 tag = "<sink>"; 8807 break; 8808 case Named_object::NAMED_OBJECT_FUNC: 8809 tag = "func"; 8810 break; 8811 case Named_object::NAMED_OBJECT_FUNC_DECLARATION: 8812 tag = "func_decl"; 8813 break; 8814 case Named_object::NAMED_OBJECT_PACKAGE: 8815 tag = "package"; 8816 break; 8817 default: 8818 tag = "<unknown named object classification>"; 8819 break; 8820 }; 8821 std::cerr << tag << "\n"; 8822 } 8823 8824 // Get the backend representation for this named object. 8825 8826 void 8827 Named_object::get_backend(Gogo* gogo, std::vector<Bexpression*>& const_decls, 8828 std::vector<Btype*>& type_decls, 8829 std::vector<Bfunction*>& func_decls) 8830 { 8831 // If this is a definition, avoid trying to get the backend 8832 // representation, as that can crash. 8833 if (this->is_redefinition_) 8834 { 8835 go_assert(saw_errors()); 8836 return; 8837 } 8838 8839 switch (this->classification_) 8840 { 8841 case NAMED_OBJECT_CONST: 8842 if (!Gogo::is_erroneous_name(this->name_)) 8843 const_decls.push_back(this->u_.const_value->get_backend(gogo, this)); 8844 break; 8845 8846 case NAMED_OBJECT_TYPE: 8847 { 8848 Named_type* named_type = this->u_.type_value; 8849 8850 // No need to do anything for aliases-- whatever has to be done 8851 // can be done for the alias target. 8852 if (named_type->is_alias()) 8853 break; 8854 8855 if (!Gogo::is_erroneous_name(this->name_)) 8856 type_decls.push_back(named_type->get_backend(gogo)); 8857 8858 // We need to produce a type descriptor for every named 8859 // type, and for a pointer to every named type, since 8860 // other files or packages might refer to them. We need 8861 // to do this even for hidden types, because they might 8862 // still be returned by some function. Simply calling the 8863 // type_descriptor method is enough to create the type 8864 // descriptor, even though we don't do anything with it. 8865 if (this->package_ == NULL && !saw_errors()) 8866 { 8867 named_type-> 8868 type_descriptor_pointer(gogo, Linemap::predeclared_location()); 8869 Type* pn = Type::make_pointer_type(named_type); 8870 pn->type_descriptor_pointer(gogo, Linemap::predeclared_location()); 8871 if (named_type->in_heap()) 8872 { 8873 named_type->gc_symbol_pointer(gogo); 8874 pn->gc_symbol_pointer(gogo); 8875 } 8876 } 8877 } 8878 break; 8879 8880 case NAMED_OBJECT_TYPE_DECLARATION: 8881 go_error_at(Linemap::unknown_location(), 8882 "reference to undefined type %qs", 8883 this->message_name().c_str()); 8884 return; 8885 8886 case NAMED_OBJECT_VAR: 8887 case NAMED_OBJECT_RESULT_VAR: 8888 case NAMED_OBJECT_SINK: 8889 go_unreachable(); 8890 8891 case NAMED_OBJECT_FUNC: 8892 { 8893 Function* func = this->u_.func_value; 8894 if (!Gogo::is_erroneous_name(this->name_)) 8895 func_decls.push_back(func->get_or_make_decl(gogo, this)); 8896 8897 if (func->block() != NULL) 8898 func->build(gogo, this); 8899 } 8900 break; 8901 8902 case NAMED_OBJECT_ERRONEOUS: 8903 break; 8904 8905 default: 8906 go_unreachable(); 8907 } 8908 } 8909 8910 // Class Bindings. 8911 8912 Bindings::Bindings(Bindings* enclosing) 8913 : enclosing_(enclosing), named_objects_(), bindings_() 8914 { 8915 } 8916 8917 // Clear imports. 8918 8919 void 8920 Bindings::clear_file_scope(Gogo* gogo) 8921 { 8922 Contour::iterator p = this->bindings_.begin(); 8923 while (p != this->bindings_.end()) 8924 { 8925 bool keep; 8926 if (p->second->package() != NULL) 8927 keep = false; 8928 else if (p->second->is_package()) 8929 keep = false; 8930 else if (p->second->is_function() 8931 && !p->second->func_value()->type()->is_method() 8932 && Gogo::unpack_hidden_name(p->second->name()) == "init") 8933 keep = false; 8934 else 8935 keep = true; 8936 8937 if (keep) 8938 ++p; 8939 else 8940 { 8941 gogo->add_file_block_name(p->second->name(), p->second->location()); 8942 p = this->bindings_.erase(p); 8943 } 8944 } 8945 } 8946 8947 // Look up a symbol. 8948 8949 Named_object* 8950 Bindings::lookup(const std::string& name) const 8951 { 8952 Contour::const_iterator p = this->bindings_.find(name); 8953 if (p != this->bindings_.end()) 8954 return p->second->resolve(); 8955 else if (this->enclosing_ != NULL) 8956 return this->enclosing_->lookup(name); 8957 else 8958 return NULL; 8959 } 8960 8961 // Look up a symbol locally. 8962 8963 Named_object* 8964 Bindings::lookup_local(const std::string& name) const 8965 { 8966 Contour::const_iterator p = this->bindings_.find(name); 8967 if (p == this->bindings_.end()) 8968 return NULL; 8969 return p->second; 8970 } 8971 8972 // Remove an object from a set of bindings. This is used for a 8973 // special case in thunks for functions which call recover. 8974 8975 void 8976 Bindings::remove_binding(Named_object* no) 8977 { 8978 Contour::iterator pb = this->bindings_.find(no->name()); 8979 go_assert(pb != this->bindings_.end()); 8980 this->bindings_.erase(pb); 8981 for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin(); 8982 pn != this->named_objects_.end(); 8983 ++pn) 8984 { 8985 if (*pn == no) 8986 { 8987 this->named_objects_.erase(pn); 8988 return; 8989 } 8990 } 8991 go_unreachable(); 8992 } 8993 8994 // Add a method to the list of objects. This is not added to the 8995 // lookup table. This is so that we have a single list of objects 8996 // declared at the top level, which we walk through when it's time to 8997 // convert to trees. 8998 8999 void 9000 Bindings::add_method(Named_object* method) 9001 { 9002 this->named_objects_.push_back(method); 9003 } 9004 9005 // Add a generic Named_object to a Contour. 9006 9007 Named_object* 9008 Bindings::add_named_object_to_contour(Contour* contour, 9009 Named_object* named_object) 9010 { 9011 go_assert(named_object == named_object->resolve()); 9012 const std::string& name(named_object->name()); 9013 go_assert(!Gogo::is_sink_name(name)); 9014 9015 std::pair<Contour::iterator, bool> ins = 9016 contour->insert(std::make_pair(name, named_object)); 9017 if (!ins.second) 9018 { 9019 // The name was already there. 9020 if (named_object->package() != NULL 9021 && ins.first->second->package() == named_object->package() 9022 && (ins.first->second->classification() 9023 == named_object->classification())) 9024 { 9025 // This is a second import of the same object. 9026 return ins.first->second; 9027 } 9028 ins.first->second = this->new_definition(ins.first->second, 9029 named_object); 9030 return ins.first->second; 9031 } 9032 else 9033 { 9034 // Don't push declarations on the list. We push them on when 9035 // and if we find the definitions. That way we genericize the 9036 // functions in order. 9037 if (!named_object->is_type_declaration() 9038 && !named_object->is_function_declaration() 9039 && !named_object->is_unknown()) 9040 this->named_objects_.push_back(named_object); 9041 return named_object; 9042 } 9043 } 9044 9045 // We had an existing named object OLD_OBJECT, and we've seen a new 9046 // one NEW_OBJECT with the same name. FIXME: This does not free the 9047 // new object when we don't need it. 9048 9049 Named_object* 9050 Bindings::new_definition(Named_object* old_object, Named_object* new_object) 9051 { 9052 if (new_object->is_erroneous() && !old_object->is_erroneous()) 9053 return new_object; 9054 9055 std::string reason; 9056 switch (old_object->classification()) 9057 { 9058 default: 9059 case Named_object::NAMED_OBJECT_UNINITIALIZED: 9060 go_unreachable(); 9061 9062 case Named_object::NAMED_OBJECT_ERRONEOUS: 9063 return old_object; 9064 9065 case Named_object::NAMED_OBJECT_UNKNOWN: 9066 { 9067 Named_object* real = old_object->unknown_value()->real_named_object(); 9068 if (real != NULL) 9069 return this->new_definition(real, new_object); 9070 go_assert(!new_object->is_unknown()); 9071 old_object->unknown_value()->set_real_named_object(new_object); 9072 if (!new_object->is_type_declaration() 9073 && !new_object->is_function_declaration()) 9074 this->named_objects_.push_back(new_object); 9075 return new_object; 9076 } 9077 9078 case Named_object::NAMED_OBJECT_CONST: 9079 break; 9080 9081 case Named_object::NAMED_OBJECT_TYPE: 9082 if (new_object->is_type_declaration()) 9083 return old_object; 9084 break; 9085 9086 case Named_object::NAMED_OBJECT_TYPE_DECLARATION: 9087 if (new_object->is_type_declaration()) 9088 return old_object; 9089 if (new_object->is_type()) 9090 { 9091 old_object->set_type_value(new_object->type_value()); 9092 new_object->type_value()->set_named_object(old_object); 9093 this->named_objects_.push_back(old_object); 9094 return old_object; 9095 } 9096 break; 9097 9098 case Named_object::NAMED_OBJECT_VAR: 9099 case Named_object::NAMED_OBJECT_RESULT_VAR: 9100 // We have already given an error in the parser for cases where 9101 // one parameter or result variable redeclares another one. 9102 if ((new_object->is_variable() 9103 && new_object->var_value()->is_parameter()) 9104 || new_object->is_result_variable()) 9105 return old_object; 9106 break; 9107 9108 case Named_object::NAMED_OBJECT_SINK: 9109 go_unreachable(); 9110 9111 case Named_object::NAMED_OBJECT_FUNC: 9112 break; 9113 9114 case Named_object::NAMED_OBJECT_FUNC_DECLARATION: 9115 { 9116 // We declare the hash and equality functions before defining 9117 // them, because we sometimes see that we need the declaration 9118 // while we are in the middle of a different function. 9119 // 9120 // We declare the main function before the user defines it, to 9121 // give better error messages. 9122 // 9123 // We declare inline functions before we define them, as we 9124 // only define them if we need them. 9125 if (new_object->is_function() 9126 && ((Linemap::is_predeclared_location(old_object->location()) 9127 && Linemap::is_predeclared_location(new_object->location())) 9128 || (Gogo::unpack_hidden_name(old_object->name()) == "main" 9129 && Linemap::is_unknown_location(old_object->location())) 9130 || (new_object->package() != NULL 9131 && old_object->func_declaration_value()->has_imported_body() 9132 && new_object->func_value()->is_inline_only()))) 9133 { 9134 Function_type* old_type = 9135 old_object->func_declaration_value()->type(); 9136 Function_type* new_type = new_object->func_value()->type(); 9137 if (old_type->is_valid_redeclaration(new_type, &reason)) 9138 { 9139 Function_declaration* fd = 9140 old_object->func_declaration_value(); 9141 go_assert(fd->asm_name().empty()); 9142 old_object->set_function_value(new_object->func_value()); 9143 this->named_objects_.push_back(old_object); 9144 return old_object; 9145 } 9146 } 9147 } 9148 break; 9149 9150 case Named_object::NAMED_OBJECT_PACKAGE: 9151 break; 9152 } 9153 9154 std::string n = old_object->message_name(); 9155 if (reason.empty()) 9156 go_error_at(new_object->location(), "redefinition of %qs", n.c_str()); 9157 else 9158 go_error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(), 9159 reason.c_str()); 9160 old_object->set_is_redefinition(); 9161 new_object->set_is_redefinition(); 9162 9163 if (!Linemap::is_unknown_location(old_object->location()) 9164 && !Linemap::is_predeclared_location(old_object->location())) 9165 go_inform(old_object->location(), "previous definition of %qs was here", 9166 n.c_str()); 9167 9168 return old_object; 9169 } 9170 9171 // Add a named type. 9172 9173 Named_object* 9174 Bindings::add_named_type(Named_type* named_type) 9175 { 9176 return this->add_named_object(named_type->named_object()); 9177 } 9178 9179 // Add a function. 9180 9181 Named_object* 9182 Bindings::add_function(const std::string& name, const Package* package, 9183 Function* function) 9184 { 9185 return this->add_named_object(Named_object::make_function(name, package, 9186 function)); 9187 } 9188 9189 // Add a function declaration. 9190 9191 Named_object* 9192 Bindings::add_function_declaration(const std::string& name, 9193 const Package* package, 9194 Function_type* type, 9195 Location location) 9196 { 9197 Named_object* no = Named_object::make_function_declaration(name, package, 9198 type, location); 9199 return this->add_named_object(no); 9200 } 9201 9202 // Define a type which was previously declared. 9203 9204 void 9205 Bindings::define_type(Named_object* no, Named_type* type) 9206 { 9207 no->set_type_value(type); 9208 this->named_objects_.push_back(no); 9209 } 9210 9211 // Mark all local variables as used. This is used for some types of 9212 // parse error. 9213 9214 void 9215 Bindings::mark_locals_used() 9216 { 9217 for (std::vector<Named_object*>::iterator p = this->named_objects_.begin(); 9218 p != this->named_objects_.end(); 9219 ++p) 9220 if ((*p)->is_variable()) 9221 (*p)->var_value()->set_is_used(); 9222 } 9223 9224 // Traverse bindings. 9225 9226 int 9227 Bindings::traverse(Traverse* traverse, bool is_global) 9228 { 9229 unsigned int traverse_mask = traverse->traverse_mask(); 9230 9231 // We don't use an iterator because we permit the traversal to add 9232 // new global objects. 9233 const unsigned int e_or_t = (Traverse::traverse_expressions 9234 | Traverse::traverse_types); 9235 for (size_t i = 0; i < this->named_objects_.size(); ++i) 9236 { 9237 Named_object* p = this->named_objects_[i]; 9238 if (p->traverse(traverse, is_global) == TRAVERSE_EXIT) 9239 return TRAVERSE_EXIT; 9240 } 9241 9242 // If we need to traverse types, check the function declarations, 9243 // which have types. Also check any methods of a type declaration. 9244 if ((traverse_mask & e_or_t) != 0) 9245 { 9246 for (Bindings::const_declarations_iterator p = 9247 this->begin_declarations(); 9248 p != this->end_declarations(); 9249 ++p) 9250 { 9251 if (p->second->is_function_declaration()) 9252 { 9253 if (Type::traverse(p->second->func_declaration_value()->type(), 9254 traverse) 9255 == TRAVERSE_EXIT) 9256 return TRAVERSE_EXIT; 9257 } 9258 else if (p->second->is_type_declaration()) 9259 { 9260 const std::vector<Named_object*>* methods = 9261 p->second->type_declaration_value()->methods(); 9262 for (std::vector<Named_object*>::const_iterator pm = 9263 methods->begin(); 9264 pm != methods->end(); 9265 pm++) 9266 { 9267 Named_object* no = *pm; 9268 Type *t; 9269 if (no->is_function()) 9270 t = no->func_value()->type(); 9271 else if (no->is_function_declaration()) 9272 t = no->func_declaration_value()->type(); 9273 else 9274 continue; 9275 if (Type::traverse(t, traverse) == TRAVERSE_EXIT) 9276 return TRAVERSE_EXIT; 9277 } 9278 } 9279 } 9280 } 9281 9282 // Traverse function declarations when needed. 9283 if ((traverse_mask & Traverse::traverse_func_declarations) != 0) 9284 { 9285 for (Bindings::const_declarations_iterator p = this->begin_declarations(); 9286 p != this->end_declarations(); 9287 ++p) 9288 { 9289 if (p->second->is_function_declaration()) 9290 { 9291 if (traverse->function_declaration(p->second) == TRAVERSE_EXIT) 9292 return TRAVERSE_EXIT; 9293 } 9294 } 9295 } 9296 9297 return TRAVERSE_CONTINUE; 9298 } 9299 9300 void 9301 Bindings::debug_dump() 9302 { 9303 std::set<Named_object*> defs; 9304 for (size_t i = 0; i < this->named_objects_.size(); ++i) 9305 defs.insert(this->named_objects_[i]); 9306 for (Contour::iterator p = this->bindings_.begin(); 9307 p != this->bindings_.end(); 9308 ++p) 9309 { 9310 const char* tag = " "; 9311 if (defs.find(p->second) != defs.end()) 9312 tag = "* "; 9313 std::cerr << tag; 9314 debug_go_named_object(p->second); 9315 } 9316 } 9317 9318 void 9319 debug_go_bindings(Bindings* bindings) 9320 { 9321 if (bindings != NULL) 9322 bindings->debug_dump(); 9323 } 9324 9325 // Class Label. 9326 9327 // Clear any references to this label. 9328 9329 void 9330 Label::clear_refs() 9331 { 9332 for (std::vector<Bindings_snapshot*>::iterator p = this->refs_.begin(); 9333 p != this->refs_.end(); 9334 ++p) 9335 delete *p; 9336 this->refs_.clear(); 9337 } 9338 9339 // Get the backend representation for a label. 9340 9341 Blabel* 9342 Label::get_backend_label(Translate_context* context) 9343 { 9344 if (this->blabel_ == NULL) 9345 { 9346 Function* function = context->function()->func_value(); 9347 Bfunction* bfunction = function->get_decl(); 9348 this->blabel_ = context->backend()->label(bfunction, this->name_, 9349 this->location_); 9350 } 9351 return this->blabel_; 9352 } 9353 9354 // Return an expression for the address of this label. 9355 9356 Bexpression* 9357 Label::get_addr(Translate_context* context, Location location) 9358 { 9359 Blabel* label = this->get_backend_label(context); 9360 return context->backend()->label_address(label, location); 9361 } 9362 9363 // Return the dummy label that represents any instance of the blank label. 9364 9365 Label* 9366 Label::create_dummy_label() 9367 { 9368 static Label* dummy_label; 9369 if (dummy_label == NULL) 9370 { 9371 dummy_label = new Label("_"); 9372 dummy_label->set_is_used(); 9373 } 9374 return dummy_label; 9375 } 9376 9377 // Class Unnamed_label. 9378 9379 // Get the backend representation for an unnamed label. 9380 9381 Blabel* 9382 Unnamed_label::get_blabel(Translate_context* context) 9383 { 9384 if (this->blabel_ == NULL) 9385 { 9386 Function* function = context->function()->func_value(); 9387 Bfunction* bfunction = function->get_decl(); 9388 this->blabel_ = context->backend()->label(bfunction, "", 9389 this->location_); 9390 } 9391 return this->blabel_; 9392 } 9393 9394 // Return a statement which defines this unnamed label. 9395 9396 Bstatement* 9397 Unnamed_label::get_definition(Translate_context* context) 9398 { 9399 Blabel* blabel = this->get_blabel(context); 9400 return context->backend()->label_definition_statement(blabel); 9401 } 9402 9403 // Return a goto statement to this unnamed label. 9404 9405 Bstatement* 9406 Unnamed_label::get_goto(Translate_context* context, Location location) 9407 { 9408 Blabel* blabel = this->get_blabel(context); 9409 return context->backend()->goto_statement(blabel, location); 9410 } 9411 9412 // Class Package. 9413 9414 Package::Package(const std::string& pkgpath, 9415 const std::string& pkgpath_symbol, Location location) 9416 : pkgpath_(pkgpath), pkgpath_symbol_(pkgpath_symbol), 9417 package_name_(), bindings_(new Bindings(NULL)), 9418 location_(location) 9419 { 9420 go_assert(!pkgpath.empty()); 9421 } 9422 9423 // Set the package name. 9424 9425 void 9426 Package::set_package_name(const std::string& package_name, Location location) 9427 { 9428 go_assert(!package_name.empty()); 9429 if (this->package_name_.empty()) 9430 this->package_name_ = package_name; 9431 else if (this->package_name_ != package_name) 9432 go_error_at(location, 9433 ("saw two different packages with " 9434 "the same package path %s: %s, %s"), 9435 this->pkgpath_.c_str(), this->package_name_.c_str(), 9436 package_name.c_str()); 9437 } 9438 9439 // Return the pkgpath symbol, which is a prefix for symbols defined in 9440 // this package. 9441 9442 std::string 9443 Package::pkgpath_symbol() const 9444 { 9445 if (this->pkgpath_symbol_.empty()) 9446 return Gogo::pkgpath_for_symbol(this->pkgpath_); 9447 return this->pkgpath_symbol_; 9448 } 9449 9450 // Set the package path symbol. 9451 9452 void 9453 Package::set_pkgpath_symbol(const std::string& pkgpath_symbol) 9454 { 9455 go_assert(!pkgpath_symbol.empty()); 9456 if (this->pkgpath_symbol_.empty()) 9457 this->pkgpath_symbol_ = pkgpath_symbol; 9458 else 9459 go_assert(this->pkgpath_symbol_ == pkgpath_symbol); 9460 } 9461 9462 // Note that symbol from this package was and qualified by ALIAS. 9463 9464 void 9465 Package::note_usage(const std::string& alias) const 9466 { 9467 Aliases::const_iterator p = this->aliases_.find(alias); 9468 go_assert(p != this->aliases_.end()); 9469 p->second->note_usage(); 9470 } 9471 9472 // Forget a given usage. If forgetting this usage means this package becomes 9473 // unused, report that error. 9474 9475 void 9476 Package::forget_usage(Expression* usage) const 9477 { 9478 if (this->fake_uses_.empty()) 9479 return; 9480 9481 std::set<Expression*>::iterator p = this->fake_uses_.find(usage); 9482 go_assert(p != this->fake_uses_.end()); 9483 this->fake_uses_.erase(p); 9484 9485 if (this->fake_uses_.empty()) 9486 go_error_at(this->location(), "imported and not used: %s", 9487 Gogo::message_name(this->package_name()).c_str()); 9488 } 9489 9490 // Clear the used field for the next file. If the only usages of this package 9491 // are possibly fake, keep the fake usages for lowering. 9492 9493 void 9494 Package::clear_used() 9495 { 9496 std::string dot_alias = "." + this->package_name(); 9497 Aliases::const_iterator p = this->aliases_.find(dot_alias); 9498 if (p != this->aliases_.end() && p->second->used() > this->fake_uses_.size()) 9499 this->fake_uses_.clear(); 9500 9501 this->aliases_.clear(); 9502 } 9503 9504 Package_alias* 9505 Package::add_alias(const std::string& alias, Location location) 9506 { 9507 Aliases::const_iterator p = this->aliases_.find(alias); 9508 if (p == this->aliases_.end()) 9509 { 9510 std::pair<Aliases::iterator, bool> ret; 9511 ret = this->aliases_.insert(std::make_pair(alias, 9512 new Package_alias(location))); 9513 p = ret.first; 9514 } 9515 return p->second; 9516 } 9517 9518 // Determine types of constants. Everything else in a package 9519 // (variables, function declarations) should already have a fixed 9520 // type. Constants may have abstract types. 9521 9522 void 9523 Package::determine_types() 9524 { 9525 Bindings* bindings = this->bindings_; 9526 for (Bindings::const_definitions_iterator p = bindings->begin_definitions(); 9527 p != bindings->end_definitions(); 9528 ++p) 9529 { 9530 if ((*p)->is_const()) 9531 (*p)->const_value()->determine_type(); 9532 } 9533 } 9534 9535 // Class Traverse. 9536 9537 // Destructor. 9538 9539 Traverse::~Traverse() 9540 { 9541 if (this->types_seen_ != NULL) 9542 delete this->types_seen_; 9543 if (this->expressions_seen_ != NULL) 9544 delete this->expressions_seen_; 9545 } 9546 9547 // Record that we are looking at a type, and return true if we have 9548 // already seen it. 9549 9550 bool 9551 Traverse::remember_type(const Type* type) 9552 { 9553 if (type->is_error_type()) 9554 return true; 9555 go_assert((this->traverse_mask() & traverse_types) != 0 9556 || (this->traverse_mask() & traverse_expressions) != 0); 9557 // We mostly only have to remember named types. But it turns out 9558 // that an interface type can refer to itself without using a name 9559 // by relying on interface inheritance, as in 9560 // 9561 // type I interface { F() interface{I} } 9562 // 9563 // Similarly it is possible for array types to refer to themselves 9564 // without a name, e.g. 9565 // 9566 // var x [uintptr(unsafe.Sizeof(&x))]byte 9567 // 9568 if (type->classification() != Type::TYPE_NAMED 9569 && type->classification() != Type::TYPE_ARRAY 9570 && type->classification() != Type::TYPE_INTERFACE) 9571 return false; 9572 if (this->types_seen_ == NULL) 9573 this->types_seen_ = new Types_seen(); 9574 std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type); 9575 return !ins.second; 9576 } 9577 9578 // Record that we are looking at an expression, and return true if we 9579 // have already seen it. NB: this routine used to assert if the traverse 9580 // mask did not include expressions/types -- this is no longer the case, 9581 // since it can be useful to remember specific expressions during 9582 // walks that only cover statements. 9583 9584 bool 9585 Traverse::remember_expression(const Expression* expression) 9586 { 9587 if (this->expressions_seen_ == NULL) 9588 this->expressions_seen_ = new Expressions_seen(); 9589 std::pair<Expressions_seen::iterator, bool> ins = 9590 this->expressions_seen_->insert(expression); 9591 return !ins.second; 9592 } 9593 9594 // The default versions of these functions should never be called: the 9595 // traversal mask indicates which functions may be called. 9596 9597 int 9598 Traverse::variable(Named_object*) 9599 { 9600 go_unreachable(); 9601 } 9602 9603 int 9604 Traverse::constant(Named_object*, bool) 9605 { 9606 go_unreachable(); 9607 } 9608 9609 int 9610 Traverse::function(Named_object*) 9611 { 9612 go_unreachable(); 9613 } 9614 9615 int 9616 Traverse::block(Block*) 9617 { 9618 go_unreachable(); 9619 } 9620 9621 int 9622 Traverse::statement(Block*, size_t*, Statement*) 9623 { 9624 go_unreachable(); 9625 } 9626 9627 int 9628 Traverse::expression(Expression**) 9629 { 9630 go_unreachable(); 9631 } 9632 9633 int 9634 Traverse::type(Type*) 9635 { 9636 go_unreachable(); 9637 } 9638 9639 int 9640 Traverse::function_declaration(Named_object*) 9641 { 9642 go_unreachable(); 9643 } 9644 9645 // Class Statement_inserter. 9646 9647 void 9648 Statement_inserter::insert(Statement* s) 9649 { 9650 if (this->statements_added_ != NULL) 9651 this->statements_added_->insert(s); 9652 9653 if (this->block_ != NULL) 9654 { 9655 go_assert(this->pindex_ != NULL); 9656 this->block_->insert_statement_before(*this->pindex_, s); 9657 ++*this->pindex_; 9658 } 9659 else if (this->var_ != NULL) 9660 this->var_->add_preinit_statement(this->gogo_, s); 9661 else 9662 go_assert(saw_errors()); 9663 }