1 // export.cc -- Export declarations in Go frontend.
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 "go-sha1.h"
10 #include "go-c.h"
11 
12 #include "gogo.h"
13 #include "types.h"
14 #include "statements.h"
15 #include "export.h"
16 
17 #include "go-linemap.h"
18 #include "backend.h"
19 
20 // This file handles exporting global declarations.
21 
22 // Class Export.
23 
24 const int Export::magic_len;
25 
26 // Current version magic string.
27 const char Export::cur_magic[Export::magic_len] =
28   {
29     'v', '3', ';', '\n'
30   };
31 
32 // Magic strings for previous versions (still supported).
33 const char Export::v1_magic[Export::magic_len] =
34   {
35     'v', '1', ';', '\n'
36   };
37 const char Export::v2_magic[Export::magic_len] =
38   {
39     'v', '2', ';', '\n'
40   };
41 
42 const int Export::checksum_len;
43 
44 // Constructor.
45 
Export(Stream * stream)46 Export::Export(Stream* stream)
47   : stream_(stream), type_index_(1), packages_()
48 {
49   go_assert(Export::checksum_len == Go_sha1_helper::checksum_len);
50 }
51 
52 // Type hash table operations, treating aliases as distinct.
53 
54 class Type_hash_alias_identical
55 {
56  public:
57   unsigned int
operator ()(const Type * type) const58   operator()(const Type* type) const
59   {
60     return type->hash_for_method(NULL,
61 				 (Type::COMPARE_ERRORS
62 				  | Type::COMPARE_TAGS
63 				  | Type::COMPARE_EMBEDDED_INTERFACES
64 				  | Type::COMPARE_ALIASES));
65   }
66 };
67 
68 class Type_alias_identical
69 {
70  public:
71   bool
operator ()(const Type * t1,const Type * t2) const72   operator()(const Type* t1, const Type* t2) const
73   {
74     return Type::are_identical(t1, t2,
75 			       (Type::COMPARE_ERRORS
76 				| Type::COMPARE_TAGS
77                                 | Type::COMPARE_EMBEDDED_INTERFACES
78 				| Type::COMPARE_ALIASES),
79 			       NULL);
80   }
81 };
82 
83 // Mapping from Type objects to a constant index.  This would be nicer
84 // as a field in Export, but then export.h would have to #include
85 // types.h.
86 
87 typedef Unordered_map_hash(const Type*, int, Type_hash_alias_identical,
88 			   Type_alias_identical) Type_refs;
89 
90 static Type_refs type_refs;
91 
92 // A functor to sort Named_object pointers by name.
93 
94 struct Sort_bindings
95 {
96   bool
operator ()Sort_bindings97   operator()(const Named_object* n1, const Named_object* n2) const
98   { return n1->name() < n2->name(); }
99 };
100 
101 // Return true if we should export NO.
102 
103 static bool
should_export(Named_object * no)104 should_export(Named_object* no)
105 {
106   // We only export objects which are locally defined.
107   if (no->package() != NULL)
108     return false;
109 
110   // We don't export packages.
111   if (no->is_package())
112     return false;
113 
114   // We don't export hidden names.
115   if (Gogo::is_hidden_name(no->name()))
116     return false;
117 
118   // We don't export various special functions.
119   if (Gogo::is_special_name(no->name()))
120     return false;
121 
122   // Methods are exported with the type, not here.
123   if (no->is_function()
124       && no->func_value()->type()->is_method())
125     return false;
126   if (no->is_function_declaration()
127       && no->func_declaration_value()->type()->is_method())
128     return false;
129 
130   // Don't export dummy global variables created for initializers when
131   // used with sinks.
132   if (no->is_variable() && no->name()[0] == '_' && no->name()[1] == '.')
133     return false;
134 
135   return true;
136 }
137 
138 // Export those identifiers marked for exporting.
139 
140 void
export_globals(const std::string & package_name,const std::string & prefix,const std::string & pkgpath,const std::map<std::string,Package * > & packages,const std::map<std::string,Package * > & imports,const std::string & import_init_fn,const Import_init_set & imported_init_fns,const Bindings * bindings)141 Export::export_globals(const std::string& package_name,
142 		       const std::string& prefix,
143 		       const std::string& pkgpath,
144 		       const std::map<std::string, Package*>& packages,
145 		       const std::map<std::string, Package*>& imports,
146 		       const std::string& import_init_fn,
147                        const Import_init_set& imported_init_fns,
148 		       const Bindings* bindings)
149 {
150   // If there have been any errors so far, don't try to export
151   // anything.  That way the export code doesn't have to worry about
152   // mismatched types or other confusions.
153   if (saw_errors())
154     return;
155 
156   // Export the symbols in sorted order.  That will reduce cases where
157   // irrelevant changes to the source code affect the exported
158   // interface.
159   std::vector<Named_object*> exports;
160   exports.reserve(bindings->size_definitions());
161 
162   for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
163        p != bindings->end_definitions();
164        ++p)
165     if (should_export(*p))
166       exports.push_back(*p);
167 
168   for (Bindings::const_declarations_iterator p =
169 	 bindings->begin_declarations();
170        p != bindings->end_declarations();
171        ++p)
172     {
173       // We export a function declaration as it may be implemented in
174       // supporting C code.  We do not export type declarations.
175       if (p->second->is_function_declaration()
176 	  && should_export(p->second))
177 	exports.push_back(p->second);
178     }
179 
180   std::sort(exports.begin(), exports.end(), Sort_bindings());
181 
182   // Assign indexes to all exported types and types referenced by
183   // exported types, and collect all packages mentioned.
184   Unordered_set(const Package*) type_imports;
185   int unexported_type_index = this->prepare_types(&exports, &type_imports);
186 
187   // Although the export data is readable, at least this version is,
188   // it is conceptually a binary format.  Start with a four byte
189   // version number.
190   this->write_bytes(Export::cur_magic, Export::magic_len);
191 
192   // The package name.
193   this->write_c_string("package ");
194   this->write_string(package_name);
195   this->write_c_string("\n");
196 
197   // The prefix or package path, used for all global symbols.
198   if (prefix.empty())
199     {
200       go_assert(!pkgpath.empty());
201       this->write_c_string("pkgpath ");
202       this->write_string(pkgpath);
203     }
204   else
205     {
206       this->write_c_string("prefix ");
207       this->write_string(prefix);
208     }
209   this->write_c_string("\n");
210 
211   this->write_packages(packages);
212 
213   this->write_imports(imports, type_imports);
214 
215   this->write_imported_init_fns(package_name, import_init_fn,
216 				imported_init_fns);
217 
218   // FIXME: It might be clever to add something about the processor
219   // and ABI being used, although ideally any problems in that area
220   // would be caught by the linker.
221 
222   // Write out all the types, both exported and not.
223   this->write_types(unexported_type_index);
224 
225   // Write out the non-type export data.
226   for (std::vector<Named_object*>::const_iterator p = exports.begin();
227        p != exports.end();
228        ++p)
229     {
230       if (!(*p)->is_type())
231 	(*p)->export_named_object(this);
232     }
233 
234   std::string checksum = this->stream_->checksum();
235   std::string s = "checksum ";
236   for (std::string::const_iterator p = checksum.begin();
237        p != checksum.end();
238        ++p)
239     {
240       unsigned char c = *p;
241       unsigned int dig = c >> 4;
242       s += dig < 10 ? '0' + dig : 'A' + dig - 10;
243       dig = c & 0xf;
244       s += dig < 10 ? '0' + dig : 'A' + dig - 10;
245     }
246   s += "\n";
247   this->stream_->write_checksum(s);
248 }
249 
250 // Traversal class to find referenced types.
251 
252 class Find_types_to_prepare : public Traverse
253 {
254  public:
Find_types_to_prepare(Export * exp,Unordered_set (const Package *)* imports)255   Find_types_to_prepare(Export* exp,
256 			Unordered_set(const Package*)* imports)
257     : Traverse(traverse_types),
258       exp_(exp), imports_(imports)
259   { }
260 
261   int
262   type(Type* type);
263 
264   // Traverse the components of a function type.
265   void
266   traverse_function(Function_type*);
267 
268   // Traverse the methods of a named type, and register its package.
269   void
270   traverse_named_type(Named_type*);
271 
272  private:
273   // Exporters.
274   Export* exp_;
275   // List of packages we are building.
276   Unordered_set(const Package*)* imports_;
277 };
278 
279 // Set type index of referenced type, record package imports, and make
280 // sure we traverse methods of named types.
281 
282 int
type(Type * type)283 Find_types_to_prepare::type(Type* type)
284 {
285   // Skip forwarders; don't try to give them a type index.
286   if (type->forward_declaration_type() != NULL)
287     return TRAVERSE_CONTINUE;
288 
289   // Skip the void type, which we'll see when exporting
290   // unsafe.Pointer.  The void type is not itself exported, because
291   // Pointer_type::do_export checks for it.
292   if (type->is_void_type())
293     return TRAVERSE_SKIP_COMPONENTS;
294 
295   // Skip abstract types.  We should never see these in real code,
296   // only in things like const declarations.
297   if (type->is_abstract())
298     return TRAVERSE_SKIP_COMPONENTS;
299 
300   // For interfaces make sure that embedded methods are sorted, since the
301   // comparison function we use for indexing types relies on it (this call has
302   // to happen before the set_type_index call below).
303   if (type->classification() == Type::TYPE_INTERFACE)
304     {
305       Interface_type* it = type->interface_type();
306       if (it != NULL)
307         it->sort_embedded();
308     }
309 
310   if (!this->exp_->set_type_index(type))
311     {
312       // We've already seen this type.
313       return TRAVERSE_SKIP_COMPONENTS;
314     }
315 
316   // At this stage of compilation traversing interface types traverses
317   // the final list of methods, but we export the locally defined
318   // methods.  If there is an embedded interface type we need to make
319   // sure to export that.  Check classification, rather than calling
320   // the interface_type method, because we want to handle named types
321   // below.
322   if (type->classification() == Type::TYPE_INTERFACE)
323     {
324       Interface_type* it = type->interface_type();
325       const Typed_identifier_list* methods = it->local_methods();
326       if (methods != NULL)
327 	{
328 	  for (Typed_identifier_list::const_iterator p = methods->begin();
329 	       p != methods->end();
330 	       ++p)
331 	    {
332 	      if (p->name().empty())
333 		Type::traverse(p->type(), this);
334 	      else
335 		this->traverse_function(p->type()->function_type());
336 	    }
337 	}
338       return TRAVERSE_SKIP_COMPONENTS;
339     }
340 
341   Named_type* nt = type->named_type();
342   if (nt != NULL)
343     this->traverse_named_type(nt);
344 
345   return TRAVERSE_CONTINUE;
346 }
347 
348 // Traverse the types in a function type.  We don't need the function
349 // type itself, just the receiver, parameter, and result types.
350 
351 void
traverse_function(Function_type * type)352 Find_types_to_prepare::traverse_function(Function_type* type)
353 {
354   go_assert(type != NULL);
355   if (this->remember_type(type))
356     return;
357   const Typed_identifier* receiver = type->receiver();
358   if (receiver != NULL)
359     Type::traverse(receiver->type(), this);
360   const Typed_identifier_list* parameters = type->parameters();
361   if (parameters != NULL)
362     parameters->traverse(this);
363   const Typed_identifier_list* results = type->results();
364   if (results != NULL)
365     results->traverse(this);
366 }
367 
368 // Traverse the methods of a named type, and record its package.
369 
370 void
traverse_named_type(Named_type * nt)371 Find_types_to_prepare::traverse_named_type(Named_type* nt)
372 {
373   const Package* package = nt->named_object()->package();
374   if (package != NULL)
375     this->imports_->insert(package);
376 
377   // We have to traverse the methods of named types, because we are
378   // going to export them.  This is not done by ordinary type
379   // traversal.
380   const Bindings* methods = nt->local_methods();
381   if (methods != NULL)
382     {
383       for (Bindings::const_definitions_iterator pm =
384 	     methods->begin_definitions();
385 	   pm != methods->end_definitions();
386 	   ++pm)
387 	{
388 	  Function* fn = (*pm)->func_value();
389 	  this->traverse_function(fn->type());
390 	  if (fn->export_for_inlining())
391 	    fn->block()->traverse(this);
392 	}
393 
394       for (Bindings::const_declarations_iterator pm =
395 	     methods->begin_declarations();
396 	   pm != methods->end_declarations();
397 	   ++pm)
398 	{
399 	  Named_object* mno = pm->second;
400 	  if (mno->is_function_declaration())
401 	    this->traverse_function(mno->func_declaration_value()->type());
402 	}
403     }
404 }
405 
406 // Prepare to export types by assigning a type index to every exported
407 // type and every type referenced by an exported type.  Also collect
408 // all the packages we see in types, so that if we refer to any types
409 // from indirectly imported packages we can tell the importer about
410 // the package.  This returns the number of exported types.
411 
412 int
prepare_types(const std::vector<Named_object * > * exports,Unordered_set (const Package *)* imports)413 Export::prepare_types(const std::vector<Named_object*>* exports,
414 		      Unordered_set(const Package*)* imports)
415 {
416   // Assign indexes to all the exported types.
417   for (std::vector<Named_object*>::const_iterator p = exports->begin();
418        p != exports->end();
419        ++p)
420     {
421       if (!(*p)->is_type())
422 	continue;
423       Interface_type* it = (*p)->type_value()->interface_type();
424       if (it != NULL)
425         it->sort_embedded();
426       this->set_type_index((*p)->type_value());
427     }
428 
429   int ret = this->type_index_;
430 
431   // Use a single instance of the traversal class because traversal
432   // classes keep track of which types they've already seen.  That
433   // lets us avoid type reference loops.
434   Find_types_to_prepare find(this, imports);
435 
436   // Traverse all the exported objects and assign indexes to all types.
437   for (std::vector<Named_object*>::const_iterator p = exports->begin();
438        p != exports->end();
439        ++p)
440     {
441       Named_object* no = *p;
442       switch (no->classification())
443 	{
444 	case Named_object::NAMED_OBJECT_CONST:
445 	  {
446 	    Type* t = no->const_value()->type();
447 	    if (t != NULL && !t->is_abstract())
448 	      Type::traverse(t, &find);
449 	  }
450 	  break;
451 
452 	case Named_object::NAMED_OBJECT_TYPE:
453 	  Type::traverse(no->type_value()->real_type(), &find);
454 	  find.traverse_named_type(no->type_value());
455 	  break;
456 
457 	case Named_object::NAMED_OBJECT_VAR:
458 	  Type::traverse(no->var_value()->type(), &find);
459 	  break;
460 
461 	case Named_object::NAMED_OBJECT_FUNC:
462 	  {
463 	    Function* fn = no->func_value();
464 	    find.traverse_function(fn->type());
465 	    if (fn->export_for_inlining())
466 	      fn->block()->traverse(&find);
467 	  }
468 	  break;
469 
470 	case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
471 	  find.traverse_function(no->func_declaration_value()->type());
472 	  break;
473 
474 	default:
475 	  // We shouldn't see anything else.  If we do we'll give an
476 	  // error later when we try to actually export it.
477 	  break;
478 	}
479     }
480 
481   return ret;
482 }
483 
484 // Give a type an index if it doesn't already have one.  Return true
485 // if we set the type index, false if it was already known.
486 
487 bool
set_type_index(Type * type)488 Export::set_type_index(Type* type)
489 {
490   type = type->forwarded();
491 
492   std::pair<Type_refs::iterator, bool> ins =
493     type_refs.insert(std::make_pair(type, 0));
494   if (!ins.second)
495     {
496       // We've already seen this type.
497       return false;
498     }
499 
500   int index = this->type_index_;
501   ++this->type_index_;
502   ins.first->second = index;
503 
504   return true;
505 }
506 
507 // Sort packages.
508 
509 static bool
packages_compare(const Package * a,const Package * b)510 packages_compare(const Package* a, const Package* b)
511 {
512   if (a->package_name() < b->package_name())
513     return true;
514   else if (a->package_name() > b->package_name())
515     return false;
516 
517   if (a->pkgpath() < b->pkgpath())
518     return true;
519   else if (a->pkgpath() > b->pkgpath())
520     return false;
521 
522   // In principle if we get here then a == b.  Try to do something sensible
523   // even if the import information is inconsistent.
524   if (a->pkgpath_symbol() < b->pkgpath_symbol())
525     return true;
526   else if (a->pkgpath_symbol() > b->pkgpath_symbol())
527     return false;
528 
529   return a < b;
530 }
531 
532 // Write out all the known packages whose pkgpath symbol is not a
533 // simple transformation of the pkgpath, so that the importing code
534 // can reliably know it.
535 
536 void
write_packages(const std::map<std::string,Package * > & packages)537 Export::write_packages(const std::map<std::string, Package*>& packages)
538 {
539   // Sort for consistent output.
540   std::vector<Package*> out;
541   for (std::map<std::string, Package*>::const_iterator p = packages.begin();
542        p != packages.end();
543        ++p)
544     {
545       if (p->second->pkgpath_symbol()
546 	  != Gogo::pkgpath_for_symbol(p->second->pkgpath()))
547 	out.push_back(p->second);
548     }
549 
550   std::sort(out.begin(), out.end(), packages_compare);
551 
552   for (std::vector<Package*>::const_iterator p = out.begin();
553        p != out.end();
554        ++p)
555     {
556       this->write_c_string("package ");
557       this->write_string((*p)->package_name());
558       this->write_c_string(" ");
559       this->write_string((*p)->pkgpath());
560       this->write_c_string(" ");
561       this->write_string((*p)->pkgpath_symbol());
562       this->write_c_string("\n");
563     }
564 }
565 
566 // Sort imported packages.
567 
568 static bool
import_compare(const std::pair<std::string,Package * > & a,const std::pair<std::string,Package * > & b)569 import_compare(const std::pair<std::string, Package*>& a,
570 	       const std::pair<std::string, Package*>& b)
571 {
572   return a.first < b.first;
573 }
574 
575 // Write out the imported packages.
576 
577 void
write_imports(const std::map<std::string,Package * > & imports,const Unordered_set (const Package *)& type_imports)578 Export::write_imports(const std::map<std::string, Package*>& imports,
579 		      const Unordered_set(const Package*)& type_imports)
580 {
581   // Sort the imports for more consistent output.
582   Unordered_set(const Package*) seen;
583   std::vector<std::pair<std::string, Package*> > sorted_imports;
584   for (std::map<std::string, Package*>::const_iterator p = imports.begin();
585        p != imports.end();
586        ++p)
587     {
588       sorted_imports.push_back(std::make_pair(p->first, p->second));
589       seen.insert(p->second);
590     }
591 
592   std::sort(sorted_imports.begin(), sorted_imports.end(), import_compare);
593 
594   for (std::vector<std::pair<std::string, Package*> >::const_iterator p =
595 	 sorted_imports.begin();
596        p != sorted_imports.end();
597        ++p)
598     {
599       this->write_c_string("import ");
600       this->write_string(p->second->package_name());
601       this->write_c_string(" ");
602       this->write_string(p->second->pkgpath());
603       this->write_c_string(" \"");
604       this->write_string(p->first);
605       this->write_c_string("\"\n");
606 
607       this->packages_.insert(p->second);
608     }
609 
610   // Write out a separate list of indirectly imported packages.
611   std::vector<const Package*> indirect_imports;
612   for (Unordered_set(const Package*)::const_iterator p =
613 	 type_imports.begin();
614        p != type_imports.end();
615        ++p)
616     {
617       if (seen.find(*p) == seen.end())
618 	indirect_imports.push_back(*p);
619     }
620 
621   std::sort(indirect_imports.begin(), indirect_imports.end(),
622 	    packages_compare);
623 
624   for (std::vector<const Package*>::const_iterator p =
625 	 indirect_imports.begin();
626        p != indirect_imports.end();
627        ++p)
628     {
629       this->write_c_string("indirectimport ");
630       this->write_string((*p)->package_name());
631       this->write_c_string(" ");
632       this->write_string((*p)->pkgpath());
633       this->write_c_string("\n");
634     }
635 }
636 
637 void
add_init_graph_edge(Init_graph * init_graph,unsigned src,unsigned sink)638 Export::add_init_graph_edge(Init_graph* init_graph, unsigned src, unsigned sink)
639 {
640   Init_graph::iterator it = init_graph->find(src);
641   if (it != init_graph->end())
642     it->second.insert(sink);
643   else
644     {
645       std::set<unsigned> succs;
646       succs.insert(sink);
647       (*init_graph)[src] = succs;
648     }
649 }
650 
651 // Constructs the imported portion of the init graph, e.g. those
652 // edges that we read from imported packages.
653 
654 void
populate_init_graph(Init_graph * init_graph,const Import_init_set & imported_init_fns,const std::map<std::string,unsigned> & init_idx)655 Export::populate_init_graph(Init_graph* init_graph,
656                             const Import_init_set& imported_init_fns,
657                             const std::map<std::string, unsigned>& init_idx)
658 {
659   for (Import_init_set::const_iterator p = imported_init_fns.begin();
660        p != imported_init_fns.end();
661        ++p)
662     {
663       const Import_init* ii = *p;
664       std::map<std::string, unsigned>::const_iterator srcit =
665           init_idx.find(ii->init_name());
666       go_assert(srcit != init_idx.end());
667       unsigned src = srcit->second;
668       for (std::set<std::string>::const_iterator pci = ii->precursors().begin();
669            pci != ii->precursors().end();
670            ++pci)
671 	{
672 	  std::map<std::string, unsigned>::const_iterator it =
673 	      init_idx.find(*pci);
674 	  go_assert(it != init_idx.end());
675 	  unsigned sink = it->second;
676 	  add_init_graph_edge(init_graph, src, sink);
677 	}
678     }
679 }
680 
681 // Write out the initialization functions which need to run for this
682 // package.
683 
684 void
write_imported_init_fns(const std::string & package_name,const std::string & import_init_fn,const Import_init_set & imported_init_fns)685 Export::write_imported_init_fns(const std::string& package_name,
686                                 const std::string& import_init_fn,
687                                 const Import_init_set& imported_init_fns)
688 {
689   if (import_init_fn.empty() && imported_init_fns.empty()) return;
690 
691   // Maps a given init function to the its index in the exported "init" clause.
692   std::map<std::string, unsigned> init_idx;
693 
694   this->write_c_string("init");
695 
696   if (!import_init_fn.empty())
697     {
698       this->write_c_string(" ");
699       this->write_string(package_name);
700       this->write_c_string(" ");
701       this->write_string(import_init_fn);
702       init_idx[import_init_fn] = 0;
703     }
704 
705   if (imported_init_fns.empty())
706     {
707       this->write_c_string("\n");
708       return;
709     }
710 
711   typedef std::map<int, std::vector<std::string> > level_map;
712   Init_graph init_graph;
713   level_map inits_at_level;
714 
715   // Walk through the set of import inits (already sorted by
716   // init fcn name) and write them out to the exports.
717   for (Import_init_set::const_iterator p = imported_init_fns.begin();
718        p != imported_init_fns.end();
719        ++p)
720     {
721       const Import_init* ii = *p;
722 
723       if (ii->init_name() == import_init_fn)
724 	continue;
725 
726       this->write_c_string(" ");
727       this->write_string(ii->package_name());
728       this->write_c_string(" ");
729       this->write_string(ii->init_name());
730 
731       // Populate init_idx.
732       go_assert(init_idx.find(ii->init_name()) == init_idx.end());
733       unsigned idx = init_idx.size();
734       init_idx[ii->init_name()] = idx;
735 
736       // If the init function has a non-negative priority value, this
737       // is an indication that it was referred to in an older version
738       // export data section (e.g. we read a legacy object
739       // file). Record such init fcns so that we can fix up the graph
740       // for them (handled later in this function).
741       if (ii->priority() > 0)
742 	{
743 	  level_map::iterator it = inits_at_level.find(ii->priority());
744 	  if (it == inits_at_level.end())
745 	    {
746 	      std::vector<std::string> l;
747 	      l.push_back(ii->init_name());
748 	      inits_at_level[ii->priority()] = l;
749 	    }
750 	  else
751 	    it->second.push_back(ii->init_name());
752 	}
753     }
754   this->write_c_string("\n");
755 
756   // Create the init graph. Start by populating the graph with
757   // all the edges we inherited from imported packages.
758   populate_init_graph(&init_graph, imported_init_fns, init_idx);
759 
760   // Now add edges from the local init function to each of the
761   // imported fcns.
762   if (!import_init_fn.empty())
763     {
764       unsigned src = 0;
765       go_assert(init_idx[import_init_fn] == 0);
766       for (Import_init_set::const_iterator p = imported_init_fns.begin();
767            p != imported_init_fns.end();
768            ++p)
769 	{
770           const Import_init* ii = *p;
771 	  unsigned sink = init_idx[ii->init_name()];
772 	  add_init_graph_edge(&init_graph, src, sink);
773 	}
774     }
775 
776   // In the scenario where one or more of the packages we imported
777   // was written with the legacy export data format, add dummy edges
778   // to capture the priority relationships. Here is a package import
779   // graph as an example:
780   //
781   //       *A
782   //       /|
783   //      / |
784   //     B  *C
785   //       /|
786   //      / |
787   //    *D *E
788   //     | /|
789   //     |/ |
790   //    *F  *G
791   //
792   // Let's suppose that the object for package "C" is from an old
793   // gccgo, e.g. it has the old export data format. All other
794   // packages are compiled with the new compiler and have the new
795   // format. Packages with *'s have init functions. The scenario is
796   // that we're compiling a package "A"; during this process we'll
797   // read the export data for "C". It should look something like
798   //
799   //   init F F..import 1 G G..import 1 D D..import 2 E E..import 2;
800   //
801   // To capture this information and convey it to the consumers of
802   // "A", the code below adds edges to the graph from each priority K
803   // function to every priority K-1 function for appropriate values
804   // of K. This will potentially add more edges than we need (for
805   // example, an edge from D to G), but given that we don't expect
806   // to see large numbers of old objects, this will hopefully be OK.
807 
808   if (inits_at_level.size() > 0)
809     {
810       for (level_map::reverse_iterator it = inits_at_level.rbegin();
811            it != inits_at_level.rend(); ++it)
812 	{
813 	  int level = it->first;
814 	  if (level < 2) break;
815 	  const std::vector<std::string>& fcns_at_level = it->second;
816 	  for (std::vector<std::string>::const_iterator sit =
817 	           fcns_at_level.begin();
818 	       sit != fcns_at_level.end(); ++sit)
819 	    {
820 	      unsigned src = init_idx[*sit];
821 	      level_map::iterator it2 = inits_at_level.find(level - 1);
822 	      if (it2 != inits_at_level.end())
823 		{
824 		  const std::vector<std::string> fcns_at_lm1 = it2->second;
825 		  for (std::vector<std::string>::const_iterator mit =
826 		           fcns_at_lm1.begin();
827 		       mit != fcns_at_lm1.end(); ++mit)
828 		    {
829 		      unsigned sink = init_idx[*mit];
830 		      add_init_graph_edge(&init_graph, src, sink);
831 		    }
832 		}
833 	    }
834 	}
835     }
836 
837   // Write out the resulting graph.
838   this->write_c_string("init_graph");
839   for (Init_graph::const_iterator ki = init_graph.begin();
840        ki != init_graph.end(); ++ki)
841     {
842       unsigned src = ki->first;
843       const std::set<unsigned>& successors = ki->second;
844       for (std::set<unsigned>::const_iterator vi = successors.begin();
845            vi != successors.end(); ++vi)
846 	{
847 	  this->write_c_string(" ");
848 	  this->write_unsigned(src);
849 	  unsigned sink = (*vi);
850 	  this->write_c_string(" ");
851 	  this->write_unsigned(sink);
852 	}
853     }
854   this->write_c_string("\n");
855 }
856 
857 // Write the types to the export stream.
858 
859 void
write_types(int unexported_type_index)860 Export::write_types(int unexported_type_index)
861 {
862   // Map from type index to type.
863   std::vector<const Type*> types(static_cast<size_t>(this->type_index_));
864   for (Type_refs::const_iterator p = type_refs.begin();
865        p != type_refs.end();
866        ++p)
867     {
868       if (p->second >= 0)
869 	types.at(p->second) = p->first;
870     }
871 
872   // Write the type information to a buffer.
873   Stream_to_string type_data;
874   Export::Stream* orig_stream = this->stream_;
875   this->stream_ = &type_data;
876 
877   std::vector<size_t> type_sizes(static_cast<size_t>(this->type_index_));
878   type_sizes[0] = 0;
879 
880   // Start at 1 because type index 0 is not used.
881   size_t start_size = 0;
882   for (int i = 1; i < this->type_index_; ++i)
883     {
884       this->write_type_definition(types[i], i);
885 
886       size_t cur_size = type_data.string().size();
887       type_sizes[i] = cur_size - start_size;
888       start_size = cur_size;
889     }
890 
891   // Back to original stream.
892   this->stream_ = orig_stream;
893 
894   // The line "types MAXP1 EXPORTEDP1 SIZES..." appears before the
895   // types.  MAXP1 is one more than the maximum type index used; that
896   // is, it is the size of the array we need to allocate to hold all
897   // the values.  Indexes 1 up to but not including EXPORTEDP1 are the
898   // exported types.  The other types are not exported.  SIZES... is a
899   // list of MAXP1-1 entries listing the size of the type definition
900   // for each type, starting at index 1.
901   char buf[100];
902   snprintf(buf, sizeof buf, "types %d %d", this->type_index_,
903 	   unexported_type_index);
904   this->write_c_string(buf);
905 
906   // Start at 1 because type index 0 is not used.
907   for (int i = 1; i < this->type_index_; ++i)
908     {
909       snprintf(buf, sizeof buf, " %lu",
910 	       static_cast<unsigned long>(type_sizes[i]));
911       this->write_c_string(buf);
912     }
913   this->write_c_string("\n");
914   this->write_string(type_data.string());
915 }
916 
917 // Write a single type to the export stream.
918 
919 void
write_type_definition(const Type * type,int index)920 Export::write_type_definition(const Type* type, int index)
921 {
922   this->write_c_string("type ");
923 
924   char buf[30];
925   snprintf(buf, sizeof buf, "%d ", index);
926   this->write_c_string(buf);
927 
928   const Named_type* nt = type->named_type();
929   if (nt != NULL)
930     {
931       const Named_object* no = nt->named_object();
932       const Package* package = no->package();
933 
934       this->write_c_string("\"");
935       if (package != NULL && !Gogo::is_hidden_name(no->name()))
936 	{
937 	  this->write_string(package->pkgpath());
938 	  this->write_c_string(".");
939 	}
940       this->write_string(nt->named_object()->name());
941       this->write_c_string("\" ");
942 
943       if (nt->is_alias())
944 	this->write_c_string("= ");
945     }
946 
947   type->export_type(this);
948 
949   // Type::export_type will print a newline for a named type, but not
950   // otherwise.
951   if (nt == NULL)
952     this->write_c_string("\n");
953 }
954 
955 // Write a name to the export stream.
956 
957 void
write_name(const std::string & name)958 Export::write_name(const std::string& name)
959 {
960   if (name.empty())
961     this->write_c_string("?");
962   else
963     this->write_string(Gogo::message_name(name));
964 }
965 
966 // Write an integer value to the export stream.
967 
968 void
write_int(int value)969 Export::write_int(int value)
970 {
971   char buf[100];
972   snprintf(buf, sizeof buf, "%d", value);
973   this->write_c_string(buf);
974 }
975 
976 // Write an integer value to the export stream.
977 
978 void
write_unsigned(unsigned value)979 Export::write_unsigned(unsigned value)
980 {
981   char buf[100];
982   snprintf(buf, sizeof buf, "%u", value);
983   this->write_c_string(buf);
984 }
985 
986 // Return the index of a type.
987 
988 int
type_index(const Type * type)989 Export::type_index(const Type* type)
990 {
991   type = type->forwarded();
992   Type_refs::const_iterator p = type_refs.find(type);
993   go_assert(p != type_refs.end());
994   int index = p->second;
995   go_assert(index != 0);
996   return index;
997 }
998 
999 // Export a type.
1000 
1001 void
write_type(const Type * type)1002 Export::write_type(const Type* type)
1003 {
1004   int index = this->type_index(type);
1005   char buf[30];
1006   snprintf(buf, sizeof buf, "<type %d>", index);
1007   this->write_c_string(buf);
1008 }
1009 
1010 // Export a type to a function body.
1011 
1012 void
write_type_to(const Type * type,Export_function_body * efb)1013 Export::write_type_to(const Type* type, Export_function_body* efb)
1014 {
1015   int index = this->type_index(type);
1016   char buf[30];
1017   snprintf(buf, sizeof buf, "<type %d>", index);
1018   efb->write_c_string(buf);
1019 }
1020 
1021 // Export escape note.
1022 
1023 void
write_escape(std::string * note)1024 Export::write_escape(std::string* note)
1025 {
1026   if (note != NULL && *note != "esc:0x0")
1027     {
1028       this->write_c_string(" ");
1029       char buf[50];
1030       go_assert(note->find("esc:") != std::string::npos);
1031       snprintf(buf, sizeof buf, "<%s>", note->c_str());
1032       this->write_c_string(buf);
1033     }
1034 }
1035 
1036 // Add the builtin types to the export table.
1037 
1038 void
register_builtin_types(Gogo * gogo)1039 Export::register_builtin_types(Gogo* gogo)
1040 {
1041   this->register_builtin_type(gogo, "int8", BUILTIN_INT8);
1042   this->register_builtin_type(gogo, "int16", BUILTIN_INT16);
1043   this->register_builtin_type(gogo, "int32", BUILTIN_INT32);
1044   this->register_builtin_type(gogo, "int64", BUILTIN_INT64);
1045   this->register_builtin_type(gogo, "uint8", BUILTIN_UINT8);
1046   this->register_builtin_type(gogo, "uint16", BUILTIN_UINT16);
1047   this->register_builtin_type(gogo, "uint32", BUILTIN_UINT32);
1048   this->register_builtin_type(gogo, "uint64", BUILTIN_UINT64);
1049   this->register_builtin_type(gogo, "float32", BUILTIN_FLOAT32);
1050   this->register_builtin_type(gogo, "float64", BUILTIN_FLOAT64);
1051   this->register_builtin_type(gogo, "complex64", BUILTIN_COMPLEX64);
1052   this->register_builtin_type(gogo, "complex128", BUILTIN_COMPLEX128);
1053   this->register_builtin_type(gogo, "int", BUILTIN_INT);
1054   this->register_builtin_type(gogo, "uint", BUILTIN_UINT);
1055   this->register_builtin_type(gogo, "uintptr", BUILTIN_UINTPTR);
1056   this->register_builtin_type(gogo, "bool", BUILTIN_BOOL);
1057   this->register_builtin_type(gogo, "string", BUILTIN_STRING);
1058   this->register_builtin_type(gogo, "error", BUILTIN_ERROR);
1059   this->register_builtin_type(gogo, "byte", BUILTIN_BYTE);
1060   this->register_builtin_type(gogo, "rune", BUILTIN_RUNE);
1061 }
1062 
1063 // Register one builtin type in the export table.
1064 
1065 void
register_builtin_type(Gogo * gogo,const char * name,Builtin_code code)1066 Export::register_builtin_type(Gogo* gogo, const char* name, Builtin_code code)
1067 {
1068   Named_object* named_object = gogo->lookup_global(name);
1069   go_assert(named_object != NULL && named_object->is_type());
1070   std::pair<Type_refs::iterator, bool> ins =
1071     type_refs.insert(std::make_pair(named_object->type_value(), code));
1072   go_assert(ins.second);
1073 
1074   // We also insert the underlying type.  We can see the underlying
1075   // type at least for string and bool.  It's OK if this insert
1076   // fails--we expect duplications here, and it doesn't matter when
1077   // they occur.
1078   Type* real_type = named_object->type_value()->real_type();
1079   type_refs.insert(std::make_pair(real_type, code));
1080 }
1081 
1082 // Class Export::Stream.
1083 
Stream()1084 Export::Stream::Stream()
1085 {
1086   this->sha1_helper_ = go_create_sha1_helper();
1087   go_assert(this->sha1_helper_ != NULL);
1088 }
1089 
~Stream()1090 Export::Stream::~Stream()
1091 {
1092 }
1093 
1094 // Write bytes to the stream.  This keeps a checksum of bytes as they
1095 // go by.
1096 
1097 void
write_and_sum_bytes(const char * bytes,size_t length)1098 Export::Stream::write_and_sum_bytes(const char* bytes, size_t length)
1099 {
1100   this->sha1_helper_->process_bytes(bytes, length);
1101   this->do_write(bytes, length);
1102 }
1103 
1104 // Get the checksum.
1105 
1106 std::string
checksum()1107 Export::Stream::checksum()
1108 {
1109   std::string rval = this->sha1_helper_->finish();
1110   delete this->sha1_helper_;
1111   return rval;
1112 }
1113 
1114 // Write the checksum string to the export data.
1115 
1116 void
write_checksum(const std::string & s)1117 Export::Stream::write_checksum(const std::string& s)
1118 {
1119   this->do_write(s.data(), s.length());
1120 }
1121 
1122 // Class Stream_to_section.
1123 
Stream_to_section(Backend * backend)1124 Stream_to_section::Stream_to_section(Backend* backend)
1125     : backend_(backend)
1126 {
1127 }
1128 
1129 // Write data to a section.
1130 
1131 void
do_write(const char * bytes,size_t length)1132 Stream_to_section::do_write(const char* bytes, size_t length)
1133 {
1134   this->backend_->write_export_data (bytes, length);
1135 }
1136