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