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