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