layout_builders: Added perfect hashing for mproperties
[nit.git] / src / 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 layout_builders
20 import rapid_type_analysis
21
22 # Add separate compiler specific options
23 redef class ToolContext
24 # --separate
25 var opt_separate: OptionBool = new OptionBool("Use separate compilation", "--separate")
26 # --no-inline-intern
27 var opt_no_inline_intern: OptionBool = new OptionBool("Do not inline call to intern methods", "--no-inline-intern")
28 # --no-union-attribute
29 var opt_no_union_attribute: OptionBool = 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: OptionBool = new OptionBool("Always call == in a polymorphic way", "--no-shortcut-equal")
32 # --inline-coloring-numbers
33 var opt_inline_coloring_numbers: OptionBool = new OptionBool("Inline colors and ids", "--inline-coloring-numbers")
34 # --use-naive-coloring
35 var opt_bm_typing: OptionBool = new OptionBool("Colorize items incrementaly, used to simulate binary matrix typing", "--bm-typing")
36 # --use-mod-perfect-hashing
37 var opt_phmod_typing: OptionBool = new OptionBool("Replace coloration by perfect hashing (with mod operator)", "--phmod-typing")
38 # --use-and-perfect-hashing
39 var opt_phand_typing: OptionBool = new OptionBool("Replace coloration by perfect hashing (with and operator)", "--phand-typing")
40 # --tables-metrics
41 var opt_tables_metrics: OptionBool = new OptionBool("Enable static size measuring of tables used for vft, typing and resolution", "--tables-metrics")
42
43 redef init
44 do
45 super
46 self.option_context.add_option(self.opt_separate)
47 self.option_context.add_option(self.opt_no_inline_intern)
48 self.option_context.add_option(self.opt_no_union_attribute)
49 self.option_context.add_option(self.opt_no_shortcut_equate)
50 self.option_context.add_option(self.opt_inline_coloring_numbers)
51 self.option_context.add_option(self.opt_bm_typing)
52 self.option_context.add_option(self.opt_phmod_typing)
53 self.option_context.add_option(self.opt_phand_typing)
54 self.option_context.add_option(self.opt_tables_metrics)
55 end
56 end
57
58 redef class ModelBuilder
59 fun run_separate_compiler(mainmodule: MModule, runtime_type_analysis: RapidTypeAnalysis)
60 do
61 var time0 = get_time
62 self.toolcontext.info("*** COMPILING TO C ***", 1)
63
64 var compiler = new SeparateCompiler(mainmodule, self, runtime_type_analysis)
65 compiler.compile_header
66
67 # compile class structures
68 for m in mainmodule.in_importation.greaters do
69 for mclass in m.intro_mclasses do
70 compiler.compile_class_to_c(mclass)
71 end
72 end
73
74 # The main function of the C
75 compiler.new_file
76 compiler.compile_main_function
77
78 # compile methods
79 for m in mainmodule.in_importation.greaters do
80 compiler.new_file
81 compiler.compile_module_to_c(m)
82 end
83
84 # compile live & cast type structures
85 compiler.new_file
86 var mtypes = compiler.do_type_coloring
87 for t in mtypes do
88 compiler.compile_type_to_c(t)
89 end
90
91 compiler.display_stats
92
93 write_and_make(compiler)
94 end
95 end
96
97 # Singleton that store the knowledge about the separate compilation process
98 class SeparateCompiler
99 super AbstractCompiler
100
101 # The result of the RTA (used to know live types and methods)
102 var runtime_type_analysis: RapidTypeAnalysis
103
104 private var undead_types: Set[MType] = new HashSet[MType]
105 private var partial_types: Set[MType] = new HashSet[MType]
106 private var live_unresolved_types: Map[MClassDef, Set[MType]] = new HashMap[MClassDef, HashSet[MType]]
107
108 private var type_layout: nullable Layout[MType]
109 private var resolution_layout: nullable Layout[MType]
110 protected var method_layout: nullable Layout[MMethod]
111 protected var attr_layout: nullable Layout[MAttribute]
112
113 init(mainmodule: MModule, mmbuilder: ModelBuilder, runtime_type_analysis: RapidTypeAnalysis) do
114 super(mainmodule, mmbuilder)
115 self.header = new_visitor
116 self.runtime_type_analysis = runtime_type_analysis
117 self.do_property_coloring
118 self.compile_box_kinds
119 end
120
121 redef fun compile_header_structs do
122 self.header.add_decl("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
123 self.compile_header_attribute_structs
124 self.header.add_decl("struct class \{ int box_kind; nitmethod_t vft[1]; \}; /* general C type representing a Nit class. */")
125
126 # With resolution_table_table, all live type resolution are stored in a big table: resolution_table
127 self.header.add_decl("struct type \{ int id; const char *name; int color; short int is_nullable; struct types *resolution_table; int table_size; int type_table[1]; \}; /* general C type representing a Nit type. */")
128
129 if modelbuilder.toolcontext.opt_phmod_typing.value or modelbuilder.toolcontext.opt_phand_typing.value then
130 self.header.add_decl("struct types \{ int mask; struct type *types[1]; \}; /* a list types (used for vts, fts and unresolved lists). */")
131 else
132 self.header.add_decl("struct types \{ struct type *types[1]; \}; /* a list types (used for vts, fts and unresolved lists). */")
133 end
134
135 if modelbuilder.toolcontext.opt_phmod_typing.value then
136 self.header.add_decl("#define HASH(mask, id) ((mask)%(id))")
137 else if modelbuilder.toolcontext.opt_phand_typing.value then
138 self.header.add_decl("#define HASH(mask, id) ((mask)&(id))")
139 end
140
141 self.header.add_decl("typedef struct \{ struct type *type; struct class *class; nitattribute_t attrs[1]; \} val; /* general C type representing a Nit instance. */")
142 end
143
144 fun compile_header_attribute_structs
145 do
146 if modelbuilder.toolcontext.opt_no_union_attribute.value then
147 self.header.add_decl("typedef void* nitattribute_t; /* general C type representing a Nit attribute. */")
148 else
149 self.header.add_decl("typedef union \{")
150 self.header.add_decl("void* val;")
151 for c, v in self.box_kinds do
152 var t = c.mclass_type
153 self.header.add_decl("{t.ctype} {t.ctypename};")
154 end
155 self.header.add_decl("\} nitattribute_t; /* general C type representing a Nit attribute. */")
156 end
157 end
158
159 fun compile_box_kinds
160 do
161 # Collect all bas box class
162 # FIXME: this is not completely fine with a separate compilation scheme
163 for classname in ["Int", "Bool", "Char", "Float", "NativeString", "Pointer"] do
164 var classes = self.mainmodule.model.get_mclasses_by_name(classname)
165 if classes == null then continue
166 assert classes.length == 1 else print classes.join(", ")
167 self.box_kinds[classes.first] = self.box_kinds.length + 1
168 end
169 end
170
171 var box_kinds = new HashMap[MClass, Int]
172
173 fun box_kind_of(mclass: MClass): Int
174 do
175 if mclass.mclass_type.ctype == "val*" then
176 return 0
177 else if mclass.kind == extern_kind then
178 return self.box_kinds[self.mainmodule.get_primitive_class("Pointer")]
179 else
180 return self.box_kinds[mclass]
181 end
182
183 end
184
185 fun compile_color_consts(colors: Map[Object, Int]) do
186 for m, c in colors do
187 if color_consts_done.has(m) then continue
188 if m isa MProperty then
189 if modelbuilder.toolcontext.opt_inline_coloring_numbers.value then
190 self.header.add_decl("#define {m.const_color} {c}")
191 else
192 self.header.add_decl("extern const int {m.const_color};")
193 self.header.add("const int {m.const_color} = {c};")
194 end
195 else if m isa MType then
196 if modelbuilder.toolcontext.opt_inline_coloring_numbers.value then
197 self.header.add_decl("#define {m.const_color} {c}")
198 else
199 self.header.add_decl("extern const int {m.const_color};")
200 self.header.add("const int {m.const_color} = {c};")
201 end
202 end
203 color_consts_done.add(m)
204 end
205 end
206
207 private var color_consts_done = new HashSet[Object]
208
209 # colorize classe properties
210 fun do_property_coloring do
211 var mclasses = new HashSet[MClass].from(modelbuilder.model.mclasses)
212
213 # Layouts
214 var method_layout_builder: PropertyLayoutBuilder[MMethod]
215 var attribute_layout_builder: PropertyLayoutBuilder[MAttribute]
216 if modelbuilder.toolcontext.opt_bm_typing.value then
217 method_layout_builder = new MMethodBMizer(self.mainmodule)
218 attribute_layout_builder = new MAttributeBMizer(self.mainmodule)
219 else if modelbuilder.toolcontext.opt_phmod_typing.value then
220 method_layout_builder = new MMethodHasher(new PHModOperator, self.mainmodule)
221 attribute_layout_builder = new MAttributeHasher(new PHModOperator, self.mainmodule)
222 else if modelbuilder.toolcontext.opt_phand_typing.value then
223 method_layout_builder = new MMethodHasher(new PHAndOperator, self.mainmodule)
224 attribute_layout_builder = new MAttributeHasher(new PHAndOperator, self.mainmodule)
225 else
226 method_layout_builder = new MMethodColorer(self.mainmodule)
227 attribute_layout_builder = new MAttributeColorer(self.mainmodule)
228 end
229
230 # methods coloration
231 var method_layout = method_layout_builder.build_layout(mclasses)
232 self.method_tables = build_method_tables(mclasses, method_layout)
233 self.compile_color_consts(method_layout.pos)
234 self.method_layout = method_layout
235
236 # attributes coloration
237 var attr_layout = attribute_layout_builder.build_layout(mclasses)
238 self.attr_tables = build_attr_tables(mclasses, attr_layout)
239 self.compile_color_consts(attr_layout.pos)
240 self.attr_layout = attr_layout
241 end
242
243 fun build_method_tables(mclasses: Set[MClass], layout: Layout[MProperty]): Map[MClass, Array[nullable MPropDef]] do
244 var tables = new HashMap[MClass, Array[nullable MPropDef]]
245 for mclass in mclasses do
246 var table = new Array[nullable MPropDef]
247 # first, fill table from parents by reverse linearization order
248 var parents = self.mainmodule.super_mclasses(mclass)
249 var lin = self.mainmodule.reverse_linearize_mclasses(parents)
250 for parent in lin do
251 for mproperty in self.mainmodule.properties(parent) do
252 if not mproperty isa MMethod then continue
253 var color = layout.pos[mproperty]
254 if table.length <= color then
255 for i in [table.length .. color[ do
256 table[i] = null
257 end
258 end
259 for mpropdef in mproperty.mpropdefs do
260 if mpropdef.mclassdef.mclass == parent then
261 table[color] = mpropdef
262 end
263 end
264 end
265 end
266
267 # then override with local properties
268 for mproperty in self.mainmodule.properties(mclass) do
269 if not mproperty isa MMethod then continue
270 var color = layout.pos[mproperty]
271 if table.length <= color then
272 for i in [table.length .. color[ do
273 table[i] = null
274 end
275 end
276 for mpropdef in mproperty.mpropdefs do
277 if mpropdef.mclassdef.mclass == mclass then
278 table[color] = mpropdef
279 end
280 end
281 end
282 tables[mclass] = table
283 end
284 return tables
285 end
286
287 fun build_attr_tables(mclasses: Set[MClass], layout: Layout[MProperty]): Map[MClass, Array[nullable MPropDef]] do
288 var tables = new HashMap[MClass, Array[nullable MPropDef]]
289 for mclass in mclasses do
290 var table = new Array[nullable MPropDef]
291 # first, fill table from parents by reverse linearization order
292 var parents = self.mainmodule.super_mclasses(mclass)
293 var lin = self.mainmodule.reverse_linearize_mclasses(parents)
294 for parent in lin do
295 for mproperty in self.mainmodule.properties(parent) do
296 if not mproperty isa MAttribute then continue
297 var color = layout.pos[mproperty]
298 if table.length <= color then
299 for i in [table.length .. color[ do
300 table[i] = null
301 end
302 end
303 for mpropdef in mproperty.mpropdefs do
304 if mpropdef.mclassdef.mclass == parent then
305 table[color] = mpropdef
306 end
307 end
308 end
309 end
310
311 # then override with local properties
312 for mproperty in self.mainmodule.properties(mclass) do
313 if not mproperty isa MAttribute then continue
314 var color = layout.pos[mproperty]
315 if table.length <= color then
316 for i in [table.length .. color[ do
317 table[i] = null
318 end
319 end
320 for mpropdef in mproperty.mpropdefs do
321 if mpropdef.mclassdef.mclass == mclass then
322 table[color] = mpropdef
323 end
324 end
325 end
326 tables[mclass] = table
327 end
328 return tables
329 end
330
331 # colorize live types of the program
332 private fun do_type_coloring: Set[MType] do
333 var mtypes = new HashSet[MType]
334 mtypes.add_all(self.runtime_type_analysis.live_types)
335 mtypes.add_all(self.runtime_type_analysis.live_cast_types)
336 mtypes.add_all(self.undead_types)
337 for c in self.box_kinds.keys do
338 mtypes.add(c.mclass_type)
339 end
340
341 for mtype in mtypes do
342 retieve_live_partial_types(mtype)
343 end
344 mtypes.add_all(self.partial_types)
345
346 # Typing Layout
347 var layout_builder: TypingLayoutBuilder[MType]
348 if modelbuilder.toolcontext.opt_bm_typing.value then
349 layout_builder = new MTypeBMizer(self.mainmodule)
350 else if modelbuilder.toolcontext.opt_phmod_typing.value then
351 layout_builder = new MTypeHasher(new PHModOperator, self.mainmodule)
352 else if modelbuilder.toolcontext.opt_phand_typing.value then
353 layout_builder = new MTypeHasher(new PHAndOperator, self.mainmodule)
354 else
355 layout_builder = new MTypeColorer(self.mainmodule)
356 end
357
358 # colorize types
359 self.type_layout = layout_builder.build_layout(mtypes)
360 self.type_tables = self.build_type_tables(mtypes)
361
362 # VT and FT are stored with other unresolved types in the big resolution_tables
363 self.compile_resolution_tables(mtypes)
364
365 return mtypes
366 end
367
368 # Build type tables
369 fun build_type_tables(mtypes: Set[MType]): Map[MType, Array[nullable MType]] do
370 var tables = new HashMap[MType, Array[nullable MType]]
371 var layout = self.type_layout
372 for mtype in mtypes do
373 var table = new Array[nullable MType]
374 var supers = new HashSet[MType]
375 supers.add_all(self.mainmodule.super_mtypes(mtype, mtypes))
376 supers.add(mtype)
377 for sup in supers do
378 var color: Int
379 if layout isa PHLayout[MType, MType] then
380 color = layout.hashes[mtype][sup]
381 else
382 color = layout.pos[sup]
383 end
384 if table.length <= color then
385 for i in [table.length .. color[ do
386 table[i] = null
387 end
388 end
389 table[color] = sup
390 end
391 tables[mtype] = table
392 end
393 return tables
394 end
395
396 protected fun compile_resolution_tables(mtypes: Set[MType]) do
397 # resolution_tables is used to perform a type resolution at runtime in O(1)
398
399 # During the visit of the body of classes, live_unresolved_types are collected
400 # and associated to
401 # Collect all live_unresolved_types (visited in the body of classes)
402
403 # Determinate fo each livetype what are its possible requested anchored types
404 var mtype2unresolved = new HashMap[MClassType, Set[MType]]
405 for mtype in self.runtime_type_analysis.live_types do
406 var set = new HashSet[MType]
407 for cd in mtype.collect_mclassdefs(self.mainmodule) do
408 if self.live_unresolved_types.has_key(cd) then
409 set.add_all(self.live_unresolved_types[cd])
410 end
411 end
412 mtype2unresolved[mtype] = set
413 end
414
415 # Compute the table layout with the prefered method
416 var resolution_builder: ResolutionLayoutBuilder
417 if modelbuilder.toolcontext.opt_bm_typing.value then
418 resolution_builder = new ResolutionBMizer
419 else if modelbuilder.toolcontext.opt_phmod_typing.value then
420 resolution_builder = new ResolutionHasher(new PHModOperator)
421 else if modelbuilder.toolcontext.opt_phand_typing.value then
422 resolution_builder = new ResolutionHasher(new PHAndOperator)
423 else
424 resolution_builder = new ResolutionColorer
425 end
426 self.resolution_layout = resolution_builder.build_layout(mtype2unresolved)
427 self.resolution_tables = self.build_resolution_tables(mtype2unresolved)
428
429 # Compile a C constant for each collected unresolved type.
430 # Either to a color, or to -1 if the unresolved type is dead (no live receiver can require it)
431 var all_unresolved = new HashSet[MType]
432 for t in self.live_unresolved_types.values do
433 all_unresolved.add_all(t)
434 end
435 var all_unresolved_types_colors = new HashMap[MType, Int]
436 for t in all_unresolved do
437 if self.resolution_layout.pos.has_key(t) then
438 all_unresolved_types_colors[t] = self.resolution_layout.pos[t]
439 else
440 all_unresolved_types_colors[t] = -1
441 end
442 end
443 self.compile_color_consts(all_unresolved_types_colors)
444
445 #print "tables"
446 #for k, v in unresolved_types_tables.as(not null) do
447 # print "{k}: {v.join(", ")}"
448 #end
449 #print ""
450 end
451
452 fun build_resolution_tables(elements: Map[MClassType, Set[MType]]): Map[MClassType, Array[nullable MType]] do
453 var tables = new HashMap[MClassType, Array[nullable MType]]
454 var layout = self.resolution_layout
455 for mclasstype, mtypes in elements do
456 var table = new Array[nullable MType]
457 for mtype in mtypes do
458 var color: Int
459 if layout isa PHLayout[MClassType, MType] then
460 color = layout.hashes[mclasstype][mtype]
461 else
462 color = layout.pos[mtype]
463 end
464 if table.length <= color then
465 for i in [table.length .. color[ do
466 table[i] = null
467 end
468 end
469 table[color] = mtype
470 end
471 tables[mclasstype] = table
472 end
473 return tables
474 end
475
476 fun retieve_live_partial_types(mtype: MType) do
477 # add formal types arguments to mtypes
478 if mtype isa MGenericType then
479 for ft in mtype.arguments do
480 if ft.need_anchor then
481 print("Why do we need anchor here ?")
482 abort
483 end
484 self.partial_types.add(ft)
485 retieve_live_partial_types(ft)
486 end
487 end
488 var mclass_type: MClassType
489 if mtype isa MNullableType then
490 mclass_type = mtype.mtype.as(MClassType)
491 else
492 mclass_type = mtype.as(MClassType)
493 end
494
495 # add virtual types to mtypes
496 for vt in self.mainmodule.properties(mclass_type.mclass) do
497 if vt isa MVirtualTypeProp then
498 var anchored = vt.mvirtualtype.lookup_bound(self.mainmodule, mclass_type).anchor_to(self.mainmodule, mclass_type)
499 self.partial_types.add(anchored)
500 end
501 end
502 end
503
504 # Separately compile all the method definitions of the module
505 fun compile_module_to_c(mmodule: MModule)
506 do
507 var old_module = self.mainmodule
508 self.mainmodule = mmodule
509 for cd in mmodule.mclassdefs do
510 for pd in cd.mpropdefs do
511 if not pd isa MMethodDef then continue
512 #print "compile {pd} @ {cd} @ {mmodule}"
513 var r = new SeparateRuntimeFunction(pd)
514 r.compile_to_c(self)
515 if true or cd.bound_mtype.ctype != "val*" then
516 var r2 = new VirtualRuntimeFunction(pd)
517 r2.compile_to_c(self)
518 end
519 end
520 end
521 self.mainmodule = old_module
522 end
523
524 # Globaly compile the type structure of a live type
525 fun compile_type_to_c(mtype: MType)
526 do
527 var c_name = mtype.c_name
528 var v = new SeparateCompilerVisitor(self)
529 v.add_decl("/* runtime type {mtype} */")
530
531 # extern const struct type_X
532 self.header.add_decl("extern const struct type_{c_name} type_{c_name};")
533 self.header.add_decl("struct type_{c_name} \{")
534 self.header.add_decl("int id;")
535 self.header.add_decl("const char *name;")
536 self.header.add_decl("int color;")
537 self.header.add_decl("short int is_nullable;")
538 self.header.add_decl("const struct types *resolution_table;")
539 self.header.add_decl("int table_size;")
540 self.header.add_decl("int type_table[{self.type_tables[mtype].length}];")
541 self.header.add_decl("\};")
542
543 # const struct type_X
544 v.add_decl("const struct type_{c_name} type_{c_name} = \{")
545 v.add_decl("{self.type_layout.ids[mtype]},")
546 v.add_decl("\"{mtype}\", /* class_name_string */")
547 var layout = self.type_layout
548 if layout isa PHLayout[MType, MType] then
549 v.add_decl("{layout.masks[mtype]},")
550 else
551 v.add_decl("{layout.pos[mtype]},")
552 end
553 if mtype isa MNullableType then
554 v.add_decl("1,")
555 else
556 v.add_decl("0,")
557 end
558 if compile_type_resolution_table(mtype) then
559 v.add_decl("(struct types*) &resolution_table_{c_name},")
560 else
561 v.add_decl("NULL,")
562 end
563 v.add_decl("{self.type_tables[mtype].length},")
564 v.add_decl("\{")
565 for stype in self.type_tables[mtype] do
566 if stype == null then
567 v.add_decl("-1, /* empty */")
568 else
569 v.add_decl("{self.type_layout.ids[stype]}, /* {stype} */")
570 end
571 end
572 v.add_decl("\},")
573 v.add_decl("\};")
574 end
575
576 fun compile_type_resolution_table(mtype: MType): Bool do
577
578 var mclass_type: MClassType
579 if mtype isa MNullableType then
580 mclass_type = mtype.mtype.as(MClassType)
581 else
582 mclass_type = mtype.as(MClassType)
583 end
584 if not self.resolution_tables.has_key(mclass_type) then return false
585
586 var layout = self.resolution_layout
587
588 # extern const struct resolution_table_X resolution_table_X
589 self.header.add_decl("extern const struct resolution_table_{mtype.c_name} resolution_table_{mtype.c_name};")
590 self.header.add_decl("struct resolution_table_{mtype.c_name} \{")
591 if layout isa PHLayout[MClassType, MType] then
592 self.header.add_decl("int mask;")
593 end
594 self.header.add_decl("struct type *types[{self.resolution_tables[mclass_type].length}];")
595 self.header.add_decl("\};")
596
597 # const struct fts_table_X fts_table_X
598 var v = new_visitor
599 v.add_decl("const struct resolution_table_{mtype.c_name} resolution_table_{mtype.c_name} = \{")
600 if layout isa PHLayout[MClassType, MType] then
601 v.add_decl("{layout.masks[mclass_type]},")
602 end
603 v.add_decl("\{")
604 for t in self.resolution_tables[mclass_type] do
605 if t == null then
606 v.add_decl("NULL, /* empty */")
607 else
608 # The table stores the result of the type resolution
609 # Therefore, for a receiver `mclass_type`, and a unresolved type `t`
610 # the value stored is tv.
611 var tv = t.resolve_for(mclass_type, mclass_type, self.mainmodule, true)
612 # FIXME: What typeids means here? How can a tv not be live?
613 if self.type_layout.ids.has_key(tv) then
614 v.add_decl("(struct type*)&type_{tv.c_name}, /* {t}: {tv} */")
615 else
616 v.add_decl("NULL, /* empty ({t}: {tv} not a live type) */")
617 end
618 end
619 end
620 v.add_decl("\},")
621 v.add_decl("\};")
622 return true
623 end
624
625 # Globally compile the table of the class mclass
626 # In a link-time optimisation compiler, tables are globally computed
627 # In a true separate compiler (a with dynamic loading) you cannot do this unfortnally
628 fun compile_class_to_c(mclass: MClass)
629 do
630 var mtype = mclass.intro.bound_mtype
631 var c_name = mclass.c_name
632
633 var vft = self.method_tables[mclass]
634 var attrs = self.attr_tables[mclass]
635 var v = new_visitor
636
637 v.add_decl("/* runtime class {c_name} */")
638
639 self.header.add_decl("struct class_{c_name} \{")
640 self.header.add_decl("int box_kind;")
641 self.header.add_decl("nitmethod_t vft[{vft.length}];")
642 self.header.add_decl("\};")
643
644 # Build class vft
645 self.header.add_decl("extern const struct class_{c_name} class_{c_name};")
646 v.add_decl("const struct class_{c_name} class_{c_name} = \{")
647 v.add_decl("{self.box_kind_of(mclass)}, /* box_kind */")
648 v.add_decl("\{")
649 for i in [0 .. vft.length[ do
650 var mpropdef = vft[i]
651 if mpropdef == null then
652 v.add_decl("NULL, /* empty */")
653 else
654 if true or mpropdef.mclassdef.bound_mtype.ctype != "val*" then
655 v.add_decl("(nitmethod_t)VIRTUAL_{mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
656 else
657 v.add_decl("(nitmethod_t){mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
658 end
659 end
660 end
661 v.add_decl("\}")
662 v.add_decl("\};")
663
664 if mtype.ctype != "val*" then
665 #Build instance struct
666 self.header.add_decl("struct instance_{c_name} \{")
667 self.header.add_decl("const struct type *type;")
668 self.header.add_decl("const struct class *class;")
669 self.header.add_decl("{mtype.ctype} value;")
670 self.header.add_decl("\};")
671
672 if not self.runtime_type_analysis.live_types.has(mtype) then return
673
674 self.header.add_decl("val* BOX_{c_name}({mtype.ctype});")
675 v.add_decl("/* allocate {mtype} */")
676 v.add_decl("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
677 v.add("struct instance_{c_name}*res = GC_MALLOC(sizeof(struct instance_{c_name}));")
678 v.add("res->type = (struct type*) &type_{c_name};")
679 v.add("res->class = (struct class*) &class_{c_name};")
680 v.add("res->value = value;")
681 v.add("return (val*)res;")
682 v.add("\}")
683 return
684 end
685
686 var is_native_array = mclass.name == "NativeArray"
687
688 var sig
689 if is_native_array then
690 sig = "int length, struct type* type"
691 else
692 sig = "struct type* type"
693 end
694
695 #Build instance struct
696 #extern const struct instance_array__NativeArray instance_array__NativeArray;
697 self.header.add_decl("struct instance_{c_name} \{")
698 self.header.add_decl("const struct type *type;")
699 self.header.add_decl("const struct class *class;")
700 self.header.add_decl("nitattribute_t attrs[{attrs.length}];")
701 if is_native_array then
702 # NativeArrays are just a instance header followed by an array of values
703 self.header.add_decl("val* values[0];")
704 end
705 self.header.add_decl("\};")
706
707
708 self.header.add_decl("{mtype.ctype} NEW_{c_name}({sig});")
709 v.add_decl("/* allocate {mtype} */")
710 v.add_decl("{mtype.ctype} NEW_{c_name}({sig}) \{")
711 var res = v.new_named_var(mtype, "self")
712 res.is_exact = true
713 if is_native_array then
714 var mtype_elt = mtype.arguments.first
715 v.add("{res} = GC_MALLOC(sizeof(struct instance_{c_name}) + length*sizeof({mtype_elt.ctype}));")
716 else
717 v.add("{res} = GC_MALLOC(sizeof(struct instance_{c_name}));")
718 end
719 v.add("{res}->type = type;")
720 if v.compiler.modelbuilder.toolcontext.opt_hardening.value then
721 v.add("if(type == NULL) \{")
722 v.add_abort("type null")
723 v.add("\}")
724 v.add("if(type->resolution_table == NULL) \{")
725 v.add("fprintf(stderr, \"Insantiation of a dead type: %s\\n\", type->name);")
726 v.add_abort("type dead")
727 v.add("\}")
728 end
729 v.add("{res}->class = (struct class*) &class_{c_name};")
730
731 self.generate_init_attr(v, res, mtype)
732 v.add("return {res};")
733 v.add("\}")
734
735 generate_check_init_instance(mtype)
736 end
737
738 redef fun generate_check_init_instance(mtype)
739 do
740 if self.modelbuilder.toolcontext.opt_no_check_initialization.value then return
741
742 var v = self.new_visitor
743 var c_name = mtype.mclass.c_name
744 var res = new RuntimeVariable("self", mtype, mtype)
745 self.header.add_decl("void CHECK_NEW_{c_name}({mtype.ctype});")
746 v.add_decl("/* allocate {mtype} */")
747 v.add_decl("void CHECK_NEW_{c_name}({mtype.ctype} {res}) \{")
748 self.generate_check_attr(v, res, mtype)
749 v.add("\}")
750 end
751
752 redef fun new_visitor do return new SeparateCompilerVisitor(self)
753
754 # Stats
755
756 private var type_tables: Map[MType, Array[nullable MType]] = new HashMap[MType, Array[nullable MType]]
757 private var resolution_tables: Map[MClassType, Array[nullable MType]] = new HashMap[MClassType, Array[nullable MType]]
758 protected var method_tables: Map[MClass, Array[nullable MPropDef]] = new HashMap[MClass, Array[nullable MPropDef]]
759 protected var attr_tables: Map[MClass, Array[nullable MPropDef]] = new HashMap[MClass, Array[nullable MPropDef]]
760
761 redef fun display_stats
762 do
763 super
764 if self.modelbuilder.toolcontext.opt_tables_metrics.value then
765 display_sizes
766 end
767 end
768
769 fun display_sizes
770 do
771 print "# size of subtyping tables"
772 print "\ttotal \tholes"
773 var total = 0
774 var holes = 0
775 for t, table in type_tables do
776 total += table.length
777 for e in table do if e == null then holes += 1
778 end
779 print "\t{total}\t{holes}"
780
781 print "# size of resolution tables"
782 print "\ttotal \tholes"
783 total = 0
784 holes = 0
785 for t, table in resolution_tables do
786 total += table.length
787 for e in table do if e == null then holes += 1
788 end
789 print "\t{total}\t{holes}"
790
791 print "# size of methods tables"
792 print "\ttotal \tholes"
793 total = 0
794 holes = 0
795 for t, table in method_tables do
796 total += table.length
797 for e in table do if e == null then holes += 1
798 end
799 print "\t{total}\t{holes}"
800
801 print "# size of attributes tables"
802 print "\ttotal \tholes"
803 total = 0
804 holes = 0
805 for t, table in attr_tables do
806 total += table.length
807 for e in table do if e == null then holes += 1
808 end
809 print "\t{total}\t{holes}"
810 end
811 end
812
813 # A visitor on the AST of property definition that generate the C code of a separate compilation process.
814 class SeparateCompilerVisitor
815 super AbstractCompilerVisitor
816
817 redef type COMPILER: SeparateCompiler
818
819 redef fun adapt_signature(m, args)
820 do
821 var msignature = m.msignature.resolve_for(m.mclassdef.bound_mtype, m.mclassdef.bound_mtype, m.mclassdef.mmodule, true)
822 var recv = args.first
823 if recv.mtype.ctype != m.mclassdef.mclass.mclass_type.ctype then
824 args.first = self.autobox(args.first, m.mclassdef.mclass.mclass_type)
825 end
826 for i in [0..msignature.arity[ do
827 var t = msignature.mparameters[i].mtype
828 if i == msignature.vararg_rank then
829 t = args[i+1].mtype
830 end
831 args[i+1] = self.autobox(args[i+1], t)
832 end
833 end
834
835 redef fun autobox(value, mtype)
836 do
837 if value.mtype == mtype then
838 return value
839 else if value.mtype.ctype == "val*" and mtype.ctype == "val*" then
840 return value
841 else if value.mtype.ctype == "val*" then
842 return self.new_expr("((struct instance_{mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype)
843 else if mtype.ctype == "val*" then
844 var valtype = value.mtype.as(MClassType)
845 var res = self.new_var(mtype)
846 if not compiler.runtime_type_analysis.live_types.has(valtype) then
847 self.add("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
848 self.add("printf(\"Dead code executed!\\n\"); exit(1);")
849 return res
850 end
851 self.add("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
852 return res
853 else
854 # Bad things will appen!
855 var res = self.new_var(mtype)
856 self.add("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
857 self.add("printf(\"Cast error: Cannot cast %s to %s.\\n\", \"{value.mtype}\", \"{mtype}\"); exit(1);")
858 return res
859 end
860 end
861
862 # Return a C expression returning the runtime type structure of the value
863 # The point of the method is to works also with primitives types.
864 fun type_info(value: RuntimeVariable): String
865 do
866 if value.mtype.ctype == "val*" then
867 return "{value}->type"
868 else
869 return "(&type_{value.mtype.c_name})"
870 end
871 end
872
873 redef fun send(mmethod, arguments)
874 do
875 if arguments.first.mcasttype.ctype != "val*" then
876 return self.monomorphic_send(mmethod, arguments.first.mcasttype, arguments)
877 end
878
879 var res: nullable RuntimeVariable
880 var msignature = mmethod.intro.msignature.resolve_for(mmethod.intro.mclassdef.bound_mtype, mmethod.intro.mclassdef.bound_mtype, mmethod.intro.mclassdef.mmodule, true)
881 var ret = msignature.return_mtype
882 if mmethod.is_new then
883 ret = arguments.first.mtype
884 res = self.new_var(ret)
885 else if ret == null then
886 res = null
887 else
888 res = self.new_var(ret)
889 end
890
891 var s = new Buffer
892 var ss = new Buffer
893
894 var recv = arguments.first
895 s.append("val*")
896 ss.append("{recv}")
897 self.varargize(mmethod.intro, mmethod.intro.msignature.as(not null), arguments)
898 for i in [0..msignature.arity[ do
899 var a = arguments[i+1]
900 var t = msignature.mparameters[i].mtype
901 if i == msignature.vararg_rank then
902 t = arguments[i+1].mcasttype
903 end
904 s.append(", {t.ctype}")
905 a = self.autobox(a, t)
906 ss.append(", {a}")
907 end
908
909 var consider_null = not self.compiler.modelbuilder.toolcontext.opt_no_check_other.value or mmethod.name == "==" or mmethod.name == "!="
910 var maybenull = recv.mcasttype isa MNullableType and consider_null
911 if maybenull then
912 self.add("if ({recv} == NULL) \{")
913 if mmethod.name == "==" then
914 assert res != null
915 var arg = arguments[1]
916 if arg.mcasttype isa MNullableType then
917 self.add("{res} = ({arg} == NULL);")
918 else if arg.mcasttype isa MNullType then
919 self.add("{res} = 1; /* is null */")
920 else
921 self.add("{res} = 0; /* {arg.inspect} cannot be null */")
922 end
923 else if mmethod.name == "!=" then
924 assert res != null
925 var arg = arguments[1]
926 if arg.mcasttype isa MNullableType then
927 self.add("{res} = ({arg} != NULL);")
928 else if arg.mcasttype isa MNullType then
929 self.add("{res} = 0; /* is null */")
930 else
931 self.add("{res} = 1; /* {arg.inspect} cannot be null */")
932 end
933 else
934 self.add_abort("Reciever is null")
935 end
936 self.add("\} else \{")
937 end
938 if not self.compiler.modelbuilder.toolcontext.opt_no_shortcut_equate.value and (mmethod.name == "==" or mmethod.name == "!=") then
939 assert res != null
940 # Recv is not null, thus is arg is, it is easy to conclude (and respect the invariants)
941 var arg = arguments[1]
942 if arg.mcasttype isa MNullType then
943 if mmethod.name == "==" then
944 self.add("{res} = 0; /* arg is null but recv is not */")
945 else
946 self.add("{res} = 1; /* arg is null and recv is not */")
947 end
948 if maybenull then
949 self.add("\}")
950 end
951 return res
952 end
953 end
954
955 var r
956 if ret == null then r = "void" else r = ret.ctype
957 var call = "(({r} (*)({s}))({arguments.first}->class->vft[{mmethod.const_color}]))({ss}) /* {mmethod} on {arguments.first.inspect}*/"
958
959 if res != null then
960 self.add("{res} = {call};")
961 else
962 self.add("{call};")
963 end
964
965 if maybenull then
966 self.add("\}")
967 end
968
969 return res
970 end
971
972 redef fun call(mmethoddef, recvtype, arguments)
973 do
974 var res: nullable RuntimeVariable
975 var ret = mmethoddef.msignature.return_mtype
976 if mmethoddef.mproperty.is_new then
977 ret = arguments.first.mtype
978 res = self.new_var(ret)
979 else if ret == null then
980 res = null
981 else
982 ret = ret.resolve_for(mmethoddef.mclassdef.bound_mtype, mmethoddef.mclassdef.bound_mtype, mmethoddef.mclassdef.mmodule, true)
983 res = self.new_var(ret)
984 end
985
986 if self.compiler.modelbuilder.mpropdef2npropdef.has_key(mmethoddef) and
987 self.compiler.modelbuilder.mpropdef2npropdef[mmethoddef] isa AInternMethPropdef and
988 not compiler.modelbuilder.toolcontext.opt_no_inline_intern.value then
989 var frame = new Frame(self, mmethoddef, recvtype, arguments)
990 frame.returnlabel = self.get_name("RET_LABEL")
991 frame.returnvar = res
992 var old_frame = self.frame
993 self.frame = frame
994 self.add("\{ /* Inline {mmethoddef} ({arguments.join(",")}) */")
995 mmethoddef.compile_inside_to_c(self, arguments)
996 self.add("{frame.returnlabel.as(not null)}:(void)0;")
997 self.add("\}")
998 self.frame = old_frame
999 return res
1000 end
1001
1002 # Autobox arguments
1003 self.adapt_signature(mmethoddef, arguments)
1004
1005 if res == null then
1006 self.add("{mmethoddef.c_name}({arguments.join(", ")});")
1007 return null
1008 else
1009 self.add("{res} = {mmethoddef.c_name}({arguments.join(", ")});")
1010 end
1011
1012 return res
1013 end
1014
1015 redef fun supercall(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): nullable RuntimeVariable
1016 do
1017 # FIXME implements a polymorphic access in tables
1018 m = m.lookup_next_definition(m.mclassdef.mmodule, m.mclassdef.bound_mtype)
1019 return self.call(m, recvtype, args)
1020 end
1021
1022 redef fun vararg_instance(mpropdef, recv, varargs, elttype)
1023 do
1024 # A vararg must be stored into an new array
1025 # The trick is that the dymaic type of the array may depends on the receiver
1026 # of the method (ie recv) if the static type is unresolved
1027 # This is more complex than usual because the unresolved type must not be resolved
1028 # with the current receiver (ie self).
1029 # Therefore to isolate the resolution from self, a local Frame is created.
1030 # One can see this implementation as an inlined method of the receiver whose only
1031 # job is to allocate the array
1032 var old_frame = self.frame
1033 var frame = new Frame(self, mpropdef, mpropdef.mclassdef.bound_mtype, [recv])
1034 self.frame = frame
1035 #print "required Array[{elttype}] for recv {recv.inspect}. bound=Array[{self.resolve_for(elttype, recv)}]. selfvar={frame.arguments.first.inspect}"
1036 var res = self.array_instance(varargs, elttype)
1037 self.frame = old_frame
1038 return res
1039 end
1040
1041 redef fun isset_attribute(a, recv)
1042 do
1043 self.check_recv_notnull(recv)
1044 var res = self.new_var(bool_type)
1045
1046 # What is the declared type of the attribute?
1047 var mtype = a.intro.static_mtype.as(not null)
1048 var intromclassdef = a.intro.mclassdef
1049 mtype = mtype.resolve_for(intromclassdef.bound_mtype, intromclassdef.bound_mtype, intromclassdef.mmodule, true)
1050
1051 if mtype isa MNullableType then
1052 self.add("{res} = 1; /* easy isset: {a} on {recv.inspect} */")
1053 return res
1054 end
1055
1056 if self.compiler.modelbuilder.toolcontext.opt_no_union_attribute.value then
1057 self.add("{res} = {recv}->attrs[{a.const_color}] != NULL; /* {a} on {recv.inspect}*/")
1058 else
1059
1060 if mtype.ctype == "val*" then
1061 self.add("{res} = {recv}->attrs[{a.const_color}].val != NULL; /* {a} on {recv.inspect} */")
1062 else
1063 self.add("{res} = 1; /* NOT YET IMPLEMENTED: isset of primitives: {a} on {recv.inspect} */")
1064 end
1065 end
1066 return res
1067 end
1068
1069 redef fun read_attribute(a, recv)
1070 do
1071 self.check_recv_notnull(recv)
1072
1073 # What is the declared type of the attribute?
1074 var ret = a.intro.static_mtype.as(not null)
1075 var intromclassdef = a.intro.mclassdef
1076 ret = ret.resolve_for(intromclassdef.bound_mtype, intromclassdef.bound_mtype, intromclassdef.mmodule, true)
1077
1078 if self.compiler.modelbuilder.toolcontext.opt_no_union_attribute.value then
1079 # Get the attribute or a box (ie. always a val*)
1080 var cret = self.object_type.as_nullable
1081 var res = self.new_var(cret)
1082 res.mcasttype = ret
1083
1084 self.add("{res} = {recv}->attrs[{a.const_color}]; /* {a} on {recv.inspect} */")
1085
1086 # Check for Uninitialized attribute
1087 if not ret isa MNullableType and not self.compiler.modelbuilder.toolcontext.opt_no_check_initialization.value then
1088 self.add("if ({res} == NULL) \{")
1089 self.add_abort("Uninitialized attribute {a.name}")
1090 self.add("\}")
1091 end
1092
1093 # Return the attribute or its unboxed version
1094 # Note: it is mandatory since we reuse the box on write, we do not whant that the box escapes
1095 return self.autobox(res, ret)
1096 else
1097 var res = self.new_var(ret)
1098 self.add("{res} = {recv}->attrs[{a.const_color}].{ret.ctypename}; /* {a} on {recv.inspect} */")
1099
1100 # Check for Uninitialized attribute
1101 if ret.ctype == "val*" and not ret isa MNullableType and not self.compiler.modelbuilder.toolcontext.opt_no_check_initialization.value then
1102 self.add("if ({res} == NULL) \{")
1103 self.add_abort("Uninitialized attribute {a.name}")
1104 self.add("\}")
1105 end
1106
1107 return res
1108 end
1109 end
1110
1111 redef fun write_attribute(a, recv, value)
1112 do
1113 self.check_recv_notnull(recv)
1114
1115 # What is the declared type of the attribute?
1116 var mtype = a.intro.static_mtype.as(not null)
1117 var intromclassdef = a.intro.mclassdef
1118 mtype = mtype.resolve_for(intromclassdef.bound_mtype, intromclassdef.bound_mtype, intromclassdef.mmodule, true)
1119
1120 # Adapt the value to the declared type
1121 value = self.autobox(value, mtype)
1122
1123 if self.compiler.modelbuilder.toolcontext.opt_no_union_attribute.value then
1124 var attr = "{recv}->attrs[{a.const_color}]"
1125 if mtype.ctype != "val*" then
1126 assert mtype isa MClassType
1127 # The attribute is primitive, thus we store it in a box
1128 # The trick is to create the box the first time then resuse the box
1129 self.add("if ({attr} != NULL) \{")
1130 self.add("((struct instance_{mtype.c_name}*){attr})->value = {value}; /* {a} on {recv.inspect} */")
1131 self.add("\} else \{")
1132 value = self.autobox(value, self.object_type.as_nullable)
1133 self.add("{attr} = {value}; /* {a} on {recv.inspect} */")
1134 self.add("\}")
1135 else
1136 # The attribute is not primitive, thus store it direclty
1137 self.add("{attr} = {value}; /* {a} on {recv.inspect} */")
1138 end
1139 else
1140 self.add("{recv}->attrs[{a.const_color}].{mtype.ctypename} = {value}; /* {a} on {recv.inspect} */")
1141 end
1142 end
1143
1144 redef fun init_instance(mtype)
1145 do
1146 var compiler = self.compiler
1147 if mtype isa MGenericType and mtype.need_anchor then
1148 link_unresolved_type(self.frame.mpropdef.mclassdef, mtype)
1149 var recv = self.frame.arguments.first
1150 var recv_type_info = self.type_info(recv)
1151 if compiler.modelbuilder.toolcontext.opt_phmod_typing.value or compiler.modelbuilder.toolcontext.opt_phand_typing.value then
1152 return self.new_expr("NEW_{mtype.mclass.c_name}((struct type *) {recv_type_info}->resolution_table->types[HASH({recv_type_info}->resolution_table->mask, {mtype.const_color})])", mtype)
1153 else
1154 return self.new_expr("NEW_{mtype.mclass.c_name}((struct type *) {recv_type_info}->resolution_table->types[{mtype.const_color}])", mtype)
1155 end
1156 end
1157 compiler.undead_types.add(mtype)
1158 return self.new_expr("NEW_{mtype.mclass.c_name}((struct type *) &type_{mtype.c_name})", mtype)
1159 end
1160
1161 redef fun check_init_instance(value, mtype)
1162 do
1163 if self.compiler.modelbuilder.toolcontext.opt_no_check_initialization.value then return
1164 self.add("CHECK_NEW_{mtype.mclass.c_name}({value});")
1165 end
1166
1167 redef fun type_test(value, mtype, tag)
1168 do
1169 self.add("/* {value.inspect} isa {mtype} */")
1170 var compiler = self.compiler
1171
1172 var recv = self.frame.arguments.first
1173 var recv_type_info = self.type_info(recv)
1174
1175 var res = self.new_var(bool_type)
1176
1177 var cltype = self.get_name("cltype")
1178 self.add_decl("int {cltype};")
1179 var idtype = self.get_name("idtype")
1180 self.add_decl("int {idtype};")
1181
1182 var maybe_null = self.maybe_null(value)
1183 var accept_null = "0"
1184 var ntype = mtype
1185 if ntype isa MNullableType then
1186 ntype = ntype.mtype
1187 accept_null = "1"
1188 end
1189
1190 if value.mcasttype.is_subtype(self.frame.mpropdef.mclassdef.mmodule, self.frame.mpropdef.mclassdef.bound_mtype, mtype) then
1191 self.add("{res} = 1; /* easy {value.inspect} isa {mtype}*/")
1192 if compiler.modelbuilder.toolcontext.opt_typing_test_metrics.value then
1193 self.compiler.count_type_test_skipped[tag] += 1
1194 self.add("count_type_test_skipped_{tag}++;")
1195 end
1196 return res
1197 end
1198
1199 if ntype.need_anchor then
1200 var type_struct = self.get_name("type_struct")
1201 self.add_decl("struct type* {type_struct};")
1202
1203 # Either with resolution_table with a direct resolution
1204 link_unresolved_type(self.frame.mpropdef.mclassdef, ntype)
1205 if compiler.modelbuilder.toolcontext.opt_phmod_typing.value or compiler.modelbuilder.toolcontext.opt_phand_typing.value then
1206 self.add("{type_struct} = {recv_type_info}->resolution_table->types[HASH({recv_type_info}->resolution_table->mask, {ntype.const_color})];")
1207 else
1208 self.add("{type_struct} = {recv_type_info}->resolution_table->types[{ntype.const_color}];")
1209 end
1210 if compiler.modelbuilder.toolcontext.opt_typing_test_metrics.value then
1211 self.compiler.count_type_test_unresolved[tag] += 1
1212 self.add("count_type_test_unresolved_{tag}++;")
1213 end
1214 self.add("{cltype} = {type_struct}->color;")
1215 self.add("{idtype} = {type_struct}->id;")
1216 if maybe_null and accept_null == "0" then
1217 var is_nullable = self.get_name("is_nullable")
1218 self.add_decl("short int {is_nullable};")
1219 self.add("{is_nullable} = {type_struct}->is_nullable;")
1220 accept_null = is_nullable.to_s
1221 end
1222 else if ntype isa MClassType then
1223 compiler.undead_types.add(mtype)
1224 self.add("{cltype} = type_{mtype.c_name}.color;")
1225 self.add("{idtype} = type_{mtype.c_name}.id;")
1226 if compiler.modelbuilder.toolcontext.opt_typing_test_metrics.value then
1227 self.compiler.count_type_test_resolved[tag] += 1
1228 self.add("count_type_test_resolved_{tag}++;")
1229 end
1230 else
1231 self.add("printf(\"NOT YET IMPLEMENTED: type_test(%s, {mtype}).\\n\", \"{value.inspect}\"); exit(1);")
1232 end
1233
1234 # check color is in table
1235 if maybe_null then
1236 self.add("if({value} == NULL) \{")
1237 self.add("{res} = {accept_null};")
1238 self.add("\} else \{")
1239 end
1240 var value_type_info = self.type_info(value)
1241 if compiler.modelbuilder.toolcontext.opt_phmod_typing.value or compiler.modelbuilder.toolcontext.opt_phand_typing.value then
1242 self.add("{cltype} = HASH({value_type_info}->color, {idtype});")
1243 end
1244 self.add("if({cltype} >= {value_type_info}->table_size) \{")
1245 self.add("{res} = 0;")
1246 self.add("\} else \{")
1247 self.add("{res} = {value_type_info}->type_table[{cltype}] == {idtype};")
1248 self.add("\}")
1249 if maybe_null then
1250 self.add("\}")
1251 end
1252
1253 return res
1254 end
1255
1256 redef fun is_same_type_test(value1, value2)
1257 do
1258 var res = self.new_var(bool_type)
1259 # Swap values to be symetric
1260 if value2.mtype.ctype != "val*" and value1.mtype.ctype == "val*" then
1261 var tmp = value1
1262 value1 = value2
1263 value2 = tmp
1264 end
1265 if value1.mtype.ctype != "val*" then
1266 if value2.mtype == value1.mtype then
1267 self.add("{res} = 1; /* is_same_type_test: compatible types {value1.mtype} vs. {value2.mtype} */")
1268 else if value2.mtype.ctype != "val*" then
1269 self.add("{res} = 0; /* is_same_type_test: incompatible types {value1.mtype} vs. {value2.mtype}*/")
1270 else
1271 var mtype1 = value1.mtype.as(MClassType)
1272 self.add("{res} = ({value2} != NULL) && ({value2}->class == (struct class*) &class_{mtype1.c_name}); /* is_same_type_test */")
1273 end
1274 else
1275 self.add("{res} = ({value1} == {value2}) || ({value1} != NULL && {value2} != NULL && {value1}->class == {value2}->class); /* is_same_type_test */")
1276 end
1277 return res
1278 end
1279
1280 redef fun class_name_string(value)
1281 do
1282 var res = self.get_name("var_class_name")
1283 self.add_decl("const char* {res};")
1284 if value.mtype.ctype == "val*" then
1285 self.add "{res} = {value} == NULL ? \"null\" : {value}->type->name;"
1286 else
1287 self.add "{res} = type_{value.mtype.c_name}.name;"
1288 end
1289 return res
1290 end
1291
1292 redef fun equal_test(value1, value2)
1293 do
1294 var res = self.new_var(bool_type)
1295 if value2.mtype.ctype != "val*" and value1.mtype.ctype == "val*" then
1296 var tmp = value1
1297 value1 = value2
1298 value2 = tmp
1299 end
1300 if value1.mtype.ctype != "val*" then
1301 if value2.mtype == value1.mtype then
1302 self.add("{res} = {value1} == {value2};")
1303 else if value2.mtype.ctype != "val*" then
1304 self.add("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
1305 else
1306 var mtype1 = value1.mtype.as(MClassType)
1307 self.add("{res} = ({value2} != NULL) && ({value2}->class == (struct class*) &class_{mtype1.c_name});")
1308 self.add("if ({res}) \{")
1309 self.add("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
1310 self.add("\}")
1311 end
1312 return res
1313 end
1314 var maybe_null = true
1315 var test = new Array[String]
1316 var t1 = value1.mcasttype
1317 if t1 isa MNullableType then
1318 test.add("{value1} != NULL")
1319 t1 = t1.mtype
1320 else
1321 maybe_null = false
1322 end
1323 var t2 = value2.mcasttype
1324 if t2 isa MNullableType then
1325 test.add("{value2} != NULL")
1326 t2 = t2.mtype
1327 else
1328 maybe_null = false
1329 end
1330
1331 var incompatible = false
1332 var primitive
1333 if t1.ctype != "val*" then
1334 primitive = t1
1335 if t1 == t2 then
1336 # No need to compare class
1337 else if t2.ctype != "val*" then
1338 incompatible = true
1339 else if can_be_primitive(value2) then
1340 test.add("{value1}->class == {value2}->class")
1341 else
1342 incompatible = true
1343 end
1344 else if t2.ctype != "val*" then
1345 primitive = t2
1346 if can_be_primitive(value1) then
1347 test.add("{value1}->class == {value2}->class")
1348 else
1349 incompatible = true
1350 end
1351 else
1352 primitive = null
1353 end
1354
1355 if incompatible then
1356 if maybe_null then
1357 self.add("{res} = {value1} == {value2}; /* incompatible types {t1} vs. {t2}; but may be NULL*/")
1358 return res
1359 else
1360 self.add("{res} = 0; /* incompatible types {t1} vs. {t2}; cannot be NULL */")
1361 return res
1362 end
1363 end
1364 if primitive != null then
1365 test.add("((struct instance_{primitive.c_name}*){value1})->value == ((struct instance_{primitive.c_name}*){value2})->value")
1366 else if can_be_primitive(value1) and can_be_primitive(value2) then
1367 test.add("{value1}->class == {value2}->class")
1368 var s = new Array[String]
1369 for t, v in self.compiler.box_kinds do
1370 s.add "({value1}->class->box_kind == {v} && ((struct instance_{t.c_name}*){value1})->value == ((struct instance_{t.c_name}*){value2})->value)"
1371 end
1372 test.add("({s.join(" || ")})")
1373 else
1374 self.add("{res} = {value1} == {value2};")
1375 return res
1376 end
1377 self.add("{res} = {value1} == {value2} || ({test.join(" && ")});")
1378 return res
1379 end
1380
1381 fun can_be_primitive(value: RuntimeVariable): Bool
1382 do
1383 var t = value.mcasttype
1384 if t isa MNullableType then t = t.mtype
1385 if not t isa MClassType then return false
1386 var k = t.mclass.kind
1387 return k == interface_kind or t.ctype != "val*"
1388 end
1389
1390 fun maybe_null(value: RuntimeVariable): Bool
1391 do
1392 var t = value.mcasttype
1393 return t isa MNullableType or t isa MNullType
1394 end
1395
1396 redef fun array_instance(array, elttype)
1397 do
1398 var nclass = self.get_class("NativeArray")
1399 var arrayclass = self.get_class("Array")
1400 var arraytype = arrayclass.get_mtype([elttype])
1401 var res = self.init_instance(arraytype)
1402 self.add("\{ /* {res} = array_instance Array[{elttype}] */")
1403 var length = self.int_instance(array.length)
1404 var nat = native_array_instance(elttype, length)
1405 for i in [0..array.length[ do
1406 var r = self.autobox(array[i], self.object_type)
1407 self.add("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
1408 end
1409 self.send(self.get_property("with_native", arrayclass.intro.bound_mtype), [res, nat, length])
1410 self.check_init_instance(res, arraytype)
1411 self.add("\}")
1412 return res
1413 end
1414
1415 fun native_array_instance(elttype: MType, length: RuntimeVariable): RuntimeVariable
1416 do
1417 var mtype = self.get_class("NativeArray").get_mtype([elttype])
1418 assert mtype isa MGenericType
1419 var compiler = self.compiler
1420 if mtype.need_anchor then
1421 link_unresolved_type(self.frame.mpropdef.mclassdef, mtype)
1422 var recv = self.frame.arguments.first
1423 var recv_type_info = self.type_info(recv)
1424 if compiler.modelbuilder.toolcontext.opt_phmod_typing.value or compiler.modelbuilder.toolcontext.opt_phand_typing.value then
1425 return self.new_expr("NEW_{mtype.mclass.c_name}({length}, (struct type *) {recv_type_info}->resolution_table->types[HASH({recv_type_info}->resolution_table->mask, {mtype.const_color})])", mtype)
1426 else
1427 return self.new_expr("NEW_{mtype.mclass.c_name}({length}, (struct type *) {recv_type_info}->resolution_table->types[{mtype.const_color}])", mtype)
1428 end
1429 end
1430 compiler.undead_types.add(mtype)
1431 return self.new_expr("NEW_{mtype.mclass.c_name}({length}, (struct type *) &type_{mtype.c_name})", mtype)
1432 end
1433
1434 redef fun native_array_def(pname, ret_type, arguments)
1435 do
1436 var elttype = arguments.first.mtype
1437 var nclass = self.get_class("NativeArray")
1438 var recv = "((struct instance_{nclass.c_name}*){arguments[0]})->values"
1439 if pname == "[]" then
1440 self.ret(self.new_expr("{recv}[{arguments[1]}]", ret_type.as(not null)))
1441 return
1442 else if pname == "[]=" then
1443 self.add("{recv}[{arguments[1]}]={arguments[2]};")
1444 return
1445 else if pname == "copy_to" then
1446 var recv1 = "((struct instance_{nclass.c_name}*){arguments[1]})->values"
1447 self.add("memcpy({recv1}, {recv}, {arguments[2]}*sizeof({elttype.ctype}));")
1448 return
1449 end
1450 end
1451
1452 redef fun calloc_array(ret_type, arguments)
1453 do
1454 var mclass = self.get_class("ArrayCapable")
1455 var ft = mclass.mclass_type.arguments.first.as(MParameterType)
1456 var res = self.native_array_instance(ft, arguments[1])
1457 self.ret(res)
1458 end
1459
1460 fun link_unresolved_type(mclassdef: MClassDef, mtype: MType) do
1461 assert mtype.need_anchor
1462 var compiler = self.compiler
1463 if not compiler.live_unresolved_types.has_key(self.frame.mpropdef.mclassdef) then
1464 compiler.live_unresolved_types[self.frame.mpropdef.mclassdef] = new HashSet[MType]
1465 end
1466 compiler.live_unresolved_types[self.frame.mpropdef.mclassdef].add(mtype)
1467 end
1468 end
1469
1470 # The C function associated to a methoddef separately compiled
1471 class SeparateRuntimeFunction
1472 super AbstractRuntimeFunction
1473
1474 redef fun build_c_name: String do return "{mmethoddef.c_name}"
1475
1476 redef fun to_s do return self.mmethoddef.to_s
1477
1478 redef fun compile_to_c(compiler)
1479 do
1480 var mmethoddef = self.mmethoddef
1481
1482 var recv = self.mmethoddef.mclassdef.bound_mtype
1483 var v = compiler.new_visitor
1484 var selfvar = new RuntimeVariable("self", recv, recv)
1485 var arguments = new Array[RuntimeVariable]
1486 var frame = new Frame(v, mmethoddef, recv, arguments)
1487 v.frame = frame
1488
1489 var msignature = mmethoddef.msignature.resolve_for(mmethoddef.mclassdef.bound_mtype, mmethoddef.mclassdef.bound_mtype, mmethoddef.mclassdef.mmodule, true)
1490
1491 var sig = new Buffer
1492 var comment = new Buffer
1493 var ret = msignature.return_mtype
1494 if ret != null then
1495 sig.append("{ret.ctype} ")
1496 else if mmethoddef.mproperty.is_new then
1497 ret = recv
1498 sig.append("{ret.ctype} ")
1499 else
1500 sig.append("void ")
1501 end
1502 sig.append(self.c_name)
1503 sig.append("({selfvar.mtype.ctype} {selfvar}")
1504 comment.append("(self: {selfvar}")
1505 arguments.add(selfvar)
1506 for i in [0..msignature.arity[ do
1507 var mtype = msignature.mparameters[i].mtype
1508 if i == msignature.vararg_rank then
1509 mtype = v.get_class("Array").get_mtype([mtype])
1510 end
1511 comment.append(", {mtype}")
1512 sig.append(", {mtype.ctype} p{i}")
1513 var argvar = new RuntimeVariable("p{i}", mtype, mtype)
1514 arguments.add(argvar)
1515 end
1516 sig.append(")")
1517 comment.append(")")
1518 if ret != null then
1519 comment.append(": {ret}")
1520 end
1521 compiler.header.add_decl("{sig};")
1522
1523 v.add_decl("/* method {self} for {comment} */")
1524 v.add_decl("{sig} \{")
1525 if ret != null then
1526 frame.returnvar = v.new_var(ret)
1527 end
1528 frame.returnlabel = v.get_name("RET_LABEL")
1529
1530 if recv != arguments.first.mtype then
1531 #print "{self} {recv} {arguments.first}"
1532 end
1533 mmethoddef.compile_inside_to_c(v, arguments)
1534
1535 v.add("{frame.returnlabel.as(not null)}:;")
1536 if ret != null then
1537 v.add("return {frame.returnvar.as(not null)};")
1538 end
1539 v.add("\}")
1540 end
1541 end
1542
1543 # The C function associated to a methoddef on a primitive type, stored into a VFT of a class
1544 # The first parameter (the reciever) is always typed by val* in order to accept an object value
1545 class VirtualRuntimeFunction
1546 super AbstractRuntimeFunction
1547
1548 redef fun build_c_name: String do return "VIRTUAL_{mmethoddef.c_name}"
1549
1550 redef fun to_s do return self.mmethoddef.to_s
1551
1552 redef fun compile_to_c(compiler)
1553 do
1554 var mmethoddef = self.mmethoddef
1555
1556 var recv = self.mmethoddef.mclassdef.bound_mtype
1557 var v = compiler.new_visitor
1558 var selfvar = new RuntimeVariable("self", v.object_type, recv)
1559 var arguments = new Array[RuntimeVariable]
1560 var frame = new Frame(v, mmethoddef, recv, arguments)
1561 v.frame = frame
1562
1563 var sig = new Buffer
1564 var comment = new Buffer
1565
1566 # Because the function is virtual, the signature must match the one of the original class
1567 var intromclassdef = self.mmethoddef.mproperty.intro.mclassdef
1568 var msignature = mmethoddef.mproperty.intro.msignature.resolve_for(intromclassdef.bound_mtype, intromclassdef.bound_mtype, intromclassdef.mmodule, true)
1569 var ret = msignature.return_mtype
1570 if ret != null then
1571 sig.append("{ret.ctype} ")
1572 else if mmethoddef.mproperty.is_new then
1573 ret = recv
1574 sig.append("{ret.ctype} ")
1575 else
1576 sig.append("void ")
1577 end
1578 sig.append(self.c_name)
1579 sig.append("({selfvar.mtype.ctype} {selfvar}")
1580 comment.append("(self: {selfvar}")
1581 arguments.add(selfvar)
1582 for i in [0..msignature.arity[ do
1583 var mtype = msignature.mparameters[i].mtype
1584 if i == msignature.vararg_rank then
1585 mtype = v.get_class("Array").get_mtype([mtype])
1586 end
1587 comment.append(", {mtype}")
1588 sig.append(", {mtype.ctype} p{i}")
1589 var argvar = new RuntimeVariable("p{i}", mtype, mtype)
1590 arguments.add(argvar)
1591 end
1592 sig.append(")")
1593 comment.append(")")
1594 if ret != null then
1595 comment.append(": {ret}")
1596 end
1597 compiler.header.add_decl("{sig};")
1598
1599 v.add_decl("/* method {self} for {comment} */")
1600 v.add_decl("{sig} \{")
1601 if ret != null then
1602 frame.returnvar = v.new_var(ret)
1603 end
1604 frame.returnlabel = v.get_name("RET_LABEL")
1605
1606 if recv != arguments.first.mtype then
1607 #print "{self} {recv} {arguments.first}"
1608 end
1609 mmethoddef.compile_inside_to_c(v, arguments)
1610
1611 v.add("{frame.returnlabel.as(not null)}:;")
1612 if ret != null then
1613 v.add("return {frame.returnvar.as(not null)};")
1614 end
1615 v.add("\}")
1616 end
1617
1618 # TODO ?
1619 redef fun call(v, arguments) do abort
1620 end
1621
1622 redef class MType
1623 fun const_color: String do return "COLOR_{c_name}"
1624 end
1625
1626 redef class MProperty
1627 fun const_color: String do return "COLOR_{c_name}"
1628 end