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