compiler: skip broken entities
[nit.git] / src / compiler / separate_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
16 module separate_compiler
17
18 import abstract_compiler
19 import coloring
20 import rapid_type_analysis
21
22 # Add separate compiler specific options
23 redef class ToolContext
24 # --separate
25 var opt_separate = new OptionBool("Use separate compilation", "--separate")
26 # --no-inline-intern
27 var opt_no_inline_intern = new OptionBool("Do not inline call to intern methods", "--no-inline-intern")
28 # --no-union-attribute
29 var opt_no_union_attribute = new OptionBool("Put primitive attibutes in a box instead of an union", "--no-union-attribute")
30 # --no-shortcut-equate
31 var opt_no_shortcut_equate = new OptionBool("Always call == in a polymorphic way", "--no-shortcut-equal")
32 # --no-tag-primitives
33 var opt_no_tag_primitives = new OptionBool("Use only boxes for primitive types", "--no-tag-primitives")
34
35 # --colors-are-symbols
36 var opt_colors_are_symbols = new OptionBool("Store colors as symbols (link-boost)", "--colors-are-symbols")
37 # --trampoline-call
38 var opt_trampoline_call = new OptionBool("Use an indirection when calling", "--trampoline-call")
39 # --guard-call
40 var opt_guard_call = new OptionBool("Guard VFT calls with a direct call", "--guard-call")
41 # --substitute-monomorph
42 var opt_substitute_monomorph = new OptionBool("Replace monomorph trampoline with direct call (link-boost)", "--substitute-monomorph")
43 # --link-boost
44 var opt_link_boost = new OptionBool("Enable all link-boost optimizations", "--link-boost")
45
46 # --inline-coloring-numbers
47 var opt_inline_coloring_numbers = new OptionBool("Inline colors and ids (semi-global)", "--inline-coloring-numbers")
48 # --inline-some-methods
49 var opt_inline_some_methods = new OptionBool("Allow the separate compiler to inline some methods (semi-global)", "--inline-some-methods")
50 # --direct-call-monomorph
51 var opt_direct_call_monomorph = new OptionBool("Allow the separate compiler to direct call monomorph sites (semi-global)", "--direct-call-monomorph")
52 # --direct-call-monomorph0
53 var opt_direct_call_monomorph0 = new OptionBool("Allow the separate compiler to direct call monomorph sites (semi-global)", "--direct-call-monomorph0")
54 # --skip-dead-methods
55 var opt_skip_dead_methods = new OptionBool("Do not compile dead methods (semi-global)", "--skip-dead-methods")
56 # --semi-global
57 var opt_semi_global = new OptionBool("Enable all semi-global optimizations", "--semi-global")
58 # --no-colo-dead-methods
59 var opt_colo_dead_methods = new OptionBool("Force colorization of dead methods", "--colo-dead-methods")
60 # --tables-metrics
61 var opt_tables_metrics = new OptionBool("Enable static size measuring of tables used for vft, typing and resolution", "--tables-metrics")
62 # --type-poset
63 var opt_type_poset = new OptionBool("Build a poset of types to create more condensed tables.", "--type-poset")
64
65 redef init
66 do
67 super
68 self.option_context.add_option(self.opt_separate)
69 self.option_context.add_option(self.opt_no_inline_intern)
70 self.option_context.add_option(self.opt_no_union_attribute)
71 self.option_context.add_option(self.opt_no_shortcut_equate)
72 self.option_context.add_option(self.opt_no_tag_primitives)
73 self.option_context.add_option(opt_colors_are_symbols, opt_trampoline_call, opt_guard_call, opt_direct_call_monomorph0, opt_substitute_monomorph, opt_link_boost)
74 self.option_context.add_option(self.opt_inline_coloring_numbers, opt_inline_some_methods, opt_direct_call_monomorph, opt_skip_dead_methods, opt_semi_global)
75 self.option_context.add_option(self.opt_colo_dead_methods)
76 self.option_context.add_option(self.opt_tables_metrics)
77 self.option_context.add_option(self.opt_type_poset)
78 end
79
80 redef fun process_options(args)
81 do
82 super
83
84 var tc = self
85 if tc.opt_semi_global.value then
86 tc.opt_inline_coloring_numbers.value = true
87 tc.opt_inline_some_methods.value = true
88 tc.opt_direct_call_monomorph.value = true
89 tc.opt_skip_dead_methods.value = true
90 end
91 if tc.opt_link_boost.value then
92 tc.opt_colors_are_symbols.value = true
93 tc.opt_substitute_monomorph.value = true
94 end
95 if tc.opt_substitute_monomorph.value then
96 tc.opt_trampoline_call.value = true
97 end
98 end
99
100 var separate_compiler_phase = new SeparateCompilerPhase(self, null)
101 end
102
103 class SeparateCompilerPhase
104 super Phase
105 redef fun process_mainmodule(mainmodule, given_mmodules) do
106 if not toolcontext.opt_separate.value then return
107
108 var modelbuilder = toolcontext.modelbuilder
109 var analysis = modelbuilder.do_rapid_type_analysis(mainmodule)
110 modelbuilder.run_separate_compiler(mainmodule, analysis)
111 end
112 end
113
114 redef class ModelBuilder
115 fun run_separate_compiler(mainmodule: MModule, runtime_type_analysis: nullable RapidTypeAnalysis)
116 do
117 var time0 = get_time
118 self.toolcontext.info("*** GENERATING C ***", 1)
119
120 var compiler = new SeparateCompiler(mainmodule, self, runtime_type_analysis)
121 compiler.do_compilation
122 compiler.display_stats
123
124 var time1 = get_time
125 self.toolcontext.info("*** END GENERATING C: {time1-time0} ***", 2)
126 write_and_make(compiler)
127 end
128
129 # Count number of invocations by VFT
130 private var nb_invok_by_tables = 0
131 # Count number of invocations by direct call
132 private var nb_invok_by_direct = 0
133 # Count number of invocations by inlining
134 private var nb_invok_by_inline = 0
135 end
136
137 # Singleton that store the knowledge about the separate compilation process
138 class SeparateCompiler
139 super AbstractCompiler
140
141 redef type VISITOR: SeparateCompilerVisitor
142
143 # The result of the RTA (used to know live types and methods)
144 var runtime_type_analysis: nullable RapidTypeAnalysis
145
146 private var undead_types: Set[MType] = new HashSet[MType]
147 private var live_unresolved_types: Map[MClassDef, Set[MType]] = new HashMap[MClassDef, HashSet[MType]]
148
149 private var type_ids: Map[MType, Int] is noinit
150 private var type_colors: Map[MType, Int] is noinit
151 private var opentype_colors: Map[MType, Int] is noinit
152
153 init do
154 var file = new_file("nit.common")
155 self.header = new CodeWriter(file)
156 self.compile_box_kinds
157 end
158
159 redef fun do_compilation
160 do
161 var compiler = self
162 compiler.compile_header
163
164 var c_name = mainmodule.c_name
165
166 # compile class structures
167 modelbuilder.toolcontext.info("Property coloring", 2)
168 compiler.new_file("{c_name}.classes")
169 compiler.do_property_coloring
170 compiler.compile_class_infos
171 for m in mainmodule.in_importation.greaters do
172 for mclass in m.intro_mclasses do
173 #if mclass.kind == abstract_kind or mclass.kind == interface_kind then continue
174 compiler.compile_class_to_c(mclass)
175 end
176 end
177
178 # The main function of the C
179 compiler.new_file("{c_name}.main")
180 compiler.compile_nitni_global_ref_functions
181 compiler.compile_main_function
182 compiler.compile_finalizer_function
183 compiler.link_mmethods
184
185 # compile methods
186 for m in mainmodule.in_importation.greaters do
187 modelbuilder.toolcontext.info("Generate C for module {m.full_name}", 2)
188 compiler.new_file("{m.c_name}.sep")
189 compiler.compile_module_to_c(m)
190 end
191
192 # compile live & cast type structures
193 modelbuilder.toolcontext.info("Type coloring", 2)
194 compiler.new_file("{c_name}.types")
195 compiler.compile_types
196 end
197
198 # Color and compile type structures and cast information
199 fun compile_types
200 do
201 var compiler = self
202
203 var mtypes = compiler.do_type_coloring
204 for t in mtypes do
205 compiler.compile_type_to_c(t)
206 end
207 # compile remaining types structures (useless but needed for the symbol resolution at link-time)
208 for t in compiler.undead_types do
209 if mtypes.has(t) then continue
210 compiler.compile_type_to_c(t)
211 end
212
213 end
214
215 redef fun compile_header_structs do
216 self.header.add_decl("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
217 self.compile_header_attribute_structs
218 self.header.add_decl("struct class \{ int box_kind; nitmethod_t vft[]; \}; /* general C type representing a Nit class. */")
219
220 # With resolution_table_table, all live type resolution are stored in a big table: resolution_table
221 self.header.add_decl("struct type \{ int id; const char *name; int color; short int is_nullable; const struct types *resolution_table; int table_size; int type_table[]; \}; /* general C type representing a Nit type. */")
222 self.header.add_decl("struct instance \{ const struct type *type; const struct class *class; nitattribute_t attrs[]; \}; /* general C type representing a Nit instance. */")
223 self.header.add_decl("struct types \{ int dummy; const struct type *types[]; \}; /* a list types (used for vts, fts and unresolved lists). */")
224 self.header.add_decl("typedef struct instance val; /* general C type representing a Nit instance. */")
225
226 if not modelbuilder.toolcontext.opt_no_tag_primitives.value then
227 self.header.add_decl("extern const struct class *class_info[];")
228 self.header.add_decl("extern const struct type *type_info[];")
229 end
230 end
231
232 fun compile_header_attribute_structs
233 do
234 if modelbuilder.toolcontext.opt_no_union_attribute.value then
235 self.header.add_decl("typedef void* nitattribute_t; /* general C type representing a Nit attribute. */")
236 else
237 self.header.add_decl("typedef union \{")
238 self.header.add_decl("void* val;")
239 for c, v in self.box_kinds do
240 var t = c.mclass_type
241
242 # `Pointer` reuse the `val` field
243 if t.mclass.name == "Pointer" then continue
244
245 self.header.add_decl("{t.ctype_extern} {t.ctypename};")
246 end
247 self.header.add_decl("\} nitattribute_t; /* general C type representing a Nit attribute. */")
248 end
249 end
250
251 fun compile_box_kinds
252 do
253 # Collect all bas box class
254 # FIXME: this is not completely fine with a separate compilation scheme
255 for classname in ["Int", "Bool", "Byte", "Char", "Float", "NativeString",
256 "Pointer", "Int8", "Int16", "UInt16", "Int32", "UInt32"] do
257 var classes = self.mainmodule.model.get_mclasses_by_name(classname)
258 if classes == null then continue
259 assert classes.length == 1 else print classes.join(", ")
260 self.box_kinds[classes.first] = self.box_kinds.length + 1
261 end
262 end
263
264 var box_kinds = new HashMap[MClass, Int]
265
266 fun box_kind_of(mclass: MClass): Int
267 do
268 #var pointer_type = self.mainmodule.pointer_type
269 #if mclass.mclass_type.ctype == "val*" or mclass.mclass_type.is_subtype(self.mainmodule, mclass.mclass_type pointer_type) then
270 if mclass.mclass_type.ctype_extern == "val*" then
271 return 0
272 else if mclass.kind == extern_kind and mclass.name != "NativeString" then
273 return self.box_kinds[self.mainmodule.pointer_type.mclass]
274 else
275 return self.box_kinds[mclass]
276 end
277
278 end
279
280 fun compile_color_consts(colors: Map[Object, Int]) do
281 var v = new_visitor
282 for m, c in colors do
283 compile_color_const(v, m, c)
284 end
285 end
286
287 fun compile_color_const(v: SeparateCompilerVisitor, m: Object, color: Int) do
288 if color_consts_done.has(m) then return
289 if m isa MEntity then
290 if modelbuilder.toolcontext.opt_inline_coloring_numbers.value then
291 self.provide_declaration(m.const_color, "#define {m.const_color} {color}")
292 else if not modelbuilder.toolcontext.opt_colors_are_symbols.value or not v.compiler.target_platform.supports_linker_script then
293 self.provide_declaration(m.const_color, "extern const int {m.const_color};")
294 v.add("const int {m.const_color} = {color};")
295 else
296 # The color 'C' is the ``address'' of a false static variable 'XC'
297 self.provide_declaration(m.const_color, "#define {m.const_color} ((long)&X{m.const_color})\nextern const void X{m.const_color};")
298 if color == -1 then color = 0 # Symbols cannot be negative, so just use 0 for dead things
299 # Teach the linker that the address of 'XC' is `color`.
300 linker_script.add("X{m.const_color} = {color};")
301 end
302 else
303 abort
304 end
305 color_consts_done.add(m)
306 end
307
308 private var color_consts_done = new HashSet[Object]
309
310 # The conflict graph of classes used for coloration
311 var class_conflict_graph: POSetConflictGraph[MClass] is noinit
312
313 # colorize classe properties
314 fun do_property_coloring do
315
316 var rta = runtime_type_analysis
317
318 # Class graph
319 var mclasses = mainmodule.flatten_mclass_hierarchy
320 class_conflict_graph = mclasses.to_conflict_graph
321
322 # Prepare to collect elements to color and build layout with
323 var mmethods = new HashMap[MClass, Set[PropertyLayoutElement]]
324 var mattributes = new HashMap[MClass, Set[MAttribute]]
325
326 # The dead methods and super-call, still need to provide a dead color symbol
327 var dead_methods = new Array[PropertyLayoutElement]
328
329 for mclass in mclasses do
330 mmethods[mclass] = new HashSet[PropertyLayoutElement]
331 mattributes[mclass] = new HashSet[MAttribute]
332 end
333
334 # Pre-collect known live things
335 if rta != null then
336 for m in rta.live_methods do
337 mmethods[m.intro_mclassdef.mclass].add m
338 end
339 for m in rta.live_super_sends do
340 var mclass = m.mclassdef.mclass
341 mmethods[mclass].add m
342 end
343 end
344
345 for m in mainmodule.in_importation.greaters do for cd in m.mclassdefs do
346 var mclass = cd.mclass
347 # Collect methods ad attributes
348 for p in cd.intro_mproperties do
349 if p isa MMethod then
350 if rta == null then
351 mmethods[mclass].add p
352 else if not rta.live_methods.has(p) then
353 dead_methods.add p
354 end
355 else if p isa MAttribute then
356 mattributes[mclass].add p
357 end
358 end
359
360 # Collect all super calls (dead or not)
361 for mpropdef in cd.mpropdefs do
362 if not mpropdef isa MMethodDef then continue
363 if mpropdef.has_supercall then
364 if rta == null then
365 mmethods[mclass].add mpropdef
366 else if not rta.live_super_sends.has(mpropdef) then
367 dead_methods.add mpropdef
368 end
369 end
370 end
371 end
372
373 # methods coloration
374 var meth_colorer = new POSetGroupColorer[MClass, PropertyLayoutElement](class_conflict_graph, mmethods)
375 var method_colors = meth_colorer.colors
376 compile_color_consts(method_colors)
377
378 # give null color to dead methods and supercalls
379 for mproperty in dead_methods do compile_color_const(new_visitor, mproperty, -1)
380
381 # attribute coloration
382 var attr_colorer = new POSetGroupColorer[MClass, MAttribute](class_conflict_graph, mattributes)
383 var attr_colors = attr_colorer.colors#ize(poset, mattributes)
384 compile_color_consts(attr_colors)
385
386 # Build method and attribute tables
387 method_tables = new HashMap[MClass, Array[nullable MPropDef]]
388 attr_tables = new HashMap[MClass, Array[nullable MProperty]]
389 for mclass in mclasses do
390 if not mclass.has_new_factory and (mclass.kind == abstract_kind or mclass.kind == interface_kind) then continue
391 if rta != null and not rta.live_classes.has(mclass) then continue
392
393 var mtype = mclass.intro.bound_mtype
394
395 # Resolve elements in the layout to get the final table
396 var meth_layout = meth_colorer.build_layout(mclass)
397 var meth_table = new Array[nullable MPropDef].with_capacity(meth_layout.length)
398 method_tables[mclass] = meth_table
399 for e in meth_layout do
400 if e == null then
401 meth_table.add null
402 else if e isa MMethod then
403 # Standard method call of `e`
404 meth_table.add e.lookup_first_definition(mainmodule, mtype)
405 else if e isa MMethodDef then
406 # Super-call in the methoddef `e`
407 meth_table.add e.lookup_next_definition(mainmodule, mtype)
408 else
409 abort
410 end
411 end
412
413 # Do not need to resolve attributes as only the position is used
414 attr_tables[mclass] = attr_colorer.build_layout(mclass)
415 end
416
417
418 end
419
420 # colorize live types of the program
421 private fun do_type_coloring: Collection[MType] do
422 # Collect types to colorize
423 var live_types = runtime_type_analysis.live_types
424 var live_cast_types = runtime_type_analysis.live_cast_types
425
426 var res = new HashSet[MType]
427 res.add_all live_types
428 res.add_all live_cast_types
429
430 if modelbuilder.toolcontext.opt_type_poset.value then
431 # Compute colors with a type poset
432 var poset = poset_from_mtypes(live_types, live_cast_types)
433 var colorer = new POSetColorer[MType]
434 colorer.colorize(poset)
435 type_ids = colorer.ids
436 type_colors = colorer.colors
437 type_tables = build_type_tables(poset)
438 else
439 # Compute colors using the class poset
440 # Faster to compute but the number of holes can degenerate
441 compute_type_test_layouts(live_types, live_cast_types)
442
443 type_ids = new HashMap[MType, Int]
444 for x in res do type_ids[x] = type_ids.length + 1
445 end
446
447 # VT and FT are stored with other unresolved types in the big resolution_tables
448 self.compute_resolution_tables(live_types)
449
450 return res
451 end
452
453 private fun poset_from_mtypes(mtypes, cast_types: Set[MType]): POSet[MType] do
454 var poset = new POSet[MType]
455
456 # Instead of doing the full matrix mtypes X cast_types,
457 # a grouping is done by the base classes of the type so
458 # that we compare only types whose base classes are in inheritance.
459
460 var mtypes_by_class = new MultiHashMap[MClass, MType]
461 for e in mtypes do
462 var c = e.undecorate.as(MClassType).mclass
463 mtypes_by_class[c].add(e)
464 poset.add_node(e)
465 end
466
467 var casttypes_by_class = new MultiHashMap[MClass, MType]
468 for e in cast_types do
469 var c = e.undecorate.as(MClassType).mclass
470 casttypes_by_class[c].add(e)
471 poset.add_node(e)
472 end
473
474 for c1, ts1 in mtypes_by_class do
475 for c2 in c1.in_hierarchy(mainmodule).greaters do
476 var ts2 = casttypes_by_class[c2]
477 for e in ts1 do
478 for o in ts2 do
479 if e == o then continue
480 if e.is_subtype(mainmodule, null, o) then
481 poset.add_edge(e, o)
482 end
483 end
484 end
485 end
486 end
487 return poset
488 end
489
490 # Build type tables
491 fun build_type_tables(mtypes: POSet[MType]): Map[MType, Array[nullable MType]] do
492 var tables = new HashMap[MType, Array[nullable MType]]
493 for mtype in mtypes do
494 var table = new Array[nullable MType]
495 for sup in mtypes[mtype].greaters do
496 var color = type_colors[sup]
497 if table.length <= color then
498 for i in [table.length .. color[ do
499 table[i] = null
500 end
501 end
502 table[color] = sup
503 end
504 tables[mtype] = table
505 end
506 return tables
507 end
508
509
510 private fun compute_type_test_layouts(mtypes: Set[MClassType], cast_types: Set[MType]) do
511 # Group cast_type by their classes
512 var bucklets = new HashMap[MClass, Set[MType]]
513 for e in cast_types do
514 var c = e.undecorate.as(MClassType).mclass
515 if not bucklets.has_key(c) then
516 bucklets[c] = new HashSet[MType]
517 end
518 bucklets[c].add(e)
519 end
520
521 # Colorize cast_types from the class hierarchy
522 var colorer = new POSetGroupColorer[MClass, MType](class_conflict_graph, bucklets)
523 type_colors = colorer.colors
524
525 var layouts = new HashMap[MClass, Array[nullable MType]]
526 for c in runtime_type_analysis.live_classes do
527 layouts[c] = colorer.build_layout(c)
528 end
529
530 # Build the table for each live type
531 for t in mtypes do
532 # A live type use the layout of its class
533 var c = t.mclass
534 var layout = layouts[c]
535 var table = new Array[nullable MType].with_capacity(layout.length)
536 type_tables[t] = table
537
538 # For each potential super-type in the layout
539 for sup in layout do
540 if sup == null then
541 table.add null
542 else if t.is_subtype(mainmodule, null, sup) then
543 table.add sup
544 else
545 table.add null
546 end
547 end
548 end
549 end
550
551 # resolution_tables is used to perform a type resolution at runtime in O(1)
552 private fun compute_resolution_tables(mtypes: Set[MType]) do
553 # During the visit of the body of classes, live_unresolved_types are collected
554 # and associated to
555 # Collect all live_unresolved_types (visited in the body of classes)
556
557 # Determinate fo each livetype what are its possible requested anchored types
558 var mtype2unresolved = new HashMap[MClass, Set[MType]]
559 for mtype in self.runtime_type_analysis.live_types do
560 var mclass = mtype.mclass
561 var set = mtype2unresolved.get_or_null(mclass)
562 if set == null then
563 set = new HashSet[MType]
564 mtype2unresolved[mclass] = set
565 end
566 for cd in mtype.collect_mclassdefs(self.mainmodule) do
567 if self.live_unresolved_types.has_key(cd) then
568 set.add_all(self.live_unresolved_types[cd])
569 end
570 end
571 end
572
573 # Compute the table layout with the prefered method
574 var colorer = new BucketsColorer[MClass, MType]
575
576 opentype_colors = colorer.colorize(mtype2unresolved)
577 resolution_tables = self.build_resolution_tables(self.runtime_type_analysis.live_types, mtype2unresolved)
578
579 # Compile a C constant for each collected unresolved type.
580 # Either to a color, or to -1 if the unresolved type is dead (no live receiver can require it)
581 var all_unresolved = new HashSet[MType]
582 for t in self.live_unresolved_types.values do
583 all_unresolved.add_all(t)
584 end
585 var all_unresolved_types_colors = new HashMap[MType, Int]
586 for t in all_unresolved do
587 if opentype_colors.has_key(t) then
588 all_unresolved_types_colors[t] = opentype_colors[t]
589 else
590 all_unresolved_types_colors[t] = -1
591 end
592 end
593 self.compile_color_consts(all_unresolved_types_colors)
594
595 #print "tables"
596 #for k, v in unresolved_types_tables.as(not null) do
597 # print "{k}: {v.join(", ")}"
598 #end
599 #print ""
600 end
601
602 fun build_resolution_tables(elements: Set[MClassType], map: Map[MClass, Set[MType]]): Map[MClassType, Array[nullable MType]] do
603 var tables = new HashMap[MClassType, Array[nullable MType]]
604 for mclasstype in elements do
605 var mtypes = map[mclasstype.mclass]
606 var table = new Array[nullable MType]
607 for mtype in mtypes do
608 var color = opentype_colors[mtype]
609 if table.length <= color then
610 for i in [table.length .. color[ do
611 table[i] = null
612 end
613 end
614 table[color] = mtype
615 end
616 tables[mclasstype] = table
617 end
618 return tables
619 end
620
621 # Separately compile all the method definitions of the module
622 fun compile_module_to_c(mmodule: MModule)
623 do
624 var old_module = self.mainmodule
625 self.mainmodule = mmodule
626 for cd in mmodule.mclassdefs do
627 for pd in cd.mpropdefs do
628 if not pd isa MMethodDef then continue
629 if pd.mproperty.is_broken or pd.is_broken or pd.msignature == null then continue # Skip broken method
630 var rta = runtime_type_analysis
631 if modelbuilder.toolcontext.opt_skip_dead_methods.value and rta != null and not rta.live_methoddefs.has(pd) then continue
632 #print "compile {pd} @ {cd} @ {mmodule}"
633 var r = pd.separate_runtime_function
634 r.compile_to_c(self)
635 var r2 = pd.virtual_runtime_function
636 if r2 != r then r2.compile_to_c(self)
637
638 # Generate trampolines
639 if modelbuilder.toolcontext.opt_trampoline_call.value then
640 r2.compile_trampolines(self)
641 end
642 end
643 end
644 self.mainmodule = old_module
645 end
646
647 # Process all introduced methods and compile some linking information (if needed)
648 fun link_mmethods
649 do
650 if not modelbuilder.toolcontext.opt_substitute_monomorph.value and not modelbuilder.toolcontext.opt_guard_call.value then return
651
652 for mmodule in mainmodule.in_importation.greaters do
653 for cd in mmodule.mclassdefs do
654 for m in cd.intro_mproperties do
655 if not m isa MMethod then continue
656 link_mmethod(m)
657 end
658 end
659 end
660 end
661
662 # Compile some linking information (if needed)
663 fun link_mmethod(m: MMethod)
664 do
665 var n2 = "CALL_" + m.const_color
666
667 # Replace monomorphic call by a direct call to the virtual implementation
668 var md = is_monomorphic(m)
669 if md != null then
670 linker_script.add("{n2} = {md.virtual_runtime_function.c_name};")
671 end
672
673 # If opt_substitute_monomorph then a trampoline is used, else a weak symbol is used
674 if modelbuilder.toolcontext.opt_guard_call.value then
675 var r = m.intro.virtual_runtime_function
676 provide_declaration(n2, "{r.c_ret} {n2}{r.c_sig} __attribute__((weak));")
677 end
678 end
679
680 # The single mmethodef called in case of monomorphism.
681 # Returns nul if dead or polymorphic.
682 fun is_monomorphic(m: MMethod): nullable MMethodDef
683 do
684 var rta = runtime_type_analysis
685 if rta == null then
686 # Without RTA, monomorphic means alone (uniq name)
687 if m.mpropdefs.length == 1 then
688 return m.mpropdefs.first
689 else
690 return null
691 end
692 else
693 # With RTA, monomorphic means only live methoddef
694 var res: nullable MMethodDef = null
695 for md in m.mpropdefs do
696 if rta.live_methoddefs.has(md) then
697 if res != null then return null
698 res = md
699 end
700 end
701 return res
702 end
703 end
704
705 # Globaly compile the type structure of a live type
706 fun compile_type_to_c(mtype: MType)
707 do
708 assert not mtype.need_anchor
709 var is_live = mtype isa MClassType and runtime_type_analysis.live_types.has(mtype)
710 var is_cast_live = runtime_type_analysis.live_cast_types.has(mtype)
711 var c_name = mtype.c_name
712 var v = new SeparateCompilerVisitor(self)
713 v.add_decl("/* runtime type {mtype} */")
714
715 # extern const struct type_X
716 self.provide_declaration("type_{c_name}", "extern const struct type type_{c_name};")
717
718 # const struct type_X
719 v.add_decl("const struct type type_{c_name} = \{")
720
721 # type id (for cast target)
722 if is_cast_live then
723 v.add_decl("{type_ids[mtype]},")
724 else
725 v.add_decl("-1, /*CAST DEAD*/")
726 end
727
728 # type name
729 v.add_decl("\"{mtype}\", /* class_name_string */")
730
731 # type color (for cast target)
732 if is_cast_live then
733 v.add_decl("{type_colors[mtype]},")
734 else
735 v.add_decl("-1, /*CAST DEAD*/")
736 end
737
738 # is_nullable bit
739 if mtype isa MNullableType then
740 v.add_decl("1,")
741 else
742 v.add_decl("0,")
743 end
744
745 # resolution table (for receiver)
746 if is_live then
747 var mclass_type = mtype.undecorate
748 assert mclass_type isa MClassType
749 if resolution_tables[mclass_type].is_empty then
750 v.add_decl("NULL, /*NO RESOLUTIONS*/")
751 else
752 compile_type_resolution_table(mtype)
753 v.require_declaration("resolution_table_{c_name}")
754 v.add_decl("&resolution_table_{c_name},")
755 end
756 else
757 v.add_decl("NULL, /*DEAD*/")
758 end
759
760 # cast table (for receiver)
761 if is_live then
762 v.add_decl("{self.type_tables[mtype].length},")
763 v.add_decl("\{")
764 for stype in self.type_tables[mtype] do
765 if stype == null then
766 v.add_decl("-1, /* empty */")
767 else
768 v.add_decl("{type_ids[stype]}, /* {stype} */")
769 end
770 end
771 v.add_decl("\},")
772 else
773 # Use -1 to indicate dead type, the info is used by --hardening
774 v.add_decl("-1, \{\}, /*DEAD TYPE*/")
775 end
776 v.add_decl("\};")
777 end
778
779 fun compile_type_resolution_table(mtype: MType) do
780
781 var mclass_type = mtype.undecorate.as(MClassType)
782
783 # extern const struct resolution_table_X resolution_table_X
784 self.provide_declaration("resolution_table_{mtype.c_name}", "extern const struct types resolution_table_{mtype.c_name};")
785
786 # const struct fts_table_X fts_table_X
787 var v = new_visitor
788 v.add_decl("const struct types resolution_table_{mtype.c_name} = \{")
789 v.add_decl("0, /* dummy */")
790 v.add_decl("\{")
791 for t in self.resolution_tables[mclass_type] do
792 if t == null then
793 v.add_decl("NULL, /* empty */")
794 else
795 # The table stores the result of the type resolution
796 # Therefore, for a receiver `mclass_type`, and a unresolved type `t`
797 # the value stored is tv.
798 var tv = t.resolve_for(mclass_type, mclass_type, self.mainmodule, true)
799 # FIXME: What typeids means here? How can a tv not be live?
800 if type_ids.has_key(tv) then
801 v.require_declaration("type_{tv.c_name}")
802 v.add_decl("&type_{tv.c_name}, /* {t}: {tv} */")
803 else
804 v.add_decl("NULL, /* empty ({t}: {tv} not a live type) */")
805 end
806 end
807 end
808 v.add_decl("\}")
809 v.add_decl("\};")
810 end
811
812 # Globally compile the table of the class mclass
813 # In a link-time optimisation compiler, tables are globally computed
814 # In a true separate compiler (a with dynamic loading) you cannot do this unfortnally
815 fun compile_class_to_c(mclass: MClass)
816 do
817 if mclass.is_broken then return
818
819 var mtype = mclass.intro.bound_mtype
820 var c_name = mclass.c_name
821
822 var v = new_visitor
823
824 var rta = runtime_type_analysis
825 var is_dead = rta != null and not rta.live_classes.has(mclass)
826 # While the class may be dead, some part of separately compiled code may use symbols associated to the class, so
827 # in order to compile and link correctly the C code, these symbols should be declared and defined.
828 var need_corpse = is_dead and mtype.is_c_primitive or mclass.kind == extern_kind or mclass.kind == enum_kind
829
830 v.add_decl("/* runtime class {c_name}: {mclass.full_name} (dead={is_dead}; need_corpse={need_corpse})*/")
831
832 # Build class vft
833 if not is_dead or need_corpse then
834 self.provide_declaration("class_{c_name}", "extern const struct class class_{c_name};")
835 v.add_decl("const struct class class_{c_name} = \{")
836 v.add_decl("{self.box_kind_of(mclass)}, /* box_kind */")
837 v.add_decl("\{")
838 var vft = self.method_tables.get_or_null(mclass)
839 if vft != null then for i in [0 .. vft.length[ do
840 var mpropdef = vft[i]
841 if mpropdef == null then
842 v.add_decl("NULL, /* empty */")
843 else
844 assert mpropdef isa MMethodDef
845 if rta != null and not rta.live_methoddefs.has(mpropdef) then
846 v.add_decl("NULL, /* DEAD {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
847 continue
848 else if mpropdef.is_broken or mpropdef.msignature == null or mpropdef.mproperty.is_broken then
849 v.add_decl("NULL, /* DEAD (BROKEN) {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
850 continue
851 end
852 var rf = mpropdef.virtual_runtime_function
853 v.require_declaration(rf.c_name)
854 v.add_decl("(nitmethod_t){rf.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
855 end
856 end
857 v.add_decl("\}")
858 v.add_decl("\};")
859 end
860
861 if mtype.is_c_primitive or mtype.mclass.name == "Pointer" then
862 # Is a primitive type or the Pointer class, not any other extern class
863
864 if mtype.is_tagged then return
865
866 #Build instance struct
867 self.header.add_decl("struct instance_{c_name} \{")
868 self.header.add_decl("const struct type *type;")
869 self.header.add_decl("const struct class *class;")
870 self.header.add_decl("{mtype.ctype_extern} value;")
871 self.header.add_decl("\};")
872
873 # Pointer is needed by extern types, live or not
874 if is_dead and mtype.mclass.name != "Pointer" then return
875
876 #Build BOX
877 self.provide_declaration("BOX_{c_name}", "val* BOX_{c_name}({mtype.ctype_extern});")
878 v.add_decl("/* allocate {mtype} */")
879 v.add_decl("val* BOX_{mtype.c_name}({mtype.ctype_extern} value) \{")
880 v.add("struct instance_{c_name}*res = nit_alloc(sizeof(struct instance_{c_name}));")
881 v.compiler.undead_types.add(mtype)
882 v.require_declaration("type_{c_name}")
883 v.add("res->type = &type_{c_name};")
884 v.require_declaration("class_{c_name}")
885 v.add("res->class = &class_{c_name};")
886 v.add("res->value = value;")
887 v.add("return (val*)res;")
888 v.add("\}")
889
890 # A Pointer class also need its constructor
891 if mtype.mclass.name != "Pointer" then return
892
893 v = new_visitor
894 self.provide_declaration("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(const struct type* type);")
895 v.add_decl("/* allocate {mtype} */")
896 v.add_decl("{mtype.ctype} NEW_{c_name}(const struct type* type) \{")
897 if is_dead then
898 v.add_abort("{mclass} is DEAD")
899 else
900 var res = v.new_named_var(mtype, "self")
901 res.is_exact = true
902 v.add("{res} = nit_alloc(sizeof(struct instance_{mtype.c_name}));")
903 v.add("{res}->type = type;")
904 hardening_live_type(v, "type")
905 v.require_declaration("class_{c_name}")
906 v.add("{res}->class = &class_{c_name};")
907 v.add("((struct instance_{mtype.c_name}*){res})->value = NULL;")
908 v.add("return {res};")
909 end
910 v.add("\}")
911 return
912 else if mclass.name == "NativeArray" then
913 #Build instance struct
914 self.header.add_decl("struct instance_{c_name} \{")
915 self.header.add_decl("const struct type *type;")
916 self.header.add_decl("const struct class *class;")
917 # NativeArrays are just a instance header followed by a length and an array of values
918 self.header.add_decl("int length;")
919 self.header.add_decl("val* values[0];")
920 self.header.add_decl("\};")
921
922 #Build NEW
923 self.provide_declaration("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(int length, const struct type* type);")
924 v.add_decl("/* allocate {mtype} */")
925 v.add_decl("{mtype.ctype} NEW_{c_name}(int length, const struct type* type) \{")
926 var res = v.get_name("self")
927 v.add_decl("struct instance_{c_name} *{res};")
928 var mtype_elt = mtype.arguments.first
929 v.add("{res} = nit_alloc(sizeof(struct instance_{c_name}) + length*sizeof({mtype_elt.ctype}));")
930 v.add("{res}->type = type;")
931 hardening_live_type(v, "type")
932 v.require_declaration("class_{c_name}")
933 v.add("{res}->class = &class_{c_name};")
934 v.add("{res}->length = length;")
935 v.add("return (val*){res};")
936 v.add("\}")
937 return
938 else if mtype.mclass.kind == extern_kind and mtype.mclass.name != "NativeString" then
939 # Is an extern class (other than Pointer and NativeString)
940 # Pointer is caught in a previous `if`, and NativeString is internal
941
942 var pointer_type = mainmodule.pointer_type
943
944 self.provide_declaration("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(const struct type* type);")
945 v.add_decl("/* allocate extern {mtype} */")
946 v.add_decl("{mtype.ctype} NEW_{c_name}(const struct type* type) \{")
947 if is_dead then
948 v.add_abort("{mclass} is DEAD")
949 else
950 var res = v.new_named_var(mtype, "self")
951 res.is_exact = true
952 v.add("{res} = nit_alloc(sizeof(struct instance_{pointer_type.c_name}));")
953 v.add("{res}->type = type;")
954 hardening_live_type(v, "type")
955 v.require_declaration("class_{c_name}")
956 v.add("{res}->class = &class_{c_name};")
957 v.add("((struct instance_{pointer_type.c_name}*){res})->value = NULL;")
958 v.add("return {res};")
959 end
960 v.add("\}")
961 return
962 end
963
964 #Build NEW
965 self.provide_declaration("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(const struct type* type);")
966 v.add_decl("/* allocate {mtype} */")
967 v.add_decl("{mtype.ctype} NEW_{c_name}(const struct type* type) \{")
968 if is_dead then
969 v.add_abort("{mclass} is DEAD")
970 else
971 var res = v.new_named_var(mtype, "self")
972 res.is_exact = true
973 var attrs = self.attr_tables.get_or_null(mclass)
974 if attrs == null then
975 v.add("{res} = nit_alloc(sizeof(struct instance));")
976 else
977 v.add("{res} = nit_alloc(sizeof(struct instance) + {attrs.length}*sizeof(nitattribute_t));")
978 end
979 v.add("{res}->type = type;")
980 hardening_live_type(v, "type")
981 v.require_declaration("class_{c_name}")
982 v.add("{res}->class = &class_{c_name};")
983 if attrs != null then
984 self.generate_init_attr(v, res, mtype)
985 v.set_finalizer res
986 end
987 v.add("return {res};")
988 end
989 v.add("\}")
990 end
991
992 # Compile structures used to map tagged primitive values to their classes and types.
993 # This method also determines which class will be tagged.
994 fun compile_class_infos
995 do
996 if modelbuilder.toolcontext.opt_no_tag_primitives.value then return
997
998 # Note: if you change the tagging scheme, do not forget to update
999 # `autobox` and `extract_tag`
1000 var class_info = new Array[nullable MClass].filled_with(null, 4)
1001 for t in box_kinds.keys do
1002 # Note: a same class can be associated to multiple slots if one want to
1003 # use some Huffman coding.
1004 if t.name == "Int" then
1005 class_info[1] = t
1006 t.mclass_type.tag_value = 1
1007 else if t.name == "Char" then
1008 class_info[2] = t
1009 t.mclass_type.tag_value = 2
1010 else if t.name == "Bool" then
1011 class_info[3] = t
1012 t.mclass_type.tag_value = 3
1013 else
1014 continue
1015 end
1016 t.mclass_type.is_tagged = true
1017 end
1018
1019 # Compile the table for classes. The tag is used as an index
1020 var v = self.new_visitor
1021 v.add_decl "const struct class *class_info[4] = \{"
1022 for t in class_info do
1023 if t == null then
1024 v.add_decl("NULL,")
1025 else
1026 var s = "class_{t.c_name}"
1027 v.require_declaration(s)
1028 v.add_decl("&{s},")
1029 end
1030 end
1031 v.add_decl("\};")
1032
1033 # Compile the table for types. The tag is used as an index
1034 v.add_decl "const struct type *type_info[4] = \{"
1035 for t in class_info do
1036 if t == null then
1037 v.add_decl("NULL,")
1038 else
1039 var s = "type_{t.c_name}"
1040 undead_types.add(t.mclass_type)
1041 v.require_declaration(s)
1042 v.add_decl("&{s},")
1043 end
1044 end
1045 v.add_decl("\};")
1046 end
1047
1048 # Add a dynamic test to ensure that the type referenced by `t` is a live type
1049 fun hardening_live_type(v: VISITOR, t: String)
1050 do
1051 if not v.compiler.modelbuilder.toolcontext.opt_hardening.value then return
1052 v.add("if({t} == NULL) \{")
1053 v.add_abort("type null")
1054 v.add("\}")
1055 v.add("if({t}->table_size < 0) \{")
1056 v.add("PRINT_ERROR(\"Insantiation of a dead type: %s\\n\", {t}->name);")
1057 v.add_abort("type dead")
1058 v.add("\}")
1059 end
1060
1061 redef fun new_visitor do return new SeparateCompilerVisitor(self)
1062
1063 # Stats
1064
1065 private var type_tables: Map[MType, Array[nullable MType]] = new HashMap[MType, Array[nullable MType]]
1066 private var resolution_tables: Map[MClassType, Array[nullable MType]] = new HashMap[MClassType, Array[nullable MType]]
1067 protected var method_tables: Map[MClass, Array[nullable MPropDef]] = new HashMap[MClass, Array[nullable MPropDef]]
1068 protected var attr_tables: Map[MClass, Array[nullable MProperty]] = new HashMap[MClass, Array[nullable MProperty]]
1069
1070 redef fun display_stats
1071 do
1072 super
1073 if self.modelbuilder.toolcontext.opt_tables_metrics.value then
1074 display_sizes
1075 end
1076 if self.modelbuilder.toolcontext.opt_isset_checks_metrics.value then
1077 display_isset_checks
1078 end
1079 var tc = self.modelbuilder.toolcontext
1080 tc.info("# implementation of method invocation",2)
1081 var nb_invok_total = modelbuilder.nb_invok_by_tables + modelbuilder.nb_invok_by_direct + modelbuilder.nb_invok_by_inline
1082 tc.info("total number of invocations: {nb_invok_total}",2)
1083 tc.info("invocations by VFT send: {modelbuilder.nb_invok_by_tables} ({div(modelbuilder.nb_invok_by_tables,nb_invok_total)}%)",2)
1084 tc.info("invocations by direct call: {modelbuilder.nb_invok_by_direct} ({div(modelbuilder.nb_invok_by_direct,nb_invok_total)}%)",2)
1085 tc.info("invocations by inlining: {modelbuilder.nb_invok_by_inline} ({div(modelbuilder.nb_invok_by_inline,nb_invok_total)}%)",2)
1086 end
1087
1088 fun display_sizes
1089 do
1090 print "# size of subtyping tables"
1091 print "\ttotal \tholes"
1092 var total = 0
1093 var holes = 0
1094 for t, table in type_tables do
1095 total += table.length
1096 for e in table do if e == null then holes += 1
1097 end
1098 print "\t{total}\t{holes}"
1099
1100 print "# size of resolution tables"
1101 print "\ttotal \tholes"
1102 total = 0
1103 holes = 0
1104 for t, table in resolution_tables do
1105 total += table.length
1106 for e in table do if e == null then holes += 1
1107 end
1108 print "\t{total}\t{holes}"
1109
1110 print "# size of methods tables"
1111 print "\ttotal \tholes"
1112 total = 0
1113 holes = 0
1114 for t, table in method_tables do
1115 total += table.length
1116 for e in table do if e == null then holes += 1
1117 end
1118 print "\t{total}\t{holes}"
1119
1120 print "# size of attributes tables"
1121 print "\ttotal \tholes"
1122 total = 0
1123 holes = 0
1124 for t, table in attr_tables do
1125 total += table.length
1126 for e in table do if e == null then holes += 1
1127 end
1128 print "\t{total}\t{holes}"
1129 end
1130
1131 protected var isset_checks_count = 0
1132 protected var attr_read_count = 0
1133
1134 fun display_isset_checks do
1135 print "# total number of compiled attribute reads"
1136 print "\t{attr_read_count}"
1137 print "# total number of compiled isset-checks"
1138 print "\t{isset_checks_count}"
1139 end
1140
1141 redef fun compile_nitni_structs
1142 do
1143 self.header.add_decl """
1144 struct nitni_instance \{
1145 struct nitni_instance *next,
1146 *prev; /* adjacent global references in global list */
1147 int count; /* number of time this global reference has been marked */
1148 struct instance *value;
1149 \};
1150 """
1151 super
1152 end
1153
1154 redef fun finalize_ffi_for_module(mmodule)
1155 do
1156 var old_module = self.mainmodule
1157 self.mainmodule = mmodule
1158 super
1159 self.mainmodule = old_module
1160 end
1161 end
1162
1163 # A visitor on the AST of property definition that generate the C code of a separate compilation process.
1164 class SeparateCompilerVisitor
1165 super AbstractCompilerVisitor
1166
1167 redef type COMPILER: SeparateCompiler
1168
1169 redef fun adapt_signature(m, args)
1170 do
1171 var msignature = m.msignature.resolve_for(m.mclassdef.bound_mtype, m.mclassdef.bound_mtype, m.mclassdef.mmodule, true)
1172 var recv = args.first
1173 if recv.mtype.ctype != m.mclassdef.mclass.mclass_type.ctype then
1174 args.first = self.autobox(args.first, m.mclassdef.mclass.mclass_type)
1175 end
1176 for i in [0..msignature.arity[ do
1177 var t = msignature.mparameters[i].mtype
1178 if i == msignature.vararg_rank then
1179 t = args[i+1].mtype
1180 end
1181 args[i+1] = self.autobox(args[i+1], t)
1182 end
1183 end
1184
1185 redef fun unbox_signature_extern(m, args)
1186 do
1187 var msignature = m.msignature.resolve_for(m.mclassdef.bound_mtype, m.mclassdef.bound_mtype, m.mclassdef.mmodule, true)
1188 if not m.mproperty.is_init and m.is_extern then
1189 args.first = self.unbox_extern(args.first, m.mclassdef.mclass.mclass_type)
1190 end
1191 for i in [0..msignature.arity[ do
1192 var t = msignature.mparameters[i].mtype
1193 if i == msignature.vararg_rank then
1194 t = args[i+1].mtype
1195 end
1196 if m.is_extern then args[i+1] = self.unbox_extern(args[i+1], t)
1197 end
1198 end
1199
1200 redef fun autobox(value, mtype)
1201 do
1202 if value.mtype == mtype then
1203 return value
1204 else if not value.mtype.is_c_primitive and not mtype.is_c_primitive then
1205 return value
1206 else if not value.mtype.is_c_primitive then
1207 if mtype.is_tagged then
1208 if mtype.name == "Int" then
1209 return self.new_expr("(long)({value})>>2", mtype)
1210 else if mtype.name == "Char" then
1211 return self.new_expr("(uint32_t)((long)({value})>>2)", mtype)
1212 else if mtype.name == "Bool" then
1213 return self.new_expr("(short int)((long)({value})>>2)", mtype)
1214 else
1215 abort
1216 end
1217 end
1218 return self.new_expr("((struct instance_{mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype)
1219 else if not mtype.is_c_primitive then
1220 assert value.mtype == value.mcasttype
1221 if value.mtype.is_tagged then
1222 var res
1223 if value.mtype.name == "Int" then
1224 res = self.new_expr("(val*)({value}<<2|1)", mtype)
1225 else if value.mtype.name == "Char" then
1226 res = self.new_expr("(val*)((long)({value})<<2|2)", mtype)
1227 else if value.mtype.name == "Bool" then
1228 res = self.new_expr("(val*)((long)({value})<<2|3)", mtype)
1229 else
1230 abort
1231 end
1232 # Do not loose type info
1233 res.mcasttype = value.mcasttype
1234 return res
1235 end
1236 var valtype = value.mtype.as(MClassType)
1237 if mtype isa MClassType and mtype.mclass.kind == extern_kind and mtype.mclass.name != "NativeString" then
1238 valtype = compiler.mainmodule.pointer_type
1239 end
1240 var res = self.new_var(mtype)
1241 # Do not loose type info
1242 res.mcasttype = value.mcasttype
1243 self.require_declaration("BOX_{valtype.c_name}")
1244 self.add("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
1245 return res
1246 else if (value.mtype.ctype == "void*" and mtype.ctype == "void*") or
1247 (value.mtype.ctype == "char*" and mtype.ctype == "void*") or
1248 (value.mtype.ctype == "void*" and mtype.ctype == "char*") then
1249 return value
1250 else
1251 # Bad things will appen!
1252 var res = self.new_var(mtype)
1253 self.add("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
1254 self.add("PRINT_ERROR(\"Cast error: Cannot cast %s to %s.\\n\", \"{value.mtype}\", \"{mtype}\"); fatal_exit(1);")
1255 return res
1256 end
1257 end
1258
1259 redef fun unbox_extern(value, mtype)
1260 do
1261 if mtype isa MClassType and mtype.mclass.kind == extern_kind and
1262 mtype.mclass.name != "NativeString" then
1263 var pointer_type = compiler.mainmodule.pointer_type
1264 var res = self.new_var_extern(mtype)
1265 self.add "{res} = ((struct instance_{pointer_type.c_name}*){value})->value; /* unboxing {value.mtype} */"
1266 return res
1267 else
1268 return value
1269 end
1270 end
1271
1272 redef fun box_extern(value, mtype)
1273 do
1274 if mtype isa MClassType and mtype.mclass.kind == extern_kind and
1275 mtype.mclass.name != "NativeString" then
1276 var valtype = compiler.mainmodule.pointer_type
1277 var res = self.new_var(mtype)
1278 compiler.undead_types.add(mtype)
1279 self.require_declaration("BOX_{valtype.c_name}")
1280 self.add("{res} = BOX_{valtype.c_name}({value}); /* boxing {value.mtype} */")
1281 self.require_declaration("type_{mtype.c_name}")
1282 self.add("{res}->type = &type_{mtype.c_name};")
1283 self.require_declaration("class_{mtype.c_name}")
1284 self.add("{res}->class = &class_{mtype.c_name};")
1285 return res
1286 else
1287 return value
1288 end
1289 end
1290
1291 # Returns a C expression containing the tag of the value as a long.
1292 #
1293 # If the C expression is evaluated to 0, it means there is no tag.
1294 # Thus the expression can be used as a condition.
1295 fun extract_tag(value: RuntimeVariable): String
1296 do
1297 assert not value.mtype.is_c_primitive
1298 return "((long){value}&3)" # Get the two low bits
1299 end
1300
1301 # Returns a C expression of the runtime class structure of the value.
1302 # The point of the method is to work also with primitive types.
1303 fun class_info(value: RuntimeVariable): String
1304 do
1305 if not value.mtype.is_c_primitive then
1306 if can_be_primitive(value) and not compiler.modelbuilder.toolcontext.opt_no_tag_primitives.value then
1307 var tag = extract_tag(value)
1308 return "({tag}?class_info[{tag}]:{value}->class)"
1309 end
1310 return "{value}->class"
1311 else
1312 compiler.undead_types.add(value.mtype)
1313 self.require_declaration("class_{value.mtype.c_name}")
1314 return "(&class_{value.mtype.c_name})"
1315 end
1316 end
1317
1318 # Returns a C expression of the runtime type structure of the value.
1319 # The point of the method is to work also with primitive types.
1320 fun type_info(value: RuntimeVariable): String
1321 do
1322 if not value.mtype.is_c_primitive then
1323 if can_be_primitive(value) and not compiler.modelbuilder.toolcontext.opt_no_tag_primitives.value then
1324 var tag = extract_tag(value)
1325 return "({tag}?type_info[{tag}]:{value}->type)"
1326 end
1327 return "{value}->type"
1328 else
1329 compiler.undead_types.add(value.mtype)
1330 self.require_declaration("type_{value.mtype.c_name}")
1331 return "(&type_{value.mtype.c_name})"
1332 end
1333 end
1334
1335 redef fun compile_callsite(callsite, args)
1336 do
1337 var rta = compiler.runtime_type_analysis
1338 # TODO: Inlining of new-style constructors with initializers
1339 if compiler.modelbuilder.toolcontext.opt_direct_call_monomorph.value and rta != null and callsite.mpropdef.initializers.is_empty then
1340 var tgs = rta.live_targets(callsite)
1341 if tgs.length == 1 then
1342 return direct_call(tgs.first, args)
1343 end
1344 end
1345 # Shortcut intern methods as they are not usually redefinable
1346 if callsite.mpropdef.is_intern and callsite.mproperty.name != "object_id" then
1347 # `object_id` is the only redefined intern method, so it can not be directly called.
1348 # TODO find a less ugly approach?
1349 return direct_call(callsite.mpropdef, args)
1350 end
1351 return super
1352 end
1353
1354 # Fully and directly call a mpropdef
1355 #
1356 # This method is used by `compile_callsite`
1357 private fun direct_call(mpropdef: MMethodDef, args: Array[RuntimeVariable]): nullable RuntimeVariable
1358 do
1359 var res0 = before_send(mpropdef.mproperty, args)
1360 var res = call(mpropdef, mpropdef.mclassdef.bound_mtype, args)
1361 if res0 != null then
1362 assert res != null
1363 self.assign(res0, res)
1364 res = res0
1365 end
1366 add("\}") # close the before_send
1367 return res
1368 end
1369 redef fun send(mmethod, arguments)
1370 do
1371 if arguments.first.mcasttype.is_c_primitive then
1372 # In order to shortcut the primitive, we need to find the most specific method
1373 # Howverr, because of performance (no flattening), we always work on the realmainmodule
1374 var m = self.compiler.mainmodule
1375 self.compiler.mainmodule = self.compiler.realmainmodule
1376 var res = self.monomorphic_send(mmethod, arguments.first.mcasttype, arguments)
1377 self.compiler.mainmodule = m
1378 return res
1379 end
1380
1381 return table_send(mmethod, arguments, mmethod)
1382 end
1383
1384 # Handle common special cases before doing the effective method invocation
1385 # This methods handle the `==` and `!=` methods and the case of the null receiver.
1386 # Note: a { is open in the generated C, that enclose and protect the effective method invocation.
1387 # Client must not forget to close the } after them.
1388 #
1389 # The value returned is the result of the common special cases.
1390 # If not null, client must compile it with the result of their own effective method invocation.
1391 #
1392 # If `before_send` can shortcut the whole message sending, a dummy `if(0){`
1393 # is generated to cancel the effective method invocation that will follow
1394 # TODO: find a better approach
1395 private fun before_send(mmethod: MMethod, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
1396 do
1397 var res: nullable RuntimeVariable = null
1398 var recv = arguments.first
1399 var consider_null = not self.compiler.modelbuilder.toolcontext.opt_no_check_null.value or mmethod.name == "==" or mmethod.name == "!="
1400 var maybenull = (recv.mcasttype isa MNullableType or recv.mcasttype isa MNullType) and consider_null
1401 if maybenull then
1402 self.add("if ({recv} == NULL) \{")
1403 if mmethod.name == "==" or mmethod.name == "is_same_instance" then
1404 res = self.new_var(bool_type)
1405 var arg = arguments[1]
1406 if arg.mcasttype isa MNullableType then
1407 self.add("{res} = ({arg} == NULL);")
1408 else if arg.mcasttype isa MNullType then
1409 self.add("{res} = 1; /* is null */")
1410 else
1411 self.add("{res} = 0; /* {arg.inspect} cannot be null */")
1412 end
1413 else if mmethod.name == "!=" then
1414 res = self.new_var(bool_type)
1415 var arg = arguments[1]
1416 if arg.mcasttype isa MNullableType then
1417 self.add("{res} = ({arg} != NULL);")
1418 else if arg.mcasttype isa MNullType then
1419 self.add("{res} = 0; /* is null */")
1420 else
1421 self.add("{res} = 1; /* {arg.inspect} cannot be null */")
1422 end
1423 else
1424 self.add_abort("Receiver is null")
1425 end
1426 self.add("\} else \{")
1427 else
1428 self.add("\{")
1429 end
1430 if not self.compiler.modelbuilder.toolcontext.opt_no_shortcut_equate.value and (mmethod.name == "==" or mmethod.name == "!=" or mmethod.name == "is_same_instance") then
1431 # Recv is not null, thus if arg is, it is easy to conclude (and respect the invariants)
1432 var arg = arguments[1]
1433 if arg.mcasttype isa MNullType then
1434 if res == null then res = self.new_var(bool_type)
1435 if mmethod.name == "!=" then
1436 self.add("{res} = 1; /* arg is null and recv is not */")
1437 else # `==` and `is_same_instance`
1438 self.add("{res} = 0; /* arg is null but recv is not */")
1439 end
1440 self.add("\}") # closes the null case
1441 self.add("if (0) \{") # what follow is useless, CC will drop it
1442 end
1443 end
1444 return res
1445 end
1446
1447 private fun table_send(mmethod: MMethod, arguments: Array[RuntimeVariable], mentity: MEntity): nullable RuntimeVariable
1448 do
1449 compiler.modelbuilder.nb_invok_by_tables += 1
1450 if compiler.modelbuilder.toolcontext.opt_invocation_metrics.value then add("count_invoke_by_tables++;")
1451
1452 assert arguments.length == mmethod.intro.msignature.arity + 1 else debug("Invalid arity for {mmethod}. {arguments.length} arguments given.")
1453
1454 var res0 = before_send(mmethod, arguments)
1455
1456 var runtime_function = mmethod.intro.virtual_runtime_function
1457 var msignature = runtime_function.called_signature
1458
1459 adapt_signature(mmethod.intro, arguments)
1460
1461 var res: nullable RuntimeVariable
1462 var ret = msignature.return_mtype
1463 if ret == null then
1464 res = null
1465 else
1466 res = self.new_var(ret)
1467 end
1468
1469 var ss = arguments.join(", ")
1470
1471 var const_color = mentity.const_color
1472 var ress
1473 if res != null then
1474 ress = "{res} = "
1475 else
1476 ress = ""
1477 end
1478 if mentity isa MMethod and compiler.modelbuilder.toolcontext.opt_direct_call_monomorph0.value then
1479 # opt_direct_call_monomorph0 is used to compare the efficiency of the alternative lookup implementation, ceteris paribus.
1480 # The difference with the non-zero option is that the monomorphism is looked-at on the mmethod level and not at the callsite level.
1481 # TODO: remove this mess and use per callsite service to detect monomorphism in a single place.
1482 var md = compiler.is_monomorphic(mentity)
1483 if md != null then
1484 var callsym = md.virtual_runtime_function.c_name
1485 self.require_declaration(callsym)
1486 self.add "{ress}{callsym}({ss}); /* {mmethod} on {arguments.first.inspect}*/"
1487 else
1488 self.require_declaration(const_color)
1489 self.add "{ress}(({runtime_function.c_funptrtype})({class_info(arguments.first)}->vft[{const_color}]))({ss}); /* {mmethod} on {arguments.first.inspect}*/"
1490 end
1491 else if mentity isa MMethod and compiler.modelbuilder.toolcontext.opt_guard_call.value then
1492 var callsym = "CALL_" + const_color
1493 self.require_declaration(callsym)
1494 self.add "if (!{callsym}) \{"
1495 self.require_declaration(const_color)
1496 self.add "{ress}(({runtime_function.c_funptrtype})({class_info(arguments.first)}->vft[{const_color}]))({ss}); /* {mmethod} on {arguments.first.inspect}*/"
1497 self.add "\} else \{"
1498 self.add "{ress}{callsym}({ss}); /* {mmethod} on {arguments.first.inspect}*/"
1499 self.add "\}"
1500 else if mentity isa MMethod and compiler.modelbuilder.toolcontext.opt_trampoline_call.value then
1501 var callsym = "CALL_" + const_color
1502 self.require_declaration(callsym)
1503 self.add "{ress}{callsym}({ss}); /* {mmethod} on {arguments.first.inspect}*/"
1504 else
1505 self.require_declaration(const_color)
1506 self.add "{ress}(({runtime_function.c_funptrtype})({class_info(arguments.first)}->vft[{const_color}]))({ss}); /* {mmethod} on {arguments.first.inspect}*/"
1507 end
1508
1509 if res0 != null then
1510 assert res != null
1511 assign(res0,res)
1512 res = res0
1513 end
1514
1515 self.add("\}") # closes the null case
1516
1517 return res
1518 end
1519
1520 redef fun call(mmethoddef, recvtype, arguments)
1521 do
1522 assert arguments.length == mmethoddef.msignature.arity + 1 else debug("Invalid arity for {mmethoddef}. {arguments.length} arguments given.")
1523
1524 var res: nullable RuntimeVariable
1525 var ret = mmethoddef.msignature.return_mtype
1526 if ret == null then
1527 res = null
1528 else
1529 ret = ret.resolve_for(mmethoddef.mclassdef.bound_mtype, mmethoddef.mclassdef.bound_mtype, mmethoddef.mclassdef.mmodule, true)
1530 res = self.new_var(ret)
1531 end
1532
1533 if (mmethoddef.is_intern and not compiler.modelbuilder.toolcontext.opt_no_inline_intern.value) or
1534 (compiler.modelbuilder.toolcontext.opt_inline_some_methods.value and mmethoddef.can_inline(self)) then
1535 compiler.modelbuilder.nb_invok_by_inline += 1
1536 if compiler.modelbuilder.toolcontext.opt_invocation_metrics.value then add("count_invoke_by_inline++;")
1537 var frame = new StaticFrame(self, mmethoddef, recvtype, arguments)
1538 frame.returnlabel = self.get_name("RET_LABEL")
1539 frame.returnvar = res
1540 var old_frame = self.frame
1541 self.frame = frame
1542 self.add("\{ /* Inline {mmethoddef} ({arguments.join(",")}) on {arguments.first.inspect} */")
1543 mmethoddef.compile_inside_to_c(self, arguments)
1544 self.add("{frame.returnlabel.as(not null)}:(void)0;")
1545 self.add("\}")
1546 self.frame = old_frame
1547 return res
1548 end
1549 compiler.modelbuilder.nb_invok_by_direct += 1
1550 if compiler.modelbuilder.toolcontext.opt_invocation_metrics.value then add("count_invoke_by_direct++;")
1551
1552 # Autobox arguments
1553 self.adapt_signature(mmethoddef, arguments)
1554
1555 self.require_declaration(mmethoddef.c_name)
1556 if res == null then
1557 self.add("{mmethoddef.c_name}({arguments.join(", ")}); /* Direct call {mmethoddef} on {arguments.first.inspect}*/")
1558 return null
1559 else
1560 self.add("{res} = {mmethoddef.c_name}({arguments.join(", ")});")
1561 end
1562
1563 return res
1564 end
1565
1566 redef fun supercall(m: MMethodDef, recvtype: MClassType, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
1567 do
1568 if arguments.first.mcasttype.is_c_primitive then
1569 # In order to shortcut the primitive, we need to find the most specific method
1570 # However, because of performance (no flattening), we always work on the realmainmodule
1571 var main = self.compiler.mainmodule
1572 self.compiler.mainmodule = self.compiler.realmainmodule
1573 var res = self.monomorphic_super_send(m, recvtype, arguments)
1574 self.compiler.mainmodule = main
1575 return res
1576 end
1577 return table_send(m.mproperty, arguments, m)
1578 end
1579
1580 redef fun vararg_instance(mpropdef, recv, varargs, elttype)
1581 do
1582 # A vararg must be stored into an new array
1583 # The trick is that the dymaic type of the array may depends on the receiver
1584 # of the method (ie recv) if the static type is unresolved
1585 # This is more complex than usual because the unresolved type must not be resolved
1586 # with the current receiver (ie self).
1587 # Therefore to isolate the resolution from self, a local StaticFrame is created.
1588 # One can see this implementation as an inlined method of the receiver whose only
1589 # job is to allocate the array
1590 var old_frame = self.frame
1591 var frame = new StaticFrame(self, mpropdef, mpropdef.mclassdef.bound_mtype, [recv])
1592 self.frame = frame
1593 #print "required Array[{elttype}] for recv {recv.inspect}. bound=Array[{self.resolve_for(elttype, recv)}]. selfvar={frame.arguments.first.inspect}"
1594 var res = self.array_instance(varargs, elttype)
1595 self.frame = old_frame
1596 return res
1597 end
1598
1599 redef fun isset_attribute(a, recv)
1600 do
1601 self.check_recv_notnull(recv)
1602 var res = self.new_var(bool_type)
1603
1604 # What is the declared type of the attribute?
1605 var mtype = a.intro.static_mtype.as(not null)
1606 var intromclassdef = a.intro.mclassdef
1607 mtype = mtype.resolve_for(intromclassdef.bound_mtype, intromclassdef.bound_mtype, intromclassdef.mmodule, true)
1608
1609 if mtype isa MNullableType then
1610 self.add("{res} = 1; /* easy isset: {a} on {recv.inspect} */")
1611 return res
1612 end
1613
1614 self.require_declaration(a.const_color)
1615 if self.compiler.modelbuilder.toolcontext.opt_no_union_attribute.value then
1616 self.add("{res} = {recv}->attrs[{a.const_color}] != NULL; /* {a} on {recv.inspect}*/")
1617 else
1618
1619 if not mtype.is_c_primitive and not mtype.is_tagged then
1620 self.add("{res} = {recv}->attrs[{a.const_color}].val != NULL; /* {a} on {recv.inspect} */")
1621 else
1622 self.add("{res} = 1; /* NOT YET IMPLEMENTED: isset of primitives: {a} on {recv.inspect} */")
1623 end
1624 end
1625 return res
1626 end
1627
1628 redef fun read_attribute(a, recv)
1629 do
1630 self.check_recv_notnull(recv)
1631
1632 # What is the declared type of the attribute?
1633 var ret = a.intro.static_mtype.as(not null)
1634 var intromclassdef = a.intro.mclassdef
1635 ret = ret.resolve_for(intromclassdef.bound_mtype, intromclassdef.bound_mtype, intromclassdef.mmodule, true)
1636
1637 if self.compiler.modelbuilder.toolcontext.opt_isset_checks_metrics.value then
1638 self.compiler.attr_read_count += 1
1639 self.add("count_attr_reads++;")
1640 end
1641
1642 self.require_declaration(a.const_color)
1643 if self.compiler.modelbuilder.toolcontext.opt_no_union_attribute.value then
1644 # Get the attribute or a box (ie. always a val*)
1645 var cret = self.object_type.as_nullable
1646 var res = self.new_var(cret)
1647 res.mcasttype = ret
1648
1649 self.add("{res} = {recv}->attrs[{a.const_color}]; /* {a} on {recv.inspect} */")
1650
1651 # Check for Uninitialized attribute
1652 if not ret isa MNullableType and not self.compiler.modelbuilder.toolcontext.opt_no_check_attr_isset.value then
1653 self.add("if (unlikely({res} == NULL)) \{")
1654 self.add_abort("Uninitialized attribute {a.name}")
1655 self.add("\}")
1656
1657 if self.compiler.modelbuilder.toolcontext.opt_isset_checks_metrics.value then
1658 self.compiler.isset_checks_count += 1
1659 self.add("count_isset_checks++;")
1660 end
1661 end
1662
1663 # Return the attribute or its unboxed version
1664 # Note: it is mandatory since we reuse the box on write, we do not whant that the box escapes
1665 return self.autobox(res, ret)
1666 else
1667 var res = self.new_var(ret)
1668 self.add("{res} = {recv}->attrs[{a.const_color}].{ret.ctypename}; /* {a} on {recv.inspect} */")
1669
1670 # Check for Uninitialized attribute
1671 if not ret.is_c_primitive and not ret isa MNullableType and not self.compiler.modelbuilder.toolcontext.opt_no_check_attr_isset.value then
1672 self.add("if (unlikely({res} == NULL)) \{")
1673 self.add_abort("Uninitialized attribute {a.name}")
1674 self.add("\}")
1675 if self.compiler.modelbuilder.toolcontext.opt_isset_checks_metrics.value then
1676 self.compiler.isset_checks_count += 1
1677 self.add("count_isset_checks++;")
1678 end
1679 end
1680
1681 return res
1682 end
1683 end
1684
1685 redef fun write_attribute(a, recv, value)
1686 do
1687 self.check_recv_notnull(recv)
1688
1689 # What is the declared type of the attribute?
1690 var mtype = a.intro.static_mtype.as(not null)
1691 var intromclassdef = a.intro.mclassdef
1692 mtype = mtype.resolve_for(intromclassdef.bound_mtype, intromclassdef.bound_mtype, intromclassdef.mmodule, true)
1693
1694 # Adapt the value to the declared type
1695 value = self.autobox(value, mtype)
1696
1697 self.require_declaration(a.const_color)
1698 if self.compiler.modelbuilder.toolcontext.opt_no_union_attribute.value then
1699 var attr = "{recv}->attrs[{a.const_color}]"
1700 if mtype.is_tagged then
1701 # The attribute is not primitive, thus store it as tagged
1702 var tv = autobox(value, compiler.mainmodule.object_type)
1703 self.add("{attr} = {tv}; /* {a} on {recv.inspect} */")
1704 else if mtype.is_c_primitive then
1705 assert mtype isa MClassType
1706 # The attribute is primitive, thus we store it in a box
1707 # The trick is to create the box the first time then resuse the box
1708 self.add("if ({attr} != NULL) \{")
1709 self.add("((struct instance_{mtype.c_name}*){attr})->value = {value}; /* {a} on {recv.inspect} */")
1710 self.add("\} else \{")
1711 value = self.autobox(value, self.object_type.as_nullable)
1712 self.add("{attr} = {value}; /* {a} on {recv.inspect} */")
1713 self.add("\}")
1714 else
1715 # The attribute is not primitive, thus store it direclty
1716 self.add("{attr} = {value}; /* {a} on {recv.inspect} */")
1717 end
1718 else
1719 self.add("{recv}->attrs[{a.const_color}].{mtype.ctypename} = {value}; /* {a} on {recv.inspect} */")
1720 end
1721 end
1722
1723 # Check that mtype is a live open type
1724 fun hardening_live_open_type(mtype: MType)
1725 do
1726 if not compiler.modelbuilder.toolcontext.opt_hardening.value then return
1727 self.require_declaration(mtype.const_color)
1728 var col = mtype.const_color
1729 self.add("if({col} == -1) \{")
1730 self.add("PRINT_ERROR(\"Resolution of a dead open type: %s\\n\", \"{mtype.to_s.escape_to_c}\");")
1731 self.add_abort("open type dead")
1732 self.add("\}")
1733 end
1734
1735 # Check that mtype it a pointer to a live cast type
1736 fun hardening_cast_type(t: String)
1737 do
1738 if not compiler.modelbuilder.toolcontext.opt_hardening.value then return
1739 add("if({t} == NULL) \{")
1740 add_abort("cast type null")
1741 add("\}")
1742 add("if({t}->id == -1 || {t}->color == -1) \{")
1743 add("PRINT_ERROR(\"Try to cast on a dead cast type: %s\\n\", {t}->name);")
1744 add_abort("cast type dead")
1745 add("\}")
1746 end
1747
1748 redef fun init_instance(mtype)
1749 do
1750 self.require_declaration("NEW_{mtype.mclass.c_name}")
1751 var compiler = self.compiler
1752 if mtype isa MGenericType and mtype.need_anchor then
1753 hardening_live_open_type(mtype)
1754 link_unresolved_type(self.frame.mpropdef.mclassdef, mtype)
1755 var recv = self.frame.arguments.first
1756 var recv_type_info = self.type_info(recv)
1757 self.require_declaration(mtype.const_color)
1758 return self.new_expr("NEW_{mtype.mclass.c_name}({recv_type_info}->resolution_table->types[{mtype.const_color}])", mtype)
1759 end
1760 compiler.undead_types.add(mtype)
1761 self.require_declaration("type_{mtype.c_name}")
1762 return self.new_expr("NEW_{mtype.mclass.c_name}(&type_{mtype.c_name})", mtype)
1763 end
1764
1765 redef fun type_test(value, mtype, tag)
1766 do
1767 self.add("/* {value.inspect} isa {mtype} */")
1768 var compiler = self.compiler
1769
1770 var recv = self.frame.arguments.first
1771 var recv_type_info = self.type_info(recv)
1772
1773 var res = self.new_var(bool_type)
1774
1775 var cltype = self.get_name("cltype")
1776 self.add_decl("int {cltype};")
1777 var idtype = self.get_name("idtype")
1778 self.add_decl("int {idtype};")
1779
1780 var maybe_null = self.maybe_null(value)
1781 var accept_null = "0"
1782 var ntype = mtype
1783 if ntype isa MNullableType then
1784 ntype = ntype.mtype
1785 accept_null = "1"
1786 end
1787
1788 if value.mcasttype.is_subtype(self.frame.mpropdef.mclassdef.mmodule, self.frame.mpropdef.mclassdef.bound_mtype, mtype) then
1789 self.add("{res} = 1; /* easy {value.inspect} isa {mtype}*/")
1790 if compiler.modelbuilder.toolcontext.opt_typing_test_metrics.value then
1791 self.compiler.count_type_test_skipped[tag] += 1
1792 self.add("count_type_test_skipped_{tag}++;")
1793 end
1794 return res
1795 end
1796
1797 if ntype.need_anchor then
1798 var type_struct = self.get_name("type_struct")
1799 self.add_decl("const struct type* {type_struct};")
1800
1801 # Either with resolution_table with a direct resolution
1802 hardening_live_open_type(mtype)
1803 link_unresolved_type(self.frame.mpropdef.mclassdef, mtype)
1804 self.require_declaration(mtype.const_color)
1805 self.add("{type_struct} = {recv_type_info}->resolution_table->types[{mtype.const_color}];")
1806 if compiler.modelbuilder.toolcontext.opt_typing_test_metrics.value then
1807 self.compiler.count_type_test_unresolved[tag] += 1
1808 self.add("count_type_test_unresolved_{tag}++;")
1809 end
1810 hardening_cast_type(type_struct)
1811 self.add("{cltype} = {type_struct}->color;")
1812 self.add("{idtype} = {type_struct}->id;")
1813 if maybe_null and accept_null == "0" then
1814 var is_nullable = self.get_name("is_nullable")
1815 self.add_decl("short int {is_nullable};")
1816 self.add("{is_nullable} = {type_struct}->is_nullable;")
1817 accept_null = is_nullable.to_s
1818 end
1819 else if ntype isa MClassType then
1820 compiler.undead_types.add(mtype)
1821 self.require_declaration("type_{mtype.c_name}")
1822 hardening_cast_type("(&type_{mtype.c_name})")
1823 self.add("{cltype} = type_{mtype.c_name}.color;")
1824 self.add("{idtype} = type_{mtype.c_name}.id;")
1825 if compiler.modelbuilder.toolcontext.opt_typing_test_metrics.value then
1826 self.compiler.count_type_test_resolved[tag] += 1
1827 self.add("count_type_test_resolved_{tag}++;")
1828 end
1829 else
1830 self.add("PRINT_ERROR(\"NOT YET IMPLEMENTED: type_test(%s, {mtype}).\\n\", \"{value.inspect}\"); fatal_exit(1);")
1831 end
1832
1833 # check color is in table
1834 if maybe_null then
1835 self.add("if({value} == NULL) \{")
1836 self.add("{res} = {accept_null};")
1837 self.add("\} else \{")
1838 end
1839 var value_type_info = self.type_info(value)
1840 self.add("if({cltype} >= {value_type_info}->table_size) \{")
1841 self.add("{res} = 0;")
1842 self.add("\} else \{")
1843 self.add("{res} = {value_type_info}->type_table[{cltype}] == {idtype};")
1844 self.add("\}")
1845 if maybe_null then
1846 self.add("\}")
1847 end
1848
1849 return res
1850 end
1851
1852 redef fun is_same_type_test(value1, value2)
1853 do
1854 var res = self.new_var(bool_type)
1855 # Swap values to be symetric
1856 if value2.mtype.is_c_primitive and not value1.mtype.is_c_primitive then
1857 var tmp = value1
1858 value1 = value2
1859 value2 = tmp
1860 end
1861 if value1.mtype.is_c_primitive then
1862 if value2.mtype == value1.mtype then
1863 self.add("{res} = 1; /* is_same_type_test: compatible types {value1.mtype} vs. {value2.mtype} */")
1864 else if value2.mtype.is_c_primitive then
1865 self.add("{res} = 0; /* is_same_type_test: incompatible types {value1.mtype} vs. {value2.mtype}*/")
1866 else
1867 var mtype1 = value1.mtype.as(MClassType)
1868 self.require_declaration("class_{mtype1.c_name}")
1869 self.add("{res} = ({value2} != NULL) && ({class_info(value2)} == &class_{mtype1.c_name}); /* is_same_type_test */")
1870 end
1871 else
1872 self.add("{res} = ({value1} == {value2}) || ({value1} != NULL && {value2} != NULL && {class_info(value1)} == {class_info(value2)}); /* is_same_type_test */")
1873 end
1874 return res
1875 end
1876
1877 redef fun class_name_string(value)
1878 do
1879 var res = self.get_name("var_class_name")
1880 self.add_decl("const char* {res};")
1881 if not value.mtype.is_c_primitive then
1882 self.add "{res} = {value} == NULL ? \"null\" : {type_info(value)}->name;"
1883 else if value.mtype isa MClassType and value.mtype.as(MClassType).mclass.kind == extern_kind and
1884 value.mtype.as(MClassType).name != "NativeString" then
1885 self.add "{res} = \"{value.mtype.as(MClassType).mclass}\";"
1886 else
1887 self.require_declaration("type_{value.mtype.c_name}")
1888 self.add "{res} = type_{value.mtype.c_name}.name;"
1889 end
1890 return res
1891 end
1892
1893 redef fun equal_test(value1, value2)
1894 do
1895 var res = self.new_var(bool_type)
1896 if value2.mtype.is_c_primitive and not value1.mtype.is_c_primitive then
1897 var tmp = value1
1898 value1 = value2
1899 value2 = tmp
1900 end
1901 if value1.mtype.is_c_primitive then
1902 var t1 = value1.mtype
1903 assert t1 == value1.mcasttype
1904
1905 # Fast case: same C type.
1906 if value2.mtype == t1 then
1907 # Same exact C primitive representation.
1908 self.add("{res} = {value1} == {value2};")
1909 return res
1910 end
1911
1912 # Complex case: value2 has a different representation
1913 # Thus, it should be checked if `value2` is type-compatible with `value1`
1914 # This compatibility is done statically if possible and dynamically else
1915
1916 # Conjunction (ands) of dynamic tests according to the static knowledge
1917 var tests = new Array[String]
1918
1919 var t2 = value2.mcasttype
1920 if t2 isa MNullableType then
1921 # The destination type cannot be null
1922 tests.add("({value2} != NULL)")
1923 t2 = t2.mtype
1924 else if t2 isa MNullType then
1925 # `value2` is known to be null, thus incompatible with a primitive
1926 self.add("{res} = 0; /* incompatible types {t1} vs. {t2}*/")
1927 return res
1928 end
1929
1930 if t2 == t1 then
1931 # Same type but different representation.
1932 else if t2.is_c_primitive then
1933 # Type of `value2` is a different primitive type, thus incompatible
1934 self.add("{res} = 0; /* incompatible types {t1} vs. {t2}*/")
1935 return res
1936 else if t1.is_tagged then
1937 # To be equal, `value2` should also be correctly tagged
1938 tests.add("({extract_tag(value2)} == {t1.tag_value})")
1939 else
1940 # To be equal, `value2` should also be boxed with the same class
1941 self.require_declaration("class_{t1.c_name}")
1942 tests.add "({class_info(value2)} == &class_{t1.c_name})"
1943 end
1944
1945 # Compare the unboxed `value2` with `value1`
1946 if tests.not_empty then
1947 self.add "if ({tests.join(" && ")}) \{"
1948 end
1949 self.add "{res} = {self.autobox(value2, t1)} == {value1};"
1950 if tests.not_empty then
1951 self.add "\} else {res} = 0;"
1952 end
1953
1954 return res
1955 end
1956 var maybe_null = true
1957 var test = new Array[String]
1958 var t1 = value1.mcasttype
1959 if t1 isa MNullableType then
1960 test.add("{value1} != NULL")
1961 t1 = t1.mtype
1962 else
1963 maybe_null = false
1964 end
1965 var t2 = value2.mcasttype
1966 if t2 isa MNullableType then
1967 test.add("{value2} != NULL")
1968 t2 = t2.mtype
1969 else
1970 maybe_null = false
1971 end
1972
1973 var incompatible = false
1974 var primitive
1975 if t1.is_c_primitive then
1976 primitive = t1
1977 if t1 == t2 then
1978 # No need to compare class
1979 else if t2.is_c_primitive then
1980 incompatible = true
1981 else if can_be_primitive(value2) then
1982 if t1.is_tagged then
1983 self.add("{res} = {value1} == {value2};")
1984 return res
1985 end
1986 if not compiler.modelbuilder.toolcontext.opt_no_tag_primitives.value then
1987 test.add("(!{extract_tag(value2)})")
1988 end
1989 test.add("{value1}->class == {value2}->class")
1990 else
1991 incompatible = true
1992 end
1993 else if t2.is_c_primitive then
1994 primitive = t2
1995 if can_be_primitive(value1) then
1996 if t2.is_tagged then
1997 self.add("{res} = {value1} == {value2};")
1998 return res
1999 end
2000 if not compiler.modelbuilder.toolcontext.opt_no_tag_primitives.value then
2001 test.add("(!{extract_tag(value1)})")
2002 end
2003 test.add("{value1}->class == {value2}->class")
2004 else
2005 incompatible = true
2006 end
2007 else
2008 primitive = null
2009 end
2010
2011 if incompatible then
2012 if maybe_null then
2013 self.add("{res} = {value1} == {value2}; /* incompatible types {t1} vs. {t2}; but may be NULL*/")
2014 return res
2015 else
2016 self.add("{res} = 0; /* incompatible types {t1} vs. {t2}; cannot be NULL */")
2017 return res
2018 end
2019 end
2020 if primitive != null then
2021 if primitive.is_tagged then
2022 self.add("{res} = {value1} == {value2};")
2023 return res
2024 end
2025 test.add("((struct instance_{primitive.c_name}*){value1})->value == ((struct instance_{primitive.c_name}*){value2})->value")
2026 else if can_be_primitive(value1) and can_be_primitive(value2) then
2027 if not compiler.modelbuilder.toolcontext.opt_no_tag_primitives.value then
2028 test.add("(!{extract_tag(value1)}) && (!{extract_tag(value2)})")
2029 end
2030 test.add("{value1}->class == {value2}->class")
2031 var s = new Array[String]
2032 for t, v in self.compiler.box_kinds do
2033 if t.mclass_type.is_tagged then continue
2034 s.add "({value1}->class->box_kind == {v} && ((struct instance_{t.c_name}*){value1})->value == ((struct instance_{t.c_name}*){value2})->value)"
2035 end
2036 if s.is_empty then
2037 self.add("{res} = {value1} == {value2};")
2038 return res
2039 end
2040 test.add("({s.join(" || ")})")
2041 else
2042 self.add("{res} = {value1} == {value2};")
2043 return res
2044 end
2045 self.add("{res} = {value1} == {value2} || ({test.join(" && ")});")
2046 return res
2047 end
2048
2049 fun can_be_primitive(value: RuntimeVariable): Bool
2050 do
2051 var t = value.mcasttype.undecorate
2052 if not t isa MClassType then return false
2053 var k = t.mclass.kind
2054 return k == interface_kind or t.is_c_primitive
2055 end
2056
2057 fun maybe_null(value: RuntimeVariable): Bool
2058 do
2059 var t = value.mcasttype
2060 return t isa MNullableType or t isa MNullType
2061 end
2062
2063 redef fun array_instance(array, elttype)
2064 do
2065 var nclass = mmodule.native_array_class
2066 var arrayclass = mmodule.array_class
2067 var arraytype = arrayclass.get_mtype([elttype])
2068 var res = self.init_instance(arraytype)
2069 self.add("\{ /* {res} = array_instance Array[{elttype}] */")
2070 var length = self.int_instance(array.length)
2071 var nat = native_array_instance(elttype, length)
2072 for i in [0..array.length[ do
2073 var r = self.autobox(array[i], self.object_type)
2074 self.add("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
2075 end
2076 self.send(self.get_property("with_native", arrayclass.intro.bound_mtype), [res, nat, length])
2077 self.add("\}")
2078 return res
2079 end
2080
2081 redef fun native_array_instance(elttype: MType, length: RuntimeVariable): RuntimeVariable
2082 do
2083 var mtype = mmodule.native_array_type(elttype)
2084 self.require_declaration("NEW_{mtype.mclass.c_name}")
2085 assert mtype isa MGenericType
2086 var compiler = self.compiler
2087 length = autobox(length, compiler.mainmodule.int_type)
2088 if mtype.need_anchor then
2089 hardening_live_open_type(mtype)
2090 link_unresolved_type(self.frame.mpropdef.mclassdef, mtype)
2091 var recv = self.frame.arguments.first
2092 var recv_type_info = self.type_info(recv)
2093 self.require_declaration(mtype.const_color)
2094 return self.new_expr("NEW_{mtype.mclass.c_name}({length}, {recv_type_info}->resolution_table->types[{mtype.const_color}])", mtype)
2095 end
2096 compiler.undead_types.add(mtype)
2097 self.require_declaration("type_{mtype.c_name}")
2098 return self.new_expr("NEW_{mtype.mclass.c_name}({length}, &type_{mtype.c_name})", mtype)
2099 end
2100
2101 redef fun native_array_def(pname, ret_type, arguments)
2102 do
2103 var elttype = arguments.first.mtype
2104 var nclass = mmodule.native_array_class
2105 var recv = "((struct instance_{nclass.c_name}*){arguments[0]})->values"
2106 if pname == "[]" then
2107 # Because the objects are boxed, return the box to avoid unnecessary (or broken) unboxing/reboxing
2108 var res = self.new_expr("{recv}[{arguments[1]}]", compiler.mainmodule.object_type)
2109 res.mcasttype = ret_type.as(not null)
2110 self.ret(res)
2111 return
2112 else if pname == "[]=" then
2113 self.add("{recv}[{arguments[1]}]={arguments[2]};")
2114 return
2115 else if pname == "length" then
2116 self.ret(self.new_expr("((struct instance_{nclass.c_name}*){arguments[0]})->length", ret_type.as(not null)))
2117 return
2118 else if pname == "copy_to" then
2119 var recv1 = "((struct instance_{nclass.c_name}*){arguments[1]})->values"
2120 self.add("memmove({recv1}, {recv}, {arguments[2]}*sizeof({elttype.ctype}));")
2121 return
2122 end
2123 end
2124
2125 redef fun native_array_get(nat, i)
2126 do
2127 var nclass = mmodule.native_array_class
2128 var recv = "((struct instance_{nclass.c_name}*){nat})->values"
2129 # Because the objects are boxed, return the box to avoid unnecessary (or broken) unboxing/reboxing
2130 var res = self.new_expr("{recv}[{i}]", compiler.mainmodule.object_type)
2131 return res
2132 end
2133
2134 redef fun native_array_set(nat, i, val)
2135 do
2136 var nclass = mmodule.native_array_class
2137 var recv = "((struct instance_{nclass.c_name}*){nat})->values"
2138 self.add("{recv}[{i}]={val};")
2139 end
2140
2141 fun link_unresolved_type(mclassdef: MClassDef, mtype: MType) do
2142 assert mtype.need_anchor
2143 var compiler = self.compiler
2144 if not compiler.live_unresolved_types.has_key(self.frame.mpropdef.mclassdef) then
2145 compiler.live_unresolved_types[self.frame.mpropdef.mclassdef] = new HashSet[MType]
2146 end
2147 compiler.live_unresolved_types[self.frame.mpropdef.mclassdef].add(mtype)
2148 end
2149 end
2150
2151 redef class MMethodDef
2152 # The C function associated to a mmethoddef
2153 fun separate_runtime_function: SeparateRuntimeFunction
2154 do
2155 var res = self.separate_runtime_function_cache
2156 if res == null then
2157 var recv = mclassdef.bound_mtype
2158 var msignature = msignature.resolve_for(recv, recv, mclassdef.mmodule, true)
2159 res = new SeparateRuntimeFunction(self, recv, msignature, c_name)
2160 self.separate_runtime_function_cache = res
2161 end
2162 return res
2163 end
2164 private var separate_runtime_function_cache: nullable SeparateRuntimeFunction
2165
2166 # The C function associated to a mmethoddef, that can be stored into a VFT of a class
2167 # The first parameter (the reciever) is always typed by val* in order to accept an object value
2168 # The C-signature is always compatible with the intro
2169 fun virtual_runtime_function: SeparateRuntimeFunction
2170 do
2171 var res = self.virtual_runtime_function_cache
2172 if res == null then
2173 # Because the function is virtual, the signature must match the one of the original class
2174 var intromclassdef = mproperty.intro.mclassdef
2175 var recv = intromclassdef.bound_mtype
2176
2177 res = separate_runtime_function
2178 if res.called_recv == recv then
2179 self.virtual_runtime_function_cache = res
2180 return res
2181 end
2182
2183 var msignature = mproperty.intro.msignature.resolve_for(recv, recv, intromclassdef.mmodule, true)
2184
2185 if recv.ctype == res.called_recv.ctype and msignature.c_equiv(res.called_signature) then
2186 self.virtual_runtime_function_cache = res
2187 return res
2188 end
2189
2190 res = new SeparateRuntimeFunction(self, recv, msignature, "VIRTUAL_{c_name}")
2191 self.virtual_runtime_function_cache = res
2192 res.is_thunk = true
2193 end
2194 return res
2195 end
2196 private var virtual_runtime_function_cache: nullable SeparateRuntimeFunction
2197 end
2198
2199 redef class MSignature
2200 # Does the C-version of `self` the same than the C-version of `other`?
2201 fun c_equiv(other: MSignature): Bool
2202 do
2203 if self == other then return true
2204 if arity != other.arity then return false
2205 for i in [0..arity[ do
2206 if mparameters[i].mtype.ctype != other.mparameters[i].mtype.ctype then return false
2207 end
2208 if return_mtype != other.return_mtype then
2209 if return_mtype == null or other.return_mtype == null then return false
2210 if return_mtype.ctype != other.return_mtype.ctype then return false
2211 end
2212 return true
2213 end
2214 end
2215
2216 # The C function associated to a methoddef separately compiled
2217 class SeparateRuntimeFunction
2218 super AbstractRuntimeFunction
2219
2220 # The call-side static receiver
2221 var called_recv: MType
2222
2223 # The call-side static signature
2224 var called_signature: MSignature
2225
2226 # The name on the compiled method
2227 redef var build_c_name: String
2228
2229 # Statically call the original body instead
2230 var is_thunk = false
2231
2232 redef fun to_s do return self.mmethoddef.to_s
2233
2234 # The C return type (something or `void`)
2235 var c_ret: String is lazy do
2236 var ret = called_signature.return_mtype
2237 if ret != null then
2238 return ret.ctype
2239 else
2240 return "void"
2241 end
2242 end
2243
2244 # The C signature (only the parmeter part)
2245 var c_sig: String is lazy do
2246 var sig = new FlatBuffer
2247 sig.append("({called_recv.ctype} self")
2248 for i in [0..called_signature.arity[ do
2249 var mtype = called_signature.mparameters[i].mtype
2250 if i == called_signature.vararg_rank then
2251 mtype = mmethoddef.mclassdef.mmodule.array_type(mtype)
2252 end
2253 sig.append(", {mtype.ctype} p{i}")
2254 end
2255 sig.append(")")
2256 return sig.to_s
2257 end
2258
2259 # The C type for the function pointer.
2260 var c_funptrtype: String is lazy do return "{c_ret}(*){c_sig}"
2261
2262 redef fun compile_to_c(compiler)
2263 do
2264 var mmethoddef = self.mmethoddef
2265
2266 var sig = "{c_ret} {c_name}{c_sig}"
2267 compiler.provide_declaration(self.c_name, "{sig};")
2268
2269 var rta = compiler.as(SeparateCompiler).runtime_type_analysis
2270
2271 var recv = self.mmethoddef.mclassdef.bound_mtype
2272 var v = compiler.new_visitor
2273 var selfvar = new RuntimeVariable("self", called_recv, recv)
2274 var arguments = new Array[RuntimeVariable]
2275 var frame = new StaticFrame(v, mmethoddef, recv, arguments)
2276 v.frame = frame
2277
2278 var msignature = called_signature
2279 var ret = called_signature.return_mtype
2280
2281 var comment = new FlatBuffer
2282 comment.append("({selfvar}: {selfvar.mtype}")
2283 arguments.add(selfvar)
2284 for i in [0..msignature.arity[ do
2285 var mtype = msignature.mparameters[i].mtype
2286 if i == msignature.vararg_rank then
2287 mtype = v.mmodule.array_type(mtype)
2288 end
2289 comment.append(", {mtype}")
2290 var argvar = new RuntimeVariable("p{i}", mtype, mtype)
2291 arguments.add(argvar)
2292 end
2293 comment.append(")")
2294 if ret != null then
2295 comment.append(": {ret}")
2296 end
2297
2298 v.add_decl("/* method {self} for {comment} */")
2299 v.add_decl("{sig} \{")
2300 if ret != null then
2301 frame.returnvar = v.new_var(ret)
2302 end
2303 frame.returnlabel = v.get_name("RET_LABEL")
2304
2305 if is_thunk then
2306 var subret = v.call(mmethoddef, recv, arguments)
2307 if ret != null then
2308 assert subret != null
2309 v.assign(frame.returnvar.as(not null), subret)
2310 end
2311 else if rta != null and not rta.live_mmodules.has(mmethoddef.mclassdef.mmodule) then
2312 v.add_abort("FATAL: Dead method executed.")
2313 else
2314 mmethoddef.compile_inside_to_c(v, arguments)
2315 end
2316
2317 v.add("{frame.returnlabel.as(not null)}:;")
2318 if ret != null then
2319 v.add("return {frame.returnvar.as(not null)};")
2320 end
2321 v.add("\}")
2322 compiler.names[self.c_name] = "{mmethoddef.full_name} ({mmethoddef.location.file.filename}:{mmethoddef.location.line_start})"
2323 end
2324
2325 # Compile the trampolines used to implement late-binding.
2326 #
2327 # See `opt_trampoline_call`.
2328 fun compile_trampolines(compiler: SeparateCompiler)
2329 do
2330 var recv = self.mmethoddef.mclassdef.bound_mtype
2331 var selfvar = new RuntimeVariable("self", called_recv, recv)
2332 var ret = called_signature.return_mtype
2333 var arguments = ["self"]
2334 for i in [0..called_signature.arity[ do arguments.add "p{i}"
2335
2336 if mmethoddef.is_intro and not recv.is_c_primitive then
2337 var m = mmethoddef.mproperty
2338 var n2 = "CALL_" + m.const_color
2339 compiler.provide_declaration(n2, "{c_ret} {n2}{c_sig};")
2340 var v2 = compiler.new_visitor
2341 v2.add "{c_ret} {n2}{c_sig} \{"
2342 v2.require_declaration(m.const_color)
2343 var call = "(({c_funptrtype})({v2.class_info(selfvar)}->vft[{m.const_color}]))({arguments.join(", ")});"
2344 if ret != null then
2345 v2.add "return {call}"
2346 else
2347 v2.add call
2348 end
2349
2350 v2.add "\}"
2351
2352 end
2353 if mmethoddef.has_supercall and not recv.is_c_primitive then
2354 var m = mmethoddef
2355 var n2 = "CALL_" + m.const_color
2356 compiler.provide_declaration(n2, "{c_ret} {n2}{c_sig};")
2357 var v2 = compiler.new_visitor
2358 v2.add "{c_ret} {n2}{c_sig} \{"
2359 v2.require_declaration(m.const_color)
2360 var call = "(({c_funptrtype})({v2.class_info(selfvar)}->vft[{m.const_color}]))({arguments.join(", ")});"
2361 if ret != null then
2362 v2.add "return {call}"
2363 else
2364 v2.add call
2365 end
2366
2367 v2.add "\}"
2368 end
2369 end
2370 end
2371
2372 redef class MType
2373 # Are values of `self` tagged?
2374 # If false, it means that the type is not primitive, or is boxed.
2375 var is_tagged = false
2376
2377 # The tag value of the type
2378 #
2379 # ENSURE `is_tagged == (tag_value > 0)`
2380 # ENSURE `not is_tagged == (tag_value == 0)`
2381 var tag_value = 0
2382 end
2383
2384 redef class MEntity
2385 var const_color: String is lazy do return "COLOR_{c_name}"
2386 end
2387
2388 interface PropertyLayoutElement end
2389
2390 redef class MProperty
2391 super PropertyLayoutElement
2392 end
2393
2394 redef class MPropDef
2395 super PropertyLayoutElement
2396 end
2397
2398 redef class AMethPropdef
2399 # The semi-global compilation does not support inlining calls to extern news
2400 redef fun can_inline
2401 do
2402 var m = mpropdef
2403 if m != null and m.mproperty.is_init and m.is_extern then return false
2404 return super
2405 end
2406 end
2407
2408 redef class AAttrPropdef
2409 redef fun init_expr(v, recv)
2410 do
2411 super
2412 if is_lazy and v.compiler.modelbuilder.toolcontext.opt_no_union_attribute.value then
2413 var guard = self.mlazypropdef.mproperty
2414 v.write_attribute(guard, recv, v.bool_instance(false))
2415 end
2416 end
2417 end