a60cccd666fc0b8e57db04a2e39785a0506a76c7
[nit.git] / src / separate_erasure_compiler.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Separate compilation of a Nit program with generic type erasure
16 module separate_erasure_compiler
17
18 intrude import separate_compiler
19
20 # Add separate erased compiler specific options
21 redef class ToolContext
22 # --erasure
23 var opt_erasure: OptionBool = new OptionBool("Erase generic types", "--erasure")
24 # --rta
25 var opt_rta = new OptionBool("Activate RTA (implicit with --global and --separate)", "--rta")
26 # --no-check-erasure-cast
27 var opt_no_check_erasure_cast: OptionBool = new OptionBool("Disable implicit casts on unsafe return with erasure-typing policy (dangerous)", "--no-check-erasure-cast")
28
29 redef init
30 do
31 super
32 self.option_context.add_option(self.opt_erasure, self.opt_no_check_erasure_cast, opt_rta)
33 end
34
35 var erasure_compiler_phase = new ErasureCompilerPhase(self, null)
36 end
37
38 class ErasureCompilerPhase
39 super Phase
40 redef fun process_mainmodule(mainmodule, given_mmodules) do
41 if not toolcontext.opt_erasure.value then return
42
43 var modelbuilder = toolcontext.modelbuilder
44 var analysis = null
45 if toolcontext.opt_rta.value then
46 analysis = modelbuilder.do_rapid_type_analysis(mainmodule)
47 end
48 modelbuilder.run_separate_erasure_compiler(mainmodule, analysis)
49 end
50 end
51
52 redef class ModelBuilder
53 fun run_separate_erasure_compiler(mainmodule: MModule, runtime_type_analysis: nullable RapidTypeAnalysis)
54 do
55 var time0 = get_time
56 self.toolcontext.info("*** GENERATING C ***", 1)
57
58 var compiler = new SeparateErasureCompiler(mainmodule, self, runtime_type_analysis)
59 compiler.compile_header
60
61 # compile class structures
62 self.toolcontext.info("Property coloring", 2)
63 compiler.new_file("{mainmodule.name}.tables")
64 compiler.do_property_coloring
65 for m in mainmodule.in_importation.greaters do
66 for mclass in m.intro_mclasses do
67 compiler.compile_class_to_c(mclass)
68 end
69 end
70 compiler.compile_color_consts(compiler.vt_colors)
71
72 # The main function of the C
73 compiler.new_file("{mainmodule.name}.main")
74 compiler.compile_nitni_global_ref_functions
75 compiler.compile_main_function
76
77 # compile methods
78 for m in mainmodule.in_importation.greaters do
79 self.toolcontext.info("Generate C for module {m}", 2)
80 compiler.new_file("{m.name}.sep")
81 compiler.compile_module_to_c(m)
82 end
83
84 compiler.display_stats
85
86 var time1 = get_time
87 self.toolcontext.info("*** END GENERATING C: {time1-time0} ***", 2)
88 write_and_make(compiler)
89 end
90 end
91
92 class SeparateErasureCompiler
93 super SeparateCompiler
94
95 private var class_ids: Map[MClass, Int]
96 private var class_colors: Map[MClass, Int]
97 protected var vt_colors: Map[MVirtualTypeProp, Int]
98
99 init(mainmodule: MModule, mmbuilder: ModelBuilder, runtime_type_analysis: nullable RapidTypeAnalysis) do
100 super
101
102 # Class coloring
103 var poset = mainmodule.flatten_mclass_hierarchy
104 var mclasses = new HashSet[MClass].from(poset)
105 var colorer = new POSetColorer[MClass]
106 colorer.colorize(poset)
107 class_ids = colorer.ids
108 class_colors = colorer.colors
109 class_tables = self.build_class_typing_tables(mclasses)
110
111 # lookup vt to build layout with
112 var vts = new HashMap[MClass, Set[MVirtualTypeProp]]
113 for mclass in mclasses do
114 vts[mclass] = new HashSet[MVirtualTypeProp]
115 for mprop in self.mainmodule.properties(mclass) do
116 if mprop isa MVirtualTypeProp then
117 vts[mclass].add(mprop)
118 end
119 end
120 end
121
122 # vt coloration
123 var vt_colorer = new POSetBucketsColorer[MClass, MVirtualTypeProp](poset, colorer.conflicts)
124 vt_colors = vt_colorer.colorize(vts)
125 vt_tables = build_vt_tables(mclasses)
126 end
127
128 fun build_vt_tables(mclasses: Set[MClass]): Map[MClass, Array[nullable MPropDef]] do
129 var tables = new HashMap[MClass, Array[nullable MPropDef]]
130 for mclass in mclasses do
131 var table = new Array[nullable MPropDef]
132 # first, fill table from parents by reverse linearization order
133 var parents = new Array[MClass]
134 if mainmodule.flatten_mclass_hierarchy.has(mclass) then
135 parents = mclass.in_hierarchy(mainmodule).greaters.to_a
136 self.mainmodule.linearize_mclasses(parents)
137 end
138 for parent in parents do
139 if parent == mclass then continue
140 for mproperty in self.mainmodule.properties(parent) do
141 if not mproperty isa MVirtualTypeProp then continue
142 var color = vt_colors[mproperty]
143 if table.length <= color then
144 for i in [table.length .. color[ do
145 table[i] = null
146 end
147 end
148 for mpropdef in mproperty.mpropdefs do
149 if mpropdef.mclassdef.mclass == parent then
150 table[color] = mpropdef
151 end
152 end
153 end
154 end
155
156 # then override with local properties
157 for mproperty in self.mainmodule.properties(mclass) do
158 if not mproperty isa MVirtualTypeProp then continue
159 var color = vt_colors[mproperty]
160 if table.length <= color then
161 for i in [table.length .. color[ do
162 table[i] = null
163 end
164 end
165 for mpropdef in mproperty.mpropdefs do
166 if mpropdef.mclassdef.mclass == mclass then
167 table[color] = mpropdef
168 end
169 end
170 end
171 tables[mclass] = table
172 end
173 return tables
174 end
175
176 # Build class tables
177 fun build_class_typing_tables(mclasses: Set[MClass]): Map[MClass, Array[nullable MClass]] do
178 var tables = new HashMap[MClass, Array[nullable MClass]]
179 for mclass in mclasses do
180 var table = new Array[nullable MClass]
181 var supers = new Array[MClass]
182 if mainmodule.flatten_mclass_hierarchy.has(mclass) then
183 supers = mclass.in_hierarchy(mainmodule).greaters.to_a
184 end
185 for sup in supers do
186 var color = class_colors[sup]
187 if table.length <= color then
188 for i in [table.length .. color[ do
189 table[i] = null
190 end
191 end
192 table[color] = sup
193 end
194 tables[mclass] = table
195 end
196 return tables
197 end
198
199 redef fun compile_header_structs do
200 self.header.add_decl("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
201 self.compile_header_attribute_structs
202 self.header.add_decl("struct class \{ int id; const char *name; int box_kind; int color; const struct vts_table *vts_table; const struct type_table *type_table; nitmethod_t vft[]; \}; /* general C type representing a Nit class. */")
203 self.header.add_decl("struct type_table \{ int size; int table[]; \}; /* colorized type table. */")
204 self.header.add_decl("struct vts_entry \{ short int is_nullable; const struct class *class; \}; /* link (nullable or not) between the vts and is bound. */")
205 self.header.add_decl("struct vts_table \{ int dummy; const struct vts_entry vts[]; \}; /* vts list of a C type representation. */")
206 self.header.add_decl("typedef struct instance \{ const struct class *class; nitattribute_t attrs[1]; \} val; /* general C type representing a Nit instance. */")
207 end
208
209 redef fun compile_class_to_c(mclass: MClass)
210 do
211 var mtype = mclass.intro.bound_mtype
212 var c_name = mclass.c_name
213 var c_instance_name = mclass.c_instance_name
214
215 var vft = self.method_tables[mclass]
216 var attrs = self.attr_tables[mclass]
217 var class_table = self.class_tables[mclass]
218 var v = self.new_visitor
219
220 var rta = runtime_type_analysis
221 var is_dead = mclass.kind == abstract_kind or mclass.kind == interface_kind
222 if not is_dead and rta != null and not rta.live_classes.has(mclass) and mtype.ctype == "val*" and mclass.name != "NativeArray" then
223 is_dead = true
224 end
225
226 v.add_decl("/* runtime class {c_name} */")
227
228 self.provide_declaration("class_{c_name}", "extern const struct class class_{c_name};")
229 v.add_decl("extern const struct type_table type_table_{c_name};")
230
231 # Build class vft
232 v.add_decl("const struct class class_{c_name} = \{")
233 v.add_decl("{class_ids[mclass]},")
234 v.add_decl("\"{mclass.name}\", /* class_name_string */")
235 v.add_decl("{self.box_kind_of(mclass)}, /* box_kind */")
236 v.add_decl("{class_colors[mclass]},")
237 if not is_dead then
238 if build_class_vts_table(mclass) then
239 v.require_declaration("vts_table_{c_name}")
240 v.add_decl("&vts_table_{c_name},")
241 else
242 v.add_decl("NULL,")
243 end
244 v.add_decl("&type_table_{c_name},")
245 v.add_decl("\{")
246 for i in [0 .. vft.length[ do
247 var mpropdef = vft[i]
248 if mpropdef == null then
249 v.add_decl("NULL, /* empty */")
250 else
251 assert mpropdef isa MMethodDef
252 if rta != null and not rta.live_methoddefs.has(mpropdef) then
253 v.add_decl("NULL, /* DEAD {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
254 continue
255 end
256 if true or mpropdef.mclassdef.bound_mtype.ctype != "val*" then
257 v.require_declaration("VIRTUAL_{mpropdef.c_name}")
258 v.add_decl("(nitmethod_t)VIRTUAL_{mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
259 else
260 v.require_declaration("{mpropdef.c_name}")
261 v.add_decl("(nitmethod_t){mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
262 end
263 end
264 end
265 v.add_decl("\}")
266 end
267 v.add_decl("\};")
268
269 # Build class type table
270
271 v.add_decl("const struct type_table type_table_{c_name} = \{")
272 v.add_decl("{class_table.length},")
273 v.add_decl("\{")
274 for msuper in class_table do
275 if msuper == null then
276 v.add_decl("-1, /* empty */")
277 else
278 v.add_decl("{self.class_ids[msuper]}, /* {msuper} */")
279 end
280 end
281 v.add_decl("\}")
282 v.add_decl("\};")
283
284 if mtype.ctype != "val*" then
285 if mtype.mclass.name == "Pointer" or mtype.mclass.kind != extern_kind then
286 #Build instance struct
287 self.header.add_decl("struct instance_{c_instance_name} \{")
288 self.header.add_decl("const struct class *class;")
289 self.header.add_decl("{mtype.ctype} value;")
290 self.header.add_decl("\};")
291 end
292
293 #Build BOX
294 self.provide_declaration("BOX_{c_name}", "val* BOX_{c_name}({mtype.ctype});")
295 v.add_decl("/* allocate {mtype} */")
296 v.add_decl("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
297 v.add("struct instance_{c_instance_name}*res = nit_alloc(sizeof(struct instance_{c_instance_name}));")
298 v.require_declaration("class_{c_name}")
299 v.add("res->class = &class_{c_name};")
300 v.add("res->value = value;")
301 v.add("return (val*)res;")
302 v.add("\}")
303 return
304 else if mclass.name == "NativeArray" then
305 #Build instance struct
306 self.header.add_decl("struct instance_{c_name} \{")
307 self.header.add_decl("const struct class *class;")
308 self.header.add_decl("int length;")
309 self.header.add_decl("val* values[];")
310 self.header.add_decl("\};")
311
312 #Build NEW
313 self.provide_declaration("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(int length);")
314 v.add_decl("/* allocate {mtype} */")
315 v.add_decl("{mtype.ctype} NEW_{c_name}(int length) \{")
316 var res = v.get_name("self")
317 v.add_decl("struct instance_{c_name} *{res};")
318 var mtype_elt = mtype.arguments.first
319 v.add("{res} = nit_alloc(sizeof(struct instance_{c_name}) + length*sizeof({mtype_elt.ctype}));")
320 v.require_declaration("class_{c_name}")
321 v.add("{res}->class = &class_{c_name};")
322 v.add("{res}->length = length;")
323 v.add("return (val*){res};")
324 v.add("\}")
325 return
326 end
327
328 #Build NEW
329 self.provide_declaration("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(void);")
330 v.add_decl("/* allocate {mtype} */")
331 v.add_decl("{mtype.ctype} NEW_{c_name}(void) \{")
332 if is_dead then
333 v.add_abort("{mclass} is DEAD")
334 else
335
336 var res = v.new_named_var(mtype, "self")
337 res.is_exact = true
338 v.add("{res} = nit_alloc(sizeof(struct instance) + {attrs.length}*sizeof(nitattribute_t));")
339 v.require_declaration("class_{c_name}")
340 v.add("{res}->class = &class_{c_name};")
341 self.generate_init_attr(v, res, mtype)
342 v.add("return {res};")
343 end
344 v.add("\}")
345 end
346
347 private fun build_class_vts_table(mclass: MClass): Bool do
348 if self.vt_tables[mclass].is_empty then return false
349
350 self.provide_declaration("vts_table_{mclass.c_name}", "extern const struct vts_table vts_table_{mclass.c_name};")
351
352 var v = new_visitor
353 v.add_decl("const struct vts_table vts_table_{mclass.c_name} = \{")
354 v.add_decl("0, /* dummy */")
355 v.add_decl("\{")
356
357 for vt in self.vt_tables[mclass] do
358 if vt == null then
359 v.add_decl("\{-1, NULL\}, /* empty */")
360 else
361 var is_null = 0
362 var bound = retrieve_vt_bound(mclass.intro.bound_mtype, vt.as(MVirtualTypeDef).bound)
363 while bound isa MNullableType do
364 bound = retrieve_vt_bound(mclass.intro.bound_mtype, bound.mtype)
365 is_null = 1
366 end
367 var vtclass = bound.as(MClassType).mclass
368 v.require_declaration("class_{vtclass.c_name}")
369 v.add_decl("\{{is_null}, &class_{vtclass.c_name}\}, /* {vt} */")
370 end
371 end
372 v.add_decl("\},")
373 v.add_decl("\};")
374 return true
375 end
376
377 private fun retrieve_vt_bound(anchor: MClassType, mtype: nullable MType): MType do
378 if mtype == null then
379 print "NOT YET IMPLEMENTED: retrieve_vt_bound on null"
380 abort
381 end
382 if mtype isa MVirtualType then
383 return mtype.anchor_to(mainmodule, anchor)
384 else if mtype isa MParameterType then
385 return mtype.anchor_to(mainmodule, anchor)
386 else
387 return mtype
388 end
389 end
390
391 redef fun new_visitor do return new SeparateErasureCompilerVisitor(self)
392
393 # Stats
394
395 private var class_tables: Map[MClass, Array[nullable MClass]]
396 private var vt_tables: Map[MClass, Array[nullable MPropDef]]
397
398 redef fun display_sizes
399 do
400 print "# size of subtyping tables"
401 print "\ttotal \tholes"
402 var total = 0
403 var holes = 0
404 for t, table in class_tables do
405 total += table.length
406 for e in table do if e == null then holes += 1
407 end
408 print "\t{total}\t{holes}"
409
410 print "# size of resolution tables"
411 print "\ttotal \tholes"
412 total = 0
413 holes = 0
414 for t, table in vt_tables do
415 total += table.length
416 for e in table do if e == null then holes += 1
417 end
418 print "\t{total}\t{holes}"
419
420 print "# size of methods tables"
421 print "\ttotal \tholes"
422 total = 0
423 holes = 0
424 for t, table in method_tables do
425 total += table.length
426 for e in table do if e == null then holes += 1
427 end
428 print "\t{total}\t{holes}"
429
430 print "# size of attributes tables"
431 print "\ttotal \tholes"
432 total = 0
433 holes = 0
434 for t, table in attr_tables do
435 total += table.length
436 for e in table do if e == null then holes += 1
437 end
438 print "\t{total}\t{holes}"
439 end
440 end
441
442 class SeparateErasureCompilerVisitor
443 super SeparateCompilerVisitor
444
445 redef fun compile_callsite(callsite, arguments)
446 do
447 var res = super
448 if callsite.erasure_cast and not self.compiler.as(SeparateErasureCompiler).modelbuilder.toolcontext.opt_no_check_erasure_cast.value then
449 assert res != null
450 var mtype = callsite.msignature.return_mtype
451 assert mtype != null
452 self.add("/* Erasure cast for return {res} isa {mtype} */")
453 var cond = self.type_test(res, mtype, "erasure")
454 self.add("if (!{cond}) \{")
455 #var x = self.class_name_string(res)
456 #var y = self.class_name_string(arguments.first)
457 #self.add("PRINT_ERROR(\"Erasure cast: expected {mtype} (self is %s), got %s for {res}\\n\", {y}, {x});")
458 self.add_abort("Cast failed")
459 self.add("\}")
460 end
461 return res
462 end
463
464 redef fun init_instance(mtype)
465 do
466 self.require_declaration("NEW_{mtype.mclass.c_name}")
467 return self.new_expr("NEW_{mtype.mclass.c_name}()", mtype)
468 end
469
470 redef fun type_test(value, mtype, tag)
471 do
472 self.add("/* type test for {value.inspect} isa {mtype} */")
473
474 var res = self.new_var(bool_type)
475
476 var cltype = self.get_name("cltype")
477 self.add_decl("int {cltype};")
478 var idtype = self.get_name("idtype")
479 self.add_decl("int {idtype};")
480
481 var maybe_null = self.maybe_null(value)
482 var accept_null = "0"
483 if mtype isa MNullableType then
484 mtype = mtype.mtype
485 accept_null = "1"
486 end
487 if mtype isa MParameterType then
488 # Here we get the bound of the the formal type (eh, erasure...)
489 mtype = mtype.resolve_for(self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.mmodule, false)
490 if mtype isa MNullableType then
491 mtype = mtype.mtype
492 accept_null = "1"
493 end
494 end
495
496 if value.mcasttype.is_subtype(self.frame.mpropdef.mclassdef.mmodule, self.frame.mpropdef.mclassdef.bound_mtype, mtype) then
497 self.add("{res} = 1; /* easy {value.inspect} isa {mtype}*/")
498 if compiler.modelbuilder.toolcontext.opt_typing_test_metrics.value then
499 self.compiler.count_type_test_skipped[tag] += 1
500 self.add("count_type_test_skipped_{tag}++;")
501 end
502 return res
503 end
504
505 var class_ptr
506 var type_table
507 if value.mtype.ctype == "val*" then
508 class_ptr = "{value}->class->"
509 else
510 var mclass = value.mtype.as(MClassType).mclass
511 self.require_declaration("class_{mclass.c_name}")
512 class_ptr = "class_{mclass.c_name}."
513 end
514
515 if mtype isa MClassType then
516 self.require_declaration("class_{mtype.mclass.c_name}")
517 self.add("{cltype} = class_{mtype.mclass.c_name}.color;")
518 self.add("{idtype} = class_{mtype.mclass.c_name}.id;")
519 if compiler.modelbuilder.toolcontext.opt_typing_test_metrics.value then
520 self.compiler.count_type_test_resolved[tag] += 1
521 self.add("count_type_test_resolved_{tag}++;")
522 end
523 else if mtype isa MVirtualType then
524 var recv = self.frame.arguments.first
525 var recv_ptr
526 if recv.mtype.ctype == "val*" then
527 recv_ptr = "{recv}->class->"
528 else
529 var mclass = recv.mtype.as(MClassType).mclass
530 self.require_declaration("class_{mclass.c_name}")
531 recv_ptr = "class_{mclass.c_name}."
532 end
533 var entry = self.get_name("entry")
534 self.add("struct vts_entry {entry};")
535 self.require_declaration(mtype.mproperty.const_color)
536 self.add("{entry} = {recv_ptr}vts_table->vts[{mtype.mproperty.const_color}];")
537 self.add("{cltype} = {entry}.class->color;")
538 self.add("{idtype} = {entry}.class->id;")
539 if maybe_null and accept_null == "0" then
540 var is_nullable = self.get_name("is_nullable")
541 self.add_decl("short int {is_nullable};")
542 self.add("{is_nullable} = {entry}.is_nullable;")
543 accept_null = is_nullable.to_s
544 end
545 if compiler.modelbuilder.toolcontext.opt_typing_test_metrics.value then
546 self.compiler.count_type_test_unresolved[tag] += 1
547 self.add("count_type_test_unresolved_{tag}++;")
548 end
549 else
550 self.debug("type_test({value.inspect}, {mtype})")
551 abort
552 end
553
554 # check color is in table
555 if maybe_null then
556 self.add("if({value} == NULL) \{")
557 self.add("{res} = {accept_null};")
558 self.add("\} else \{")
559 end
560 self.add("if({cltype} >= {class_ptr}type_table->size) \{")
561 self.add("{res} = 0;")
562 self.add("\} else \{")
563 self.add("{res} = {class_ptr}type_table->table[{cltype}] == {idtype};")
564 self.add("\}")
565 if maybe_null then
566 self.add("\}")
567 end
568
569 return res
570 end
571
572 redef fun class_name_string(value)
573 do
574 var res = self.get_name("var_class_name")
575 self.add_decl("const char* {res};")
576 if value.mtype.ctype == "val*" then
577 self.add "{res} = {value} == NULL ? \"null\" : {value}->class->name;"
578 else
579 self.require_declaration("class_{value.mtype.c_name}")
580 self.add "{res} = class_{value.mtype.c_name}.name;"
581 end
582 return res
583 end
584
585 redef fun native_array_instance(elttype, length)
586 do
587 var nclass = self.get_class("NativeArray")
588 var mtype = nclass.get_mtype([elttype])
589 var res = self.new_var(mtype)
590 res.is_exact = true
591 self.require_declaration("NEW_{nclass.c_name}")
592 self.add("{res} = NEW_{nclass.c_name}({length});")
593 return res
594 end
595
596 redef fun calloc_array(ret_type, arguments)
597 do
598 var ret = ret_type.as(MClassType)
599 self.require_declaration("NEW_{ret.mclass.c_name}")
600 self.ret(self.new_expr("NEW_{ret.mclass.c_name}({arguments[1]})", ret_type))
601 end
602 end