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