erasure_compiler: Add contract phase dependency
[nit.git] / src / compiler / 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 = 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 = 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 redef fun process_options(args)
36 do
37 super
38
39 if opt_no_check_all.value then
40 opt_no_check_erasure_cast.value = true
41 end
42
43 # Temporary disabled. TODO: implement tagging in the erasure compiler.
44 if opt_erasure.value then
45 opt_no_tag_primitives.value = true
46 end
47 end
48
49 var erasure_compiler_phase = new ErasureCompilerPhase(self, [contracts_phase])
50 end
51
52 class ErasureCompilerPhase
53 super Phase
54 redef fun process_mainmodule(mainmodule, given_mmodules) do
55 if not toolcontext.opt_erasure.value then return
56
57 var modelbuilder = toolcontext.modelbuilder
58 var analysis = null
59 if toolcontext.opt_rta.value then
60 analysis = modelbuilder.do_rapid_type_analysis(mainmodule)
61 end
62 modelbuilder.run_separate_erasure_compiler(mainmodule, analysis)
63 end
64 end
65
66 redef class ModelBuilder
67 fun run_separate_erasure_compiler(mainmodule: MModule, runtime_type_analysis: nullable RapidTypeAnalysis)
68 do
69 var time0 = get_time
70 self.toolcontext.info("*** GENERATING C ***", 1)
71
72 var compiler = new SeparateErasureCompiler(mainmodule, self, runtime_type_analysis)
73 compiler.do_compilation
74 compiler.display_stats
75 var time1 = get_time
76 self.toolcontext.info("*** END GENERATING C: {time1-time0} ***", 2)
77 write_and_make(compiler)
78 end
79 end
80
81 class SeparateErasureCompiler
82 super SeparateCompiler
83
84 private var class_ids: Map[MClass, Int] is noinit
85 private var class_colors: Map[MClass, Int] is noinit
86 protected var vt_colors: Map[MVirtualTypeProp, Int] is noinit
87
88 init do
89
90 # Class coloring
91 var poset = mainmodule.flatten_mclass_hierarchy
92 var mclasses = new HashSet[MClass].from(poset)
93 var colorer = new POSetColorer[MClass]
94 colorer.colorize(poset)
95 class_ids = colorer.ids
96 class_colors = colorer.colors
97 class_tables = self.build_class_typing_tables(mclasses)
98
99 # lookup vt to build layout with
100 var vts = new HashMap[MClass, Set[MVirtualTypeProp]]
101 for mclass in mclasses do
102 vts[mclass] = new HashSet[MVirtualTypeProp]
103 for mprop in self.mainmodule.properties(mclass) do
104 if mprop isa MVirtualTypeProp then
105 vts[mclass].add(mprop)
106 end
107 end
108 end
109
110 # vt coloration
111 var vt_colorer = new POSetBucketsColorer[MClass, MVirtualTypeProp](poset, colorer.conflicts)
112 vt_colors = vt_colorer.colorize(vts)
113 vt_tables = build_vt_tables(mclasses)
114 end
115
116 fun build_vt_tables(mclasses: Set[MClass]): Map[MClass, Array[nullable MPropDef]] do
117 var tables = new HashMap[MClass, Array[nullable MPropDef]]
118 for mclass in mclasses do
119 var table = new Array[nullable MPropDef]
120 # first, fill table from parents by reverse linearization order
121 var parents = new Array[MClass]
122 if mainmodule.flatten_mclass_hierarchy.has(mclass) then
123 parents = mclass.in_hierarchy(mainmodule).greaters.to_a
124 self.mainmodule.linearize_mclasses(parents)
125 end
126 for parent in parents do
127 if parent == mclass then continue
128 for mproperty in self.mainmodule.properties(parent) do
129 if not mproperty isa MVirtualTypeProp then continue
130 var color = vt_colors[mproperty]
131 if table.length <= color then
132 for i in [table.length .. color[ do
133 table[i] = null
134 end
135 end
136 for mpropdef in mproperty.mpropdefs do
137 if mpropdef.mclassdef.mclass == parent then
138 table[color] = mpropdef
139 end
140 end
141 end
142 end
143
144 # then override with local properties
145 for mproperty in self.mainmodule.properties(mclass) do
146 if not mproperty isa MVirtualTypeProp then continue
147 var color = vt_colors[mproperty]
148 if table.length <= color then
149 for i in [table.length .. color[ do
150 table[i] = null
151 end
152 end
153 for mpropdef in mproperty.mpropdefs do
154 if mpropdef.mclassdef.mclass == mclass then
155 table[color] = mpropdef
156 end
157 end
158 end
159 tables[mclass] = table
160 end
161 return tables
162 end
163
164 # Build class tables
165 fun build_class_typing_tables(mclasses: Set[MClass]): Map[MClass, Array[nullable MClass]] do
166 var tables = new HashMap[MClass, Array[nullable MClass]]
167 for mclass in mclasses do
168 var table = new Array[nullable MClass]
169 var supers = new Array[MClass]
170 if mainmodule.flatten_mclass_hierarchy.has(mclass) then
171 supers = mclass.in_hierarchy(mainmodule).greaters.to_a
172 end
173 for sup in supers do
174 var color = class_colors[sup]
175 if table.length <= color then
176 for i in [table.length .. color[ do
177 table[i] = null
178 end
179 end
180 table[color] = sup
181 end
182 tables[mclass] = table
183 end
184 return tables
185 end
186
187 redef fun compile_header_structs do
188 self.header.add_decl("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
189 self.compile_header_attribute_structs
190 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. */")
191 self.header.add_decl("struct type_table \{ int size; int table[]; \}; /* colorized type table. */")
192 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. */")
193 self.header.add_decl("struct vts_table \{ int dummy; const struct vts_entry vts[]; \}; /* vts list of a C type representation. */")
194 self.header.add_decl("typedef struct instance \{ const struct class *class; nitattribute_t attrs[1]; \} val; /* general C type representing a Nit instance. */")
195 end
196
197 redef fun compile_class_if_universal(ccinfo, v)
198 do
199 var mclass = ccinfo.mclass
200 var mtype = ccinfo.mtype
201 var c_name = mclass.c_name
202 var is_dead = ccinfo.is_dead
203
204 if mtype.is_c_primitive or mtype.mclass.name == "Pointer" then
205 #Build instance struct
206 self.header.add_decl("struct instance_{c_name} \{")
207 self.header.add_decl("const struct class *class;")
208 self.header.add_decl("{mtype.ctype} value;")
209 self.header.add_decl("\};")
210
211 #Build BOX
212 self.provide_declaration("BOX_{c_name}", "val* BOX_{c_name}({mtype.ctype_extern});")
213 v.add_decl("/* allocate {mtype} */")
214 v.add_decl("val* BOX_{mtype.c_name}({mtype.ctype_extern} value) \{")
215 v.add("struct instance_{c_name}*res = nit_alloc(sizeof(struct instance_{c_name}));")
216 v.require_declaration("class_{c_name}")
217 v.add("res->class = &class_{c_name};")
218 v.add("res->value = value;")
219 v.add("return (val*)res;")
220 v.add("\}")
221
222 if mtype.mclass.name != "Pointer" then return true
223
224 v = new_visitor
225 self.provide_declaration("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}();")
226 v.add_decl("/* allocate {mtype} */")
227 v.add_decl("{mtype.ctype} NEW_{c_name}() \{")
228 if is_dead then
229 v.add_abort("{mclass} is DEAD")
230 else
231 var res = v.new_named_var(mtype, "self")
232 res.is_exact = true
233 v.add("{res} = nit_alloc(sizeof(struct instance_{mtype.c_name}));")
234 v.require_declaration("class_{c_name}")
235 v.add("{res}->class = &class_{c_name};")
236 v.add("((struct instance_{mtype.c_name}*){res})->value = NULL;")
237 v.add("return {res};")
238 end
239 v.add("\}")
240 return true
241 else if mclass.name == "NativeArray" then
242 #Build instance struct
243 self.header.add_decl("struct instance_{c_name} \{")
244 self.header.add_decl("const struct class *class;")
245 self.header.add_decl("int length;")
246 self.header.add_decl("val* values[];")
247 self.header.add_decl("\};")
248
249 #Build NEW
250 self.provide_declaration("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(int length);")
251 v.add_decl("/* allocate {mtype} */")
252 v.add_decl("{mtype.ctype} NEW_{c_name}(int length) \{")
253 var res = v.get_name("self")
254 v.add_decl("struct instance_{c_name} *{res};")
255 var mtype_elt = mtype.arguments.first
256 v.add("{res} = nit_alloc(sizeof(struct instance_{c_name}) + length*sizeof({mtype_elt.ctype}));")
257 v.require_declaration("class_{c_name}")
258 v.add("{res}->class = &class_{c_name};")
259 v.add("{res}->length = length;")
260 v.add("return (val*){res};")
261 v.add("\}")
262 return true
263 else if mclass.name == "RoutineRef" then
264 self.header.add_decl("struct instance_{c_name} \{")
265 self.header.add_decl("const struct class *class;")
266 self.header.add_decl("val* recv;")
267 self.header.add_decl("nitmethod_t method;")
268 self.header.add_decl("\};")
269
270 self.provide_declaration("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(val* recv, nitmethod_t method, const struct class* class);")
271 v.add_decl("/* allocate {mtype} */")
272 v.add_decl("{mtype.ctype} NEW_{c_name}(val* recv, nitmethod_t method, const struct class* class)\{")
273 var res = v.get_name("self")
274 v.add_decl("struct instance_{c_name} *{res};")
275 var alloc = v.nit_alloc("sizeof(struct instance_{c_name})", mclass.full_name)
276 v.add("{res} = {alloc};")
277 v.add("{res}->class = class;")
278 v.add("{res}->recv = recv;")
279 v.add("{res}->method = method;")
280 v.add("return (val*){res};")
281 v.add("\}")
282 return true
283 else if mtype.mclass.kind == extern_kind and mtype.mclass.name != "CString" then
284 var pointer_type = mainmodule.pointer_type
285
286 self.provide_declaration("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}();")
287 v.add_decl("/* allocate {mtype} */")
288 v.add_decl("{mtype.ctype} NEW_{c_name}() \{")
289 if is_dead then
290 v.add_abort("{mclass} is DEAD")
291 else
292 var res = v.new_named_var(mtype, "self")
293 res.is_exact = true
294 v.add("{res} = nit_alloc(sizeof(struct instance_{pointer_type.c_name}));")
295 #v.add("{res}->type = type;")
296 v.require_declaration("class_{c_name}")
297 v.add("{res}->class = &class_{c_name};")
298 v.add("((struct instance_{pointer_type.c_name}*){res})->value = NULL;")
299 v.add("return {res};")
300 end
301 v.add("\}")
302 return true
303 end
304 return false
305 end
306
307 redef fun compile_class_vft(ccinfo, v)
308 do
309 var mclass = ccinfo.mclass
310 var mtype = ccinfo.mtype
311 var c_name = mclass.c_name
312 var is_dead = ccinfo.is_dead
313 var rta = runtime_type_analysis
314
315 # Build class vft
316 self.provide_declaration("class_{c_name}", "extern const struct class class_{c_name};")
317
318 v.add_decl("const struct class class_{c_name} = \{")
319 v.add_decl("{class_ids[mclass]},")
320 v.add_decl("\"{mclass.name}\", /* class_name_string */")
321 v.add_decl("{self.box_kind_of(mclass)}, /* box_kind */")
322 v.add_decl("{class_colors[mclass]},")
323 if not is_dead then
324 if build_class_vts_table(mclass) then
325 v.require_declaration("vts_table_{c_name}")
326 v.add_decl("&vts_table_{c_name},")
327 else
328 v.add_decl("NULL,")
329 end
330 v.add_decl("&type_table_{c_name},")
331 v.add_decl("\{")
332 var vft = self.method_tables.get_or_null(mclass)
333 if vft != null then for i in [0 .. vft.length[ do
334 var mpropdef = vft[i]
335 if mpropdef == null then
336 v.add_decl("NULL, /* empty */")
337 else
338 assert mpropdef isa MMethodDef
339 if rta != null and not rta.live_methoddefs.has(mpropdef) then
340 v.add_decl("NULL, /* DEAD {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
341 continue
342 end
343 var rf = mpropdef.virtual_runtime_function
344 v.require_declaration(rf.c_name)
345 v.add_decl("(nitmethod_t){rf.c_name}, /* pointer to {mpropdef.full_name} */")
346 end
347 end
348 v.add_decl("\}")
349 end
350 v.add_decl("\};")
351 end
352
353 protected fun compile_class_type_table(ccinfo: ClassCompilationInfo, v: SeparateCompilerVisitor)
354 do
355 var mclass = ccinfo.mclass
356 var c_name = mclass.c_name
357 var class_table = self.class_tables[mclass]
358
359 # Build class type table
360 v.add_decl("const struct type_table type_table_{c_name} = \{")
361 v.add_decl("{class_table.length},")
362 v.add_decl("\{")
363 for msuper in class_table do
364 if msuper == null then
365 v.add_decl("-1, /* empty */")
366 else
367 v.add_decl("{self.class_ids[msuper]}, /* {msuper} */")
368 end
369 end
370 v.add_decl("\}")
371 v.add_decl("\};")
372 end
373
374 redef fun compile_default_new(ccinfo, v)
375 do
376 var mclass = ccinfo.mclass
377 var mtype = ccinfo.mtype
378 var c_name = mclass.c_name
379 var is_dead = ccinfo.is_dead
380
381 #Build NEW
382 self.provide_declaration("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(void);")
383 v.add_decl("/* allocate {mtype} */")
384 v.add_decl("{mtype.ctype} NEW_{c_name}(void) \{")
385 if is_dead then
386 v.add_abort("{mclass} is DEAD")
387 else
388
389 var res = v.new_named_var(mtype, "self")
390 res.is_exact = true
391 var attrs = self.attr_tables.get_or_null(mclass)
392 if attrs == null then
393 v.add("{res} = nit_alloc(sizeof(struct instance));")
394 else
395 v.add("{res} = nit_alloc(sizeof(struct instance) + {attrs.length}*sizeof(nitattribute_t));")
396 end
397 v.require_declaration("class_{c_name}")
398 v.add("{res}->class = &class_{c_name};")
399 if attrs != null then
400 self.generate_init_attr(v, res, mtype)
401 v.set_finalizer res
402 end
403 v.add("return {res};")
404 end
405 v.add("\}")
406 end
407
408 redef fun build_class_compilation_info(mclass)
409 do
410 var ccinfo = super
411 var mtype = ccinfo.mtype
412 var rta = runtime_type_analysis
413 var is_dead = false # mclass.kind == abstract_kind or mclass.kind == interface_kind
414 if not is_dead and rta != null and not rta.live_classes.has(mclass) and not mtype.is_c_primitive and mclass.name != "NativeArray" then
415 is_dead = true
416 end
417 ccinfo.is_dead = is_dead
418 return ccinfo
419 end
420
421 redef fun compile_class_to_c(mclass: MClass)
422 do
423 var ccinfo = build_class_compilation_info(mclass)
424 var v = new_visitor
425 v.add_decl("/* runtime class {mclass.c_name} */")
426 self.provide_declaration("class_{mclass.c_name}", "extern const struct class class_{mclass.c_name};")
427 v.add_decl("extern const struct type_table type_table_{mclass.c_name};")
428 self.compile_class_vft(ccinfo, v)
429 self.compile_class_type_table(ccinfo, v)
430 if not self.compile_class_if_universal(ccinfo, v) then
431 self.compile_default_new(ccinfo, v)
432 end
433 end
434
435 private fun build_class_vts_table(mclass: MClass): Bool do
436 if self.vt_tables[mclass].is_empty then return false
437
438 self.provide_declaration("vts_table_{mclass.c_name}", "extern const struct vts_table vts_table_{mclass.c_name};")
439
440 var v = new_visitor
441 v.add_decl("const struct vts_table vts_table_{mclass.c_name} = \{")
442 v.add_decl("0, /* dummy */")
443 v.add_decl("\{")
444
445 for vt in self.vt_tables[mclass] do
446 if vt == null then
447 v.add_decl("\{-1, NULL\}, /* empty */")
448 else
449 var is_null = 0
450 var bound = retrieve_vt_bound(mclass.intro.bound_mtype, vt.as(MVirtualTypeDef).bound)
451 while bound isa MNullableType do
452 bound = retrieve_vt_bound(mclass.intro.bound_mtype, bound.mtype)
453 is_null = 1
454 end
455 var vtclass = bound.as(MClassType).mclass
456 v.require_declaration("class_{vtclass.c_name}")
457 v.add_decl("\{{is_null}, &class_{vtclass.c_name}\}, /* {vt} */")
458 end
459 end
460 v.add_decl("\},")
461 v.add_decl("\};")
462 return true
463 end
464
465 private fun retrieve_vt_bound(anchor: MClassType, mtype: nullable MType): MType do
466 if mtype == null then
467 print "NOT YET IMPLEMENTED: retrieve_vt_bound on null"
468 abort
469 end
470 if mtype isa MVirtualType then
471 return mtype.anchor_to(mainmodule, anchor)
472 else if mtype isa MParameterType then
473 return mtype.anchor_to(mainmodule, anchor)
474 else
475 return mtype
476 end
477 end
478
479 redef fun compile_types
480 do
481 compile_color_consts(vt_colors)
482 end
483
484 redef fun new_visitor do return new SeparateErasureCompilerVisitor(self)
485
486 # Stats
487
488 private var class_tables: Map[MClass, Array[nullable MClass]] is noinit
489 private var vt_tables: Map[MClass, Array[nullable MPropDef]] is noinit
490
491 redef fun display_sizes
492 do
493 print "# size of subtyping tables"
494 print "\ttotal \tholes"
495 var total = 0
496 var holes = 0
497 for t, table in class_tables do
498 total += table.length
499 for e in table do if e == null then holes += 1
500 end
501 print "\t{total}\t{holes}"
502
503 print "# size of resolution tables"
504 print "\ttotal \tholes"
505 total = 0
506 holes = 0
507 for t, table in vt_tables do
508 total += table.length
509 for e in table do if e == null then holes += 1
510 end
511 print "\t{total}\t{holes}"
512
513 print "# size of methods tables"
514 print "\ttotal \tholes"
515 total = 0
516 holes = 0
517 for t, table in method_tables do
518 total += table.length
519 for e in table do if e == null then holes += 1
520 end
521 print "\t{total}\t{holes}"
522
523 print "# size of attributes tables"
524 print "\ttotal \tholes"
525 total = 0
526 holes = 0
527 for t, table in attr_tables do
528 total += table.length
529 for e in table do if e == null then holes += 1
530 end
531 print "\t{total}\t{holes}"
532 end
533 end
534
535 class SeparateErasureCompilerVisitor
536 super SeparateCompilerVisitor
537
538 redef fun compile_callsite(callsite, arguments)
539 do
540 var res = super
541 if callsite.erasure_cast and not self.compiler.as(SeparateErasureCompiler).modelbuilder.toolcontext.opt_no_check_erasure_cast.value then
542 assert res != null
543 var mtype = callsite.msignature.return_mtype
544 assert mtype != null
545 self.add("/* Erasure cast for return {res} isa {mtype} */")
546 var cond = self.type_test(res, mtype, "erasure")
547 self.add("if (!{cond}) \{")
548 #var x = self.class_name_string(res)
549 #var y = self.class_name_string(arguments.first)
550 #self.add("PRINT_ERROR(\"Erasure cast: expected {mtype} (self is %s), got %s for {res}\\n\", {y}, {x});")
551 self.add_abort("Cast failed")
552 self.add("\}")
553 end
554 return res
555 end
556
557 redef fun init_instance(mtype)
558 do
559 self.require_declaration("NEW_{mtype.mclass.c_name}")
560 return self.new_expr("NEW_{mtype.mclass.c_name}()", mtype)
561 end
562
563 redef fun type_test(value, mtype, tag)
564 do
565 self.add("/* type test for {value.inspect} isa {mtype} */")
566
567 var res = self.new_var(bool_type)
568
569 var cltype = self.get_name("cltype")
570 self.add_decl("int {cltype};")
571 var idtype = self.get_name("idtype")
572 self.add_decl("int {idtype};")
573
574 var maybe_null = self.maybe_null(value)
575 var accept_null = "0"
576 if mtype isa MNullableType then
577 mtype = mtype.mtype
578 accept_null = "1"
579 end
580 if mtype isa MParameterType then
581 # Here we get the bound of the the formal type (eh, erasure...)
582 mtype = mtype.resolve_for(self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.mmodule, false)
583 if mtype isa MNullableType then
584 mtype = mtype.mtype
585 accept_null = "1"
586 end
587 end
588
589 if value.mcasttype.is_subtype(self.frame.mpropdef.mclassdef.mmodule, self.frame.mpropdef.mclassdef.bound_mtype, mtype) then
590 self.add("{res} = 1; /* easy {value.inspect} isa {mtype}*/")
591 if compiler.modelbuilder.toolcontext.opt_typing_test_metrics.value then
592 self.compiler.count_type_test_skipped[tag] += 1
593 self.add("count_type_test_skipped_{tag}++;")
594 end
595 return res
596 end
597
598 var class_ptr
599 if not value.mtype.is_c_primitive then
600 class_ptr = "{value}->class->"
601 else
602 var mclass = value.mtype.as(MClassType).mclass
603 self.require_declaration("class_{mclass.c_name}")
604 class_ptr = "class_{mclass.c_name}."
605 end
606
607 if mtype isa MClassType then
608 self.require_declaration("class_{mtype.mclass.c_name}")
609 self.add("{cltype} = class_{mtype.mclass.c_name}.color;")
610 self.add("{idtype} = class_{mtype.mclass.c_name}.id;")
611 if compiler.modelbuilder.toolcontext.opt_typing_test_metrics.value then
612 self.compiler.count_type_test_resolved[tag] += 1
613 self.add("count_type_test_resolved_{tag}++;")
614 end
615 else if mtype isa MVirtualType then
616 var recv = self.frame.arguments.first
617 var recv_ptr
618 if not recv.mtype.is_c_primitive then
619 recv_ptr = "{recv}->class->"
620 else
621 var mclass = recv.mtype.as(MClassType).mclass
622 self.require_declaration("class_{mclass.c_name}")
623 recv_ptr = "class_{mclass.c_name}."
624 end
625 var entry = self.get_name("entry")
626 self.add("struct vts_entry {entry};")
627 self.require_declaration(mtype.mproperty.const_color)
628 self.add("{entry} = {recv_ptr}vts_table->vts[{mtype.mproperty.const_color}];")
629 self.add("{cltype} = {entry}.class->color;")
630 self.add("{idtype} = {entry}.class->id;")
631 if maybe_null and accept_null == "0" then
632 var is_nullable = self.get_name("is_nullable")
633 self.add_decl("short int {is_nullable};")
634 self.add("{is_nullable} = {entry}.is_nullable;")
635 accept_null = is_nullable.to_s
636 end
637 if compiler.modelbuilder.toolcontext.opt_typing_test_metrics.value then
638 self.compiler.count_type_test_unresolved[tag] += 1
639 self.add("count_type_test_unresolved_{tag}++;")
640 end
641 else
642 self.debug("type_test({value.inspect}, {mtype})")
643 abort
644 end
645
646 # check color is in table
647 if maybe_null then
648 self.add("if({value} == NULL) \{")
649 self.add("{res} = {accept_null};")
650 self.add("\} else \{")
651 end
652 self.add("if({cltype} >= {class_ptr}type_table->size) \{")
653 self.add("{res} = 0;")
654 self.add("\} else \{")
655 self.add("{res} = {class_ptr}type_table->table[{cltype}] == {idtype};")
656 self.add("\}")
657 if maybe_null then
658 self.add("\}")
659 end
660
661 return res
662 end
663
664 redef fun unbox_extern(value, mtype)
665 do
666 if mtype isa MClassType and mtype.mclass.kind == extern_kind and
667 mtype.mclass.name != "CString" then
668 var pointer_type = compiler.mainmodule.pointer_type
669 var res = self.new_var_extern(mtype)
670 self.add "{res} = ((struct instance_{pointer_type.c_name}*){value})->value; /* unboxing {value.mtype} */"
671 return res
672 else
673 return value
674 end
675 end
676
677 redef fun box_extern(value, mtype)
678 do
679 if mtype isa MClassType and mtype.mclass.kind == extern_kind and
680 mtype.mclass.name != "CString" then
681 var valtype = compiler.mainmodule.pointer_type
682 var res = self.new_var(mtype)
683 if compiler.runtime_type_analysis != null and not compiler.runtime_type_analysis.live_types.has(value.mtype.as(MClassType)) then
684 self.add("/*no boxing of {value.mtype}: {value.mtype} is not live! */")
685 self.add("PRINT_ERROR(\"Dead code executed!\\n\"); fatal_exit(1);")
686 return res
687 end
688 self.require_declaration("BOX_{valtype.c_name}")
689 self.add("{res} = BOX_{valtype.c_name}({value}); /* boxing {value.mtype} */")
690 self.require_declaration("class_{mtype.c_name}")
691 self.add("{res}->class = &class_{mtype.c_name};")
692 return res
693 else
694 return value
695 end
696 end
697
698 redef fun class_name_string(value)
699 do
700 var res = self.get_name("var_class_name")
701 self.add_decl("const char* {res};")
702 if not value.mtype.is_c_primitive then
703 self.add "{res} = {value} == NULL ? \"null\" : {value}->class->name;"
704 else
705 self.require_declaration("class_{value.mtype.c_name}")
706 self.add "{res} = class_{value.mtype.c_name}.name;"
707 end
708 return res
709 end
710
711 redef fun native_array_instance(elttype, length)
712 do
713 var nclass = mmodule.native_array_class
714 var mtype = nclass.get_mtype([elttype])
715 var res = self.new_var(mtype)
716 res.is_exact = true
717 self.require_declaration("NEW_{nclass.c_name}")
718 length = autobox(length, compiler.mainmodule.int_type)
719 self.add("{res} = NEW_{nclass.c_name}({length});")
720 return res
721 end
722
723 redef fun routine_ref_instance(routine_type, recv, callsite)
724 do
725 var mmethoddef = callsite.mpropdef
726 #debug "ENTER ref_instance"
727 var mmethod = mmethoddef.mproperty
728 # routine_mclass is the specialized one, e.g: FunRef1, ProcRef2, etc..
729 var routine_mclass = routine_type.mclass
730
731 var nclasses = mmodule.model.get_mclasses_by_name("RoutineRef").as(not null)
732 var base_routine_mclass = nclasses.first
733
734 # All routine classes use the same `NEW` constructor.
735 # However, they have different declared `class` and `type` value.
736 self.require_declaration("NEW_{base_routine_mclass.c_name}")
737
738 var recv_class_cname = recv.mcasttype.as(MClassType).mclass.c_name
739 var my_recv = recv
740
741 if recv.mtype.is_c_primitive then
742 my_recv = autobox(recv, mmodule.object_type)
743 end
744 var my_recv_mclass_type = my_recv.mtype.as(MClassType)
745
746 # The class of the concrete Routine must exist (e.g ProcRef0, FunRef0, etc.)
747 self.require_declaration("class_{routine_mclass.c_name}")
748
749 self.require_declaration(mmethoddef.c_name)
750
751 var thunk_function = mmethoddef.callref_thunk(my_recv_mclass_type)
752 var runtime_function = mmethoddef.virtual_runtime_function
753
754 var is_c_equiv = runtime_function.msignature.c_equiv(thunk_function.msignature)
755
756 var c_ref = thunk_function.c_ref
757 if is_c_equiv then
758 var const_color = mmethoddef.mproperty.const_color
759 c_ref = "{class_info(my_recv)}->vft[{const_color}]"
760 self.require_declaration(const_color)
761 else
762 self.require_declaration(thunk_function.c_name)
763 compiler.thunk_todo(thunk_function)
764 end
765 compiler.thunk_todo(thunk_function)
766
767 # Each RoutineRef points to a receiver AND a callref_thunk
768 var res = self.new_expr("NEW_{base_routine_mclass.c_name}({my_recv}, (nitmethod_t){c_ref}, &class_{routine_mclass.c_name})", routine_type)
769 #debug "LEAVING ref_instance"
770 return res
771
772 end
773 end