1 # This file is part of NIT ( http://www.nitlanguage.org ).
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
15 # Separate compilation of a Nit program
16 module separate_compiler
18 import abstract_compiler
19 import layout_builders
20 import rapid_type_analysis
21 import collect_super_sends
24 # Add separate compiler specific options
25 redef class ToolContext
27 var opt_separate
: OptionBool = new OptionBool("Use separate compilation", "--separate")
29 var opt_no_inline_intern
: OptionBool = new OptionBool("Do not inline call to intern methods", "--no-inline-intern")
30 # --no-union-attribute
31 var opt_no_union_attribute
: OptionBool = new OptionBool("Put primitive attibutes in a box instead of an union", "--no-union-attribute")
32 # --no-shortcut-equate
33 var opt_no_shortcut_equate
: OptionBool = new OptionBool("Always call == in a polymorphic way", "--no-shortcut-equal")
34 # --inline-coloring-numbers
35 var opt_inline_coloring_numbers
: OptionBool = new OptionBool("Inline colors and ids", "--inline-coloring-numbers")
36 # --use-naive-coloring
37 var opt_bm_typing
: OptionBool = new OptionBool("Colorize items incrementaly, used to simulate binary matrix typing", "--bm-typing")
38 # --use-mod-perfect-hashing
39 var opt_phmod_typing
: OptionBool = new OptionBool("Replace coloration by perfect hashing (with mod operator)", "--phmod-typing")
40 # --use-and-perfect-hashing
41 var opt_phand_typing
: OptionBool = new OptionBool("Replace coloration by perfect hashing (with and operator)", "--phand-typing")
43 var opt_tables_metrics
: OptionBool = new OptionBool("Enable static size measuring of tables used for vft, typing and resolution", "--tables-metrics")
48 self.option_context
.add_option
(self.opt_separate
)
49 self.option_context
.add_option
(self.opt_no_inline_intern
)
50 self.option_context
.add_option
(self.opt_no_union_attribute
)
51 self.option_context
.add_option
(self.opt_no_shortcut_equate
)
52 self.option_context
.add_option
(self.opt_inline_coloring_numbers
)
53 self.option_context
.add_option
(self.opt_bm_typing
)
54 self.option_context
.add_option
(self.opt_phmod_typing
)
55 self.option_context
.add_option
(self.opt_phand_typing
)
56 self.option_context
.add_option
(self.opt_tables_metrics
)
60 redef class ModelBuilder
61 fun run_separate_compiler
(mainmodule
: MModule, runtime_type_analysis
: nullable RapidTypeAnalysis)
64 self.toolcontext
.info
("*** GENERATING C ***", 1)
66 var compiler
= new SeparateCompiler(mainmodule
, self, runtime_type_analysis
)
67 compiler
.compile_header
69 # compile class structures
70 self.toolcontext
.info
("Property coloring", 2)
71 compiler
.new_file
("{mainmodule.name}.classes")
72 compiler
.do_property_coloring
73 for m
in mainmodule
.in_importation
.greaters
do
74 for mclass
in m
.intro_mclasses
do
75 if mclass
.kind
== abstract_kind
or mclass
.kind
== interface_kind
then continue
76 compiler
.compile_class_to_c
(mclass
)
80 # The main function of the C
81 compiler
.new_file
("{mainmodule.name}.main")
82 compiler
.compile_main_function
85 for m
in mainmodule
.in_importation
.greaters
do
86 self.toolcontext
.info
("Generate C for module {m}", 2)
87 compiler
.new_file
("{m.name}.sep")
88 compiler
.compile_module_to_c
(m
)
91 # compile live & cast type structures
92 self.toolcontext
.info
("Type coloring", 2)
93 compiler
.new_file
("{mainmodule.name}.types")
94 var mtypes
= compiler
.do_type_coloring
96 compiler
.compile_type_to_c
(t
)
98 # compile remaining types structures (useless but needed for the symbol resolution at link-time)
99 for t
in compiler
.undead_types
do
100 if mtypes
.has
(t
) then continue
101 compiler
.compile_type_to_c
(t
)
104 compiler
.display_stats
107 self.toolcontext
.info
("*** END GENERATING C: {time1-time0} ***", 2)
108 write_and_make
(compiler
)
112 # Singleton that store the knowledge about the separate compilation process
113 class SeparateCompiler
114 super AbstractCompiler
116 redef type VISITOR: SeparateCompilerVisitor
118 # The result of the RTA (used to know live types and methods)
119 var runtime_type_analysis
: nullable RapidTypeAnalysis
121 private var undead_types
: Set[MType] = new HashSet[MType]
122 private var live_unresolved_types
: Map[MClassDef, Set[MType]] = new HashMap[MClassDef, HashSet[MType]]
124 private var type_layout
: nullable Layout[MType]
125 private var resolution_layout
: nullable Layout[MType]
126 protected var method_layout
: nullable Layout[PropertyLayoutElement]
127 protected var attr_layout
: nullable Layout[MAttribute]
129 init(mainmodule
: MModule, mmbuilder
: ModelBuilder, runtime_type_analysis
: nullable RapidTypeAnalysis) do
130 super(mainmodule
, mmbuilder
)
131 var file
= new_file
("nit.common")
132 self.header
= new CodeWriter(file
)
133 self.runtime_type_analysis
= runtime_type_analysis
134 self.compile_box_kinds
137 redef fun compile_header_structs
do
138 self.header
.add_decl
("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
139 self.compile_header_attribute_structs
140 self.header
.add_decl
("struct class \{ int box_kind; nitmethod_t vft[]; \}; /* general C type representing a Nit class. */")
142 # With resolution_table_table, all live type resolution are stored in a big table: resolution_table
143 self.header
.add_decl
("struct type \{ int id; const char *name; int color; short int is_nullable; const struct types *resolution_table; int table_size; int type_table[]; \}; /* general C type representing a Nit type. */")
144 self.header
.add_decl
("struct instance \{ const struct type *type; const struct class *class; nitattribute_t attrs[]; \}; /* general C type representing a Nit instance. */")
146 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
147 self.header
.add_decl
("struct types \{ int mask; const struct type *types[]; \}; /* a list types (used for vts, fts and unresolved lists). */")
149 self.header
.add_decl
("struct types \{ int dummy; const struct type *types[]; \}; /* a list types (used for vts, fts and unresolved lists). */")
152 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
153 self.header
.add_decl
("#define HASH(mask, id) ((mask)%(id))")
154 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
155 self.header
.add_decl
("#define HASH(mask, id) ((mask)&(id))")
158 self.header
.add_decl
("typedef struct instance val; /* general C type representing a Nit instance. */")
161 fun compile_header_attribute_structs
163 if modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
164 self.header
.add_decl
("typedef void* nitattribute_t; /* general C type representing a Nit attribute. */")
166 self.header
.add_decl
("typedef union \{")
167 self.header
.add_decl
("void* val;")
168 for c
, v
in self.box_kinds
do
169 var t
= c
.mclass_type
170 self.header
.add_decl
("{t.ctype} {t.ctypename};")
172 self.header
.add_decl
("\} nitattribute_t; /* general C type representing a Nit attribute. */")
176 fun compile_box_kinds
178 # Collect all bas box class
179 # FIXME: this is not completely fine with a separate compilation scheme
180 for classname
in ["Int", "Bool", "Char", "Float", "NativeString", "Pointer"] do
181 var classes
= self.mainmodule
.model
.get_mclasses_by_name
(classname
)
182 if classes
== null then continue
183 assert classes
.length
== 1 else print classes
.join
(", ")
184 self.box_kinds
[classes
.first
] = self.box_kinds
.length
+ 1
188 var box_kinds
= new HashMap[MClass, Int]
190 fun box_kind_of
(mclass
: MClass): Int
192 if mclass
.mclass_type
.ctype
== "val*" then
194 else if mclass
.kind
== extern_kind
then
195 return self.box_kinds
[self.mainmodule
.get_primitive_class
("Pointer")]
197 return self.box_kinds
[mclass
]
202 fun compile_color_consts
(colors
: Map[Object, Int]) do
204 for m
, c
in colors
do
205 compile_color_const
(v
, m
, c
)
209 fun compile_color_const
(v
: SeparateCompilerVisitor, m
: Object, color
: Int) do
210 if color_consts_done
.has
(m
) then return
211 if m
isa MProperty then
212 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
213 self.provide_declaration
(m
.const_color
, "#define {m.const_color} {color}")
215 self.provide_declaration
(m
.const_color
, "extern const int {m.const_color};")
216 v
.add
("const int {m.const_color} = {color};")
218 else if m
isa MPropDef then
219 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
220 self.provide_declaration
(m
.const_color
, "#define {m.const_color} {color}")
222 self.provide_declaration
(m
.const_color
, "extern const int {m.const_color};")
223 v
.add
("const int {m.const_color} = {color};")
225 else if m
isa MType then
226 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
227 self.provide_declaration
(m
.const_color
, "#define {m.const_color} {color}")
229 self.provide_declaration
(m
.const_color
, "extern const int {m.const_color};")
230 v
.add
("const int {m.const_color} = {color};")
233 color_consts_done
.add
(m
)
236 private var color_consts_done
= new HashSet[Object]
238 # colorize classe properties
239 fun do_property_coloring
do
240 var mclasses
= new HashSet[MClass].from
(modelbuilder
.model
.mclasses
)
243 var method_layout_builder
: PropertyLayoutBuilder[PropertyLayoutElement]
244 var attribute_layout_builder
: PropertyLayoutBuilder[MAttribute]
245 #FIXME PH and BM layouts too slow for large programs
246 #if modelbuilder.toolcontext.opt_bm_typing.value then
247 # method_layout_builder = new MMethodBMizer(self.mainmodule)
248 # attribute_layout_builder = new MAttributeBMizer(self.mainmodule)
249 #else if modelbuilder.toolcontext.opt_phmod_typing.value then
250 # method_layout_builder = new MMethodHasher(new PHModOperator, self.mainmodule)
251 # attribute_layout_builder = new MAttributeHasher(new PHModOperator, self.mainmodule)
252 #else if modelbuilder.toolcontext.opt_phand_typing.value then
253 # method_layout_builder = new MMethodHasher(new PHAndOperator, self.mainmodule)
254 # attribute_layout_builder = new MAttributeHasher(new PHAndOperator, self.mainmodule)
257 var class_layout_builder
= new MClassColorer(self.mainmodule
)
258 class_layout_builder
.build_layout
(mclasses
)
259 method_layout_builder
= new MPropertyColorer[PropertyLayoutElement](self.mainmodule
, class_layout_builder
)
260 attribute_layout_builder
= new MPropertyColorer[MAttribute](self.mainmodule
, class_layout_builder
)
263 # lookup properties to build layout with
264 var mmethods
= new HashMap[MClass, Set[PropertyLayoutElement]]
265 var mattributes
= new HashMap[MClass, Set[MAttribute]]
266 for mclass
in mclasses
do
267 mmethods
[mclass
] = new HashSet[PropertyLayoutElement]
268 mattributes
[mclass
] = new HashSet[MAttribute]
269 for mprop
in self.mainmodule
.properties
(mclass
) do
270 if mprop
isa MMethod then
271 mmethods
[mclass
].add
(mprop
)
272 else if mprop
isa MAttribute then
273 mattributes
[mclass
].add
(mprop
)
278 # lookup super calls and add it to the list of mmethods to build layout with
280 if runtime_type_analysis
!= null then
281 super_calls
= runtime_type_analysis
.live_super_sends
283 super_calls
= modelbuilder
.collect_super_sends
285 for mmethoddef
in super_calls
do
286 var mclass
= mmethoddef
.mclassdef
.mclass
287 mmethods
[mclass
].add
(mmethoddef
)
288 for descendant
in mclass
.in_hierarchy
(self.mainmodule
).smallers
do
289 mmethods
[descendant
].add
(mmethoddef
)
294 self.method_layout
= method_layout_builder
.build_layout
(mmethods
)
295 self.method_tables
= build_method_tables
(mclasses
, super_calls
)
296 self.compile_color_consts
(method_layout
.pos
)
298 # attribute null color to dead supercalls
299 for mmodule
in self.mainmodule
.in_importation
.greaters
do
300 for mclassdef
in mmodule
.mclassdefs
do
301 for mpropdef
in mclassdef
.mpropdefs
do
302 if mpropdef
.has_supercall
then
303 compile_color_const
(new_visitor
, mpropdef
, -1)
309 # attributes coloration
310 self.attr_layout
= attribute_layout_builder
.build_layout
(mattributes
)
311 self.attr_tables
= build_attr_tables
(mclasses
)
312 self.compile_color_consts
(attr_layout
.pos
)
315 fun build_method_tables
(mclasses
: Set[MClass], super_calls
: Set[MMethodDef]): Map[MClass, Array[nullable MPropDef]] do
316 var layout
= self.method_layout
317 var tables
= new HashMap[MClass, Array[nullable MPropDef]]
318 for mclass
in mclasses
do
319 var table
= new Array[nullable MPropDef]
320 var supercalls
= new List[MMethodDef]
322 # first, fill table from parents by reverse linearization order
323 var parents
= new Array[MClass]
324 if mainmodule
.flatten_mclass_hierarchy
.has
(mclass
) then
325 parents
= mclass
.in_hierarchy
(mainmodule
).greaters
.to_a
326 self.mainmodule
.linearize_mclasses
(parents
)
329 for parent
in parents
do
330 if parent
== mclass
then continue
331 for mproperty
in self.mainmodule
.properties
(parent
) do
332 if not mproperty
isa MMethod then continue
333 var color
= layout
.pos
[mproperty
]
334 if table
.length
<= color
then
335 for i
in [table
.length
.. color
[ do
339 for mpropdef
in mproperty
.mpropdefs
do
340 if mpropdef
.mclassdef
.mclass
== parent
then
341 table
[color
] = mpropdef
346 # lookup for super calls in super classes
347 for mmethoddef
in super_calls
do
348 for mclassdef
in parent
.mclassdefs
do
349 if mclassdef
.mpropdefs
.has
(mmethoddef
) then
350 supercalls
.add
(mmethoddef
)
356 # then override with local properties
357 for mproperty
in self.mainmodule
.properties
(mclass
) do
358 if not mproperty
isa MMethod then continue
359 var color
= layout
.pos
[mproperty
]
360 if table
.length
<= color
then
361 for i
in [table
.length
.. color
[ do
365 for mpropdef
in mproperty
.mpropdefs
do
366 if mpropdef
.mclassdef
.mclass
== mclass
then
367 table
[color
] = mpropdef
372 # lookup for super calls in local class
373 for mmethoddef
in super_calls
do
374 for mclassdef
in mclass
.mclassdefs
do
375 if mclassdef
.mpropdefs
.has
(mmethoddef
) then
376 supercalls
.add
(mmethoddef
)
380 # insert super calls in table according to receiver
381 for supercall
in supercalls
do
382 var color
= layout
.pos
[supercall
]
383 if table
.length
<= color
then
384 for i
in [table
.length
.. color
[ do
388 var mmethoddef
= supercall
.lookup_next_definition
(self.mainmodule
, mclass
.intro
.bound_mtype
)
389 table
[color
] = mmethoddef
391 tables
[mclass
] = table
396 fun build_attr_tables
(mclasses
: Set[MClass]): Map[MClass, Array[nullable MPropDef]] do
397 var layout
= self.attr_layout
398 var tables
= new HashMap[MClass, Array[nullable MPropDef]]
399 for mclass
in mclasses
do
400 var table
= new Array[nullable MPropDef]
401 # first, fill table from parents by reverse linearization order
402 var parents
= new Array[MClass]
403 if mainmodule
.flatten_mclass_hierarchy
.has
(mclass
) then
404 parents
= mclass
.in_hierarchy
(mainmodule
).greaters
.to_a
405 self.mainmodule
.linearize_mclasses
(parents
)
407 for parent
in parents
do
408 if parent
== mclass
then continue
409 for mproperty
in self.mainmodule
.properties
(parent
) do
410 if not mproperty
isa MAttribute then continue
411 var color
= layout
.pos
[mproperty
]
412 if table
.length
<= color
then
413 for i
in [table
.length
.. color
[ do
417 for mpropdef
in mproperty
.mpropdefs
do
418 if mpropdef
.mclassdef
.mclass
== parent
then
419 table
[color
] = mpropdef
425 # then override with local properties
426 for mproperty
in self.mainmodule
.properties
(mclass
) do
427 if not mproperty
isa MAttribute then continue
428 var color
= layout
.pos
[mproperty
]
429 if table
.length
<= color
then
430 for i
in [table
.length
.. color
[ do
434 for mpropdef
in mproperty
.mpropdefs
do
435 if mpropdef
.mclassdef
.mclass
== mclass
then
436 table
[color
] = mpropdef
440 tables
[mclass
] = table
445 # colorize live types of the program
446 private fun do_type_coloring
: POSet[MType] do
447 var mtypes
= new HashSet[MType]
448 mtypes
.add_all
(self.runtime_type_analysis
.live_types
)
449 mtypes
.add_all
(self.runtime_type_analysis
.live_cast_types
)
450 for c
in self.box_kinds
.keys
do
451 mtypes
.add
(c
.mclass_type
)
455 var layout_builder
: TypingLayoutBuilder[MType]
456 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
457 layout_builder
= new MTypeBMizer(self.mainmodule
)
458 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
459 layout_builder
= new MTypeHasher(new PHModOperator, self.mainmodule
)
460 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
461 layout_builder
= new MTypeHasher(new PHAndOperator, self.mainmodule
)
463 layout_builder
= new MTypeColorer(self.mainmodule
)
467 self.type_layout
= layout_builder
.build_layout
(mtypes
)
468 var poset
= layout_builder
.poset
.as(not null)
469 self.type_tables
= self.build_type_tables
(poset
)
471 # VT and FT are stored with other unresolved types in the big resolution_tables
472 self.compile_resolution_tables
(mtypes
)
478 fun build_type_tables
(mtypes
: POSet[MType]): Map[MType, Array[nullable MType]] do
479 var tables
= new HashMap[MType, Array[nullable MType]]
480 var layout
= self.type_layout
481 for mtype
in mtypes
do
482 var table
= new Array[nullable MType]
483 for sup
in mtypes
[mtype
].greaters
do
485 if layout
isa PHLayout[MType, MType] then
486 color
= layout
.hashes
[mtype
][sup
]
488 color
= layout
.pos
[sup
]
490 if table
.length
<= color
then
491 for i
in [table
.length
.. color
[ do
497 tables
[mtype
] = table
502 protected fun compile_resolution_tables
(mtypes
: Set[MType]) do
503 # resolution_tables is used to perform a type resolution at runtime in O(1)
505 # During the visit of the body of classes, live_unresolved_types are collected
507 # Collect all live_unresolved_types (visited in the body of classes)
509 # Determinate fo each livetype what are its possible requested anchored types
510 var mtype2unresolved
= new HashMap[MClassType, Set[MType]]
511 for mtype
in self.runtime_type_analysis
.live_types
do
512 var set
= new HashSet[MType]
513 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
514 if self.live_unresolved_types
.has_key
(cd
) then
515 set
.add_all
(self.live_unresolved_types
[cd
])
518 mtype2unresolved
[mtype
] = set
521 # Compute the table layout with the prefered method
522 var resolution_builder
: ResolutionLayoutBuilder
523 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
524 resolution_builder
= new ResolutionBMizer
525 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
526 resolution_builder
= new ResolutionHasher(new PHModOperator)
527 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
528 resolution_builder
= new ResolutionHasher(new PHAndOperator)
530 resolution_builder
= new ResolutionColorer
532 self.resolution_layout
= resolution_builder
.build_layout
(mtype2unresolved
)
533 self.resolution_tables
= self.build_resolution_tables
(mtype2unresolved
)
535 # Compile a C constant for each collected unresolved type.
536 # Either to a color, or to -1 if the unresolved type is dead (no live receiver can require it)
537 var all_unresolved
= new HashSet[MType]
538 for t
in self.live_unresolved_types
.values
do
539 all_unresolved
.add_all
(t
)
541 var all_unresolved_types_colors
= new HashMap[MType, Int]
542 for t
in all_unresolved
do
543 if self.resolution_layout
.pos
.has_key
(t
) then
544 all_unresolved_types_colors
[t
] = self.resolution_layout
.pos
[t
]
546 all_unresolved_types_colors
[t
] = -1
549 self.compile_color_consts
(all_unresolved_types_colors
)
552 #for k, v in unresolved_types_tables.as(not null) do
553 # print "{k}: {v.join(", ")}"
558 fun build_resolution_tables
(elements
: Map[MClassType, Set[MType]]): Map[MClassType, Array[nullable MType]] do
559 var tables
= new HashMap[MClassType, Array[nullable MType]]
560 var layout
= self.resolution_layout
561 for mclasstype
, mtypes
in elements
do
562 var table
= new Array[nullable MType]
563 for mtype
in mtypes
do
565 if layout
isa PHLayout[MClassType, MType] then
566 color
= layout
.hashes
[mclasstype
][mtype
]
568 color
= layout
.pos
[mtype
]
570 if table
.length
<= color
then
571 for i
in [table
.length
.. color
[ do
577 tables
[mclasstype
] = table
582 # Separately compile all the method definitions of the module
583 fun compile_module_to_c
(mmodule
: MModule)
585 var old_module
= self.mainmodule
586 self.mainmodule
= mmodule
587 for cd
in mmodule
.mclassdefs
do
588 for pd
in cd
.mpropdefs
do
589 if not pd
isa MMethodDef then continue
590 #print "compile {pd} @ {cd} @ {mmodule}"
591 var r
= pd
.separate_runtime_function
593 var r2
= pd
.virtual_runtime_function
594 r2
.compile_to_c
(self)
597 self.mainmodule
= old_module
600 # Globaly compile the type structure of a live type
601 fun compile_type_to_c
(mtype
: MType)
603 assert not mtype
.need_anchor
604 var layout
= self.type_layout
605 var is_live
= mtype
isa MClassType and runtime_type_analysis
.live_types
.has
(mtype
)
606 var is_cast_live
= runtime_type_analysis
.live_cast_types
.has
(mtype
)
607 var c_name
= mtype
.c_name
608 var v
= new SeparateCompilerVisitor(self)
609 v
.add_decl
("/* runtime type {mtype} */")
611 # extern const struct type_X
612 self.provide_declaration
("type_{c_name}", "extern const struct type type_{c_name};")
614 # const struct type_X
615 v
.add_decl
("const struct type type_{c_name} = \{")
617 # type id (for cast target)
619 v
.add_decl
("{layout.ids[mtype]},")
621 v
.add_decl
("-1, /*CAST DEAD*/")
625 v
.add_decl
("\"{mtype}\
", /* class_name_string */")
627 # type color (for cast target)
629 if layout
isa PHLayout[MType, MType] then
630 v
.add_decl
("{layout.masks[mtype]},")
632 v
.add_decl
("{layout.pos[mtype]},")
635 v
.add_decl
("-1, /*CAST DEAD*/")
639 if mtype
isa MNullableType then
645 # resolution table (for receiver)
647 var mclass_type
= mtype
648 if mclass_type
isa MNullableType then mclass_type
= mclass_type
.mtype
649 assert mclass_type
isa MClassType
650 if resolution_tables
[mclass_type
].is_empty
then
651 v
.add_decl
("NULL, /*NO RESOLUTIONS*/")
653 compile_type_resolution_table
(mtype
)
654 v
.require_declaration
("resolution_table_{c_name}")
655 v
.add_decl
("&resolution_table_{c_name},")
658 v
.add_decl
("NULL, /*DEAD*/")
661 # cast table (for receiver)
663 v
.add_decl
("{self.type_tables[mtype].length},")
665 for stype
in self.type_tables
[mtype
] do
666 if stype
== null then
667 v
.add_decl
("-1, /* empty */")
669 v
.add_decl
("{layout.ids[stype]}, /* {stype} */")
674 v
.add_decl
("0, \{\}, /*DEAD TYPE*/")
679 fun compile_type_resolution_table
(mtype
: MType) do
681 var mclass_type
: MClassType
682 if mtype
isa MNullableType then
683 mclass_type
= mtype
.mtype
.as(MClassType)
685 mclass_type
= mtype
.as(MClassType)
688 var layout
= self.resolution_layout
690 # extern const struct resolution_table_X resolution_table_X
691 self.provide_declaration
("resolution_table_{mtype.c_name}", "extern const struct types resolution_table_{mtype.c_name};")
693 # const struct fts_table_X fts_table_X
695 v
.add_decl
("const struct types resolution_table_{mtype.c_name} = \{")
696 if layout
isa PHLayout[MClassType, MType] then
697 v
.add_decl
("{layout.masks[mclass_type]},")
699 v
.add_decl
("0, /* dummy */")
702 for t
in self.resolution_tables
[mclass_type
] do
704 v
.add_decl
("NULL, /* empty */")
706 # The table stores the result of the type resolution
707 # Therefore, for a receiver `mclass_type`, and a unresolved type `t`
708 # the value stored is tv.
709 var tv
= t
.resolve_for
(mclass_type
, mclass_type
, self.mainmodule
, true)
710 # FIXME: What typeids means here? How can a tv not be live?
711 if self.type_layout
.ids
.has_key
(tv
) then
712 v
.require_declaration
("type_{tv.c_name}")
713 v
.add_decl
("&type_{tv.c_name}, /* {t}: {tv} */")
715 v
.add_decl
("NULL, /* empty ({t}: {tv} not a live type) */")
723 # Globally compile the table of the class mclass
724 # In a link-time optimisation compiler, tables are globally computed
725 # In a true separate compiler (a with dynamic loading) you cannot do this unfortnally
726 fun compile_class_to_c
(mclass
: MClass)
728 var mtype
= mclass
.intro
.bound_mtype
729 var c_name
= mclass
.c_name
731 var vft
= self.method_tables
[mclass
]
732 var attrs
= self.attr_tables
[mclass
]
735 var is_dead
= runtime_type_analysis
!= null and not runtime_type_analysis
.live_classes
.has
(mclass
) and mtype
.ctype
== "val*" and mclass
.name
!= "NativeArray"
737 v
.add_decl
("/* runtime class {c_name} */")
741 self.provide_declaration
("class_{c_name}", "extern const struct class class_{c_name};")
742 v
.add_decl
("const struct class class_{c_name} = \{")
743 v
.add_decl
("{self.box_kind_of(mclass)}, /* box_kind */")
745 for i
in [0 .. vft
.length
[ do
746 var mpropdef
= vft
[i
]
747 if mpropdef
== null then
748 v
.add_decl
("NULL, /* empty */")
750 assert mpropdef
isa MMethodDef
751 var rf
= mpropdef
.virtual_runtime_function
752 v
.require_declaration
(rf
.c_name
)
753 v
.add_decl
("(nitmethod_t){rf.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
760 if mtype
.ctype
!= "val*" then
761 #Build instance struct
762 self.header
.add_decl
("struct instance_{c_name} \{")
763 self.header
.add_decl
("const struct type *type;")
764 self.header
.add_decl
("const struct class *class;")
765 self.header
.add_decl
("{mtype.ctype} value;")
766 self.header
.add_decl
("\};")
768 if not self.runtime_type_analysis
.live_types
.has
(mtype
) then return
771 self.header
.add_decl
("val* BOX_{c_name}({mtype.ctype});")
772 v
.add_decl
("/* allocate {mtype} */")
773 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
774 v
.add
("struct instance_{c_name}*res = nit_alloc(sizeof(struct instance_{c_name}));")
775 v
.require_declaration
("type_{c_name}")
776 v
.add
("res->type = &type_{c_name};")
777 v
.require_declaration
("class_{c_name}")
778 v
.add
("res->class = &class_{c_name};")
779 v
.add
("res->value = value;")
780 v
.add
("return (val*)res;")
783 else if mclass
.name
== "NativeArray" then
784 #Build instance struct
785 self.header
.add_decl
("struct instance_{c_name} \{")
786 self.header
.add_decl
("const struct type *type;")
787 self.header
.add_decl
("const struct class *class;")
788 # NativeArrays are just a instance header followed by an array of values
789 self.header
.add_decl
("val* values[0];")
790 self.header
.add_decl
("\};")
793 self.provide_declaration
("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(int length, const struct type* type);")
794 v
.add_decl
("/* allocate {mtype} */")
795 v
.add_decl
("{mtype.ctype} NEW_{c_name}(int length, const struct type* type) \{")
796 var res
= v
.new_named_var
(mtype
, "self")
798 var mtype_elt
= mtype
.arguments
.first
799 v
.add
("{res} = nit_alloc(sizeof(struct instance_{c_name}) + length*sizeof({mtype_elt.ctype}));")
800 v
.add
("{res}->type = type;")
801 hardening_live_type
(v
, "type")
802 v
.require_declaration
("class_{c_name}")
803 v
.add
("{res}->class = &class_{c_name};")
804 v
.add
("return {res};")
810 self.provide_declaration
("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(const struct type* type);")
811 v
.add_decl
("/* allocate {mtype} */")
812 v
.add_decl
("{mtype.ctype} NEW_{c_name}(const struct type* type) \{")
814 v
.add_abort
("{mclass} is DEAD")
816 var res
= v
.new_named_var
(mtype
, "self")
818 v
.add
("{res} = nit_alloc(sizeof(struct instance) + {attrs.length}*sizeof(nitattribute_t));")
819 v
.add
("{res}->type = type;")
820 hardening_live_type
(v
, "type")
821 v
.require_declaration
("class_{c_name}")
822 v
.add
("{res}->class = &class_{c_name};")
823 self.generate_init_attr
(v
, res
, mtype
)
824 v
.add
("return {res};")
829 # Add a dynamic test to ensure that the type referenced by `t` is a live type
830 fun hardening_live_type
(v
: VISITOR, t
: String)
832 if not v
.compiler
.modelbuilder
.toolcontext
.opt_hardening
.value
then return
833 v
.add
("if({t} == NULL) \{")
834 v
.add_abort
("type null")
836 v
.add
("if({t}->table_size == 0) \{")
837 v
.add
("fprintf(stderr, \"Insantiation of a dead
type: %s\\n\
", {t}->name);")
838 v
.add_abort
("type dead")
842 redef fun new_visitor
do return new SeparateCompilerVisitor(self)
846 private var type_tables
: Map[MType, Array[nullable MType]] = new HashMap[MType, Array[nullable MType]]
847 private var resolution_tables
: Map[MClassType, Array[nullable MType]] = new HashMap[MClassType, Array[nullable MType]]
848 protected var method_tables
: Map[MClass, Array[nullable MPropDef]] = new HashMap[MClass, Array[nullable MPropDef]]
849 protected var attr_tables
: Map[MClass, Array[nullable MPropDef]] = new HashMap[MClass, Array[nullable MPropDef]]
851 redef fun display_stats
854 if self.modelbuilder
.toolcontext
.opt_tables_metrics
.value
then
861 print
"# size of subtyping tables"
862 print
"\ttotal \tholes"
865 for t
, table
in type_tables
do
866 total
+= table
.length
867 for e
in table
do if e
== null then holes
+= 1
869 print
"\t{total}\t{holes}"
871 print
"# size of resolution tables"
872 print
"\ttotal \tholes"
875 for t
, table
in resolution_tables
do
876 total
+= table
.length
877 for e
in table
do if e
== null then holes
+= 1
879 print
"\t{total}\t{holes}"
881 print
"# size of methods tables"
882 print
"\ttotal \tholes"
885 for t
, table
in method_tables
do
886 total
+= table
.length
887 for e
in table
do if e
== null then holes
+= 1
889 print
"\t{total}\t{holes}"
891 print
"# size of attributes tables"
892 print
"\ttotal \tholes"
895 for t
, table
in attr_tables
do
896 total
+= table
.length
897 for e
in table
do if e
== null then holes
+= 1
899 print
"\t{total}\t{holes}"
902 redef fun compile_nitni_structs
904 self.header
.add_decl
("struct nitni_instance \{struct instance *value;\};")
907 redef fun finalize_ffi_for_module
(nmodule
)
909 var old_module
= self.mainmodule
910 self.mainmodule
= nmodule
.mmodule
.as(not null)
912 self.mainmodule
= old_module
916 # A visitor on the AST of property definition that generate the C code of a separate compilation process.
917 class SeparateCompilerVisitor
918 super AbstractCompilerVisitor
920 redef type COMPILER: SeparateCompiler
922 redef fun adapt_signature
(m
, args
)
924 var msignature
= m
.msignature
.resolve_for
(m
.mclassdef
.bound_mtype
, m
.mclassdef
.bound_mtype
, m
.mclassdef
.mmodule
, true)
925 var recv
= args
.first
926 if recv
.mtype
.ctype
!= m
.mclassdef
.mclass
.mclass_type
.ctype
then
927 args
.first
= self.autobox
(args
.first
, m
.mclassdef
.mclass
.mclass_type
)
929 for i
in [0..msignature
.arity
[ do
930 var t
= msignature
.mparameters
[i
].mtype
931 if i
== msignature
.vararg_rank
then
934 args
[i
+1] = self.autobox
(args
[i
+1], t
)
938 redef fun autobox
(value
, mtype
)
940 if value
.mtype
== mtype
then
942 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
944 else if value
.mtype
.ctype
== "val*" then
945 return self.new_expr
("((struct instance_{mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
946 else if mtype
.ctype
== "val*" then
947 var valtype
= value
.mtype
.as(MClassType)
948 var res
= self.new_var
(mtype
)
949 if compiler
.runtime_type_analysis
!= null and not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
950 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
951 self.add
("printf(\"Dead code executed
!\\n\
"); show_backtrace(1);")
954 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
956 else if value
.mtype
.cname_blind
== "void*" and mtype
.cname_blind
== "void*" then
959 # Bad things will appen!
960 var res
= self.new_var
(mtype
)
961 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
962 self.add
("printf(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); show_backtrace(1);")
967 # Return a C expression returning the runtime type structure of the value
968 # The point of the method is to works also with primitives types.
969 fun type_info
(value
: RuntimeVariable): String
971 if value
.mtype
.ctype
== "val*" then
972 return "{value}->type"
974 self.require_declaration
("type_{value.mtype.c_name}")
975 return "(&type_{value.mtype.c_name})"
979 redef fun send
(mmethod
, arguments
)
981 self.varargize
(mmethod
.intro
, mmethod
.intro
.msignature
.as(not null), arguments
)
983 if arguments
.first
.mcasttype
.ctype
!= "val*" then
984 # In order to shortcut the primitive, we need to find the most specific method
985 # Howverr, because of performance (no flattening), we always work on the realmainmodule
986 var m
= self.compiler
.mainmodule
987 self.compiler
.mainmodule
= self.compiler
.realmainmodule
988 var res
= self.monomorphic_send
(mmethod
, arguments
.first
.mcasttype
, arguments
)
989 self.compiler
.mainmodule
= m
993 return table_send
(mmethod
, arguments
, mmethod
.const_color
)
996 private fun table_send
(mmethod
: MMethod, arguments
: Array[RuntimeVariable], const_color
: String): nullable RuntimeVariable
998 assert arguments
.length
== mmethod
.intro
.msignature
.arity
+ 1 else debug
("Invalid arity for {mmethod}. {arguments.length} arguments given.")
1000 var res
: nullable RuntimeVariable
1001 var msignature
= mmethod
.intro
.msignature
.resolve_for
(mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.mmodule
, true)
1002 var ret
= msignature
.return_mtype
1003 if mmethod
.is_new
then
1004 ret
= arguments
.first
.mtype
1005 res
= self.new_var
(ret
)
1006 else if ret
== null then
1009 res
= self.new_var
(ret
)
1015 var recv
= arguments
.first
1018 for i
in [0..msignature
.arity
[ do
1019 var a
= arguments
[i
+1]
1020 var t
= msignature
.mparameters
[i
].mtype
1021 if i
== msignature
.vararg_rank
then
1022 t
= arguments
[i
+1].mcasttype
1024 s
.append
(", {t.ctype}")
1025 a
= self.autobox
(a
, t
)
1029 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
or mmethod
.name
== "==" or mmethod
.name
== "!="
1030 var maybenull
= recv
.mcasttype
isa MNullableType and consider_null
1032 self.add
("if ({recv} == NULL) \{")
1033 if mmethod
.name
== "==" then
1035 var arg
= arguments
[1]
1036 if arg
.mcasttype
isa MNullableType then
1037 self.add
("{res} = ({arg} == NULL);")
1038 else if arg
.mcasttype
isa MNullType then
1039 self.add
("{res} = 1; /* is null */")
1041 self.add
("{res} = 0; /* {arg.inspect} cannot be null */")
1043 else if mmethod
.name
== "!=" then
1045 var arg
= arguments
[1]
1046 if arg
.mcasttype
isa MNullableType then
1047 self.add
("{res} = ({arg} != NULL);")
1048 else if arg
.mcasttype
isa MNullType then
1049 self.add
("{res} = 0; /* is null */")
1051 self.add
("{res} = 1; /* {arg.inspect} cannot be null */")
1054 self.add_abort
("Receiver is null")
1056 self.add
("\} else \{")
1058 if not self.compiler
.modelbuilder
.toolcontext
.opt_no_shortcut_equate
.value
and (mmethod
.name
== "==" or mmethod
.name
== "!=") then
1060 # Recv is not null, thus is arg is, it is easy to conclude (and respect the invariants)
1061 var arg
= arguments
[1]
1062 if arg
.mcasttype
isa MNullType then
1063 if mmethod
.name
== "==" then
1064 self.add
("{res} = 0; /* arg is null but recv is not */")
1066 self.add
("{res} = 1; /* arg is null and recv is not */")
1076 if ret
== null then r
= "void" else r
= ret
.ctype
1077 self.require_declaration
(const_color
)
1078 var call
= "(({r} (*)({s}))({arguments.first}->class->vft[{const_color}]))({ss}) /* {mmethod} on {arguments.first.inspect}*/"
1081 self.add
("{res} = {call};")
1093 redef fun call
(mmethoddef
, recvtype
, arguments
)
1095 assert arguments
.length
== mmethoddef
.msignature
.arity
+ 1 else debug
("Invalid arity for {mmethoddef}. {arguments.length} arguments given.")
1097 var res
: nullable RuntimeVariable
1098 var ret
= mmethoddef
.msignature
.return_mtype
1099 if mmethoddef
.mproperty
.is_new
then
1100 ret
= arguments
.first
.mtype
1101 res
= self.new_var
(ret
)
1102 else if ret
== null then
1105 ret
= ret
.resolve_for
(mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.mmodule
, true)
1106 res
= self.new_var
(ret
)
1109 if self.compiler
.modelbuilder
.mpropdef2npropdef
.has_key
(mmethoddef
) and
1110 self.compiler
.modelbuilder
.mpropdef2npropdef
[mmethoddef
] isa AInternMethPropdef and
1111 not compiler
.modelbuilder
.toolcontext
.opt_no_inline_intern
.value
then
1112 var frame
= new Frame(self, mmethoddef
, recvtype
, arguments
)
1113 frame
.returnlabel
= self.get_name
("RET_LABEL")
1114 frame
.returnvar
= res
1115 var old_frame
= self.frame
1117 self.add
("\{ /* Inline {mmethoddef} ({arguments.join(",")}) */")
1118 mmethoddef
.compile_inside_to_c
(self, arguments
)
1119 self.add
("{frame.returnlabel.as(not null)}:(void)0;")
1121 self.frame
= old_frame
1126 self.adapt_signature
(mmethoddef
, arguments
)
1128 self.require_declaration
(mmethoddef
.c_name
)
1130 self.add
("{mmethoddef.c_name}({arguments.join(", ")});")
1133 self.add
("{res} = {mmethoddef.c_name}({arguments.join(", ")});")
1139 redef fun supercall
(m
: MMethodDef, recvtype
: MClassType, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
1141 if arguments
.first
.mcasttype
.ctype
!= "val*" then
1142 # In order to shortcut the primitive, we need to find the most specific method
1143 # However, because of performance (no flattening), we always work on the realmainmodule
1144 var main
= self.compiler
.mainmodule
1145 self.compiler
.mainmodule
= self.compiler
.realmainmodule
1146 var res
= self.monomorphic_super_send
(m
, recvtype
, arguments
)
1147 self.compiler
.mainmodule
= main
1150 return table_send
(m
.mproperty
, arguments
, m
.const_color
)
1153 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
1155 # A vararg must be stored into an new array
1156 # The trick is that the dymaic type of the array may depends on the receiver
1157 # of the method (ie recv) if the static type is unresolved
1158 # This is more complex than usual because the unresolved type must not be resolved
1159 # with the current receiver (ie self).
1160 # Therefore to isolate the resolution from self, a local Frame is created.
1161 # One can see this implementation as an inlined method of the receiver whose only
1162 # job is to allocate the array
1163 var old_frame
= self.frame
1164 var frame
= new Frame(self, mpropdef
, mpropdef
.mclassdef
.bound_mtype
, [recv
])
1166 #print "required Array[{elttype}] for recv {recv.inspect}. bound=Array[{self.resolve_for(elttype, recv)}]. selfvar={frame.arguments.first.inspect}"
1167 var res
= self.array_instance
(varargs
, elttype
)
1168 self.frame
= old_frame
1172 redef fun isset_attribute
(a
, recv
)
1174 self.check_recv_notnull
(recv
)
1175 var res
= self.new_var
(bool_type
)
1177 # What is the declared type of the attribute?
1178 var mtype
= a
.intro
.static_mtype
.as(not null)
1179 var intromclassdef
= a
.intro
.mclassdef
1180 mtype
= mtype
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1182 if mtype
isa MNullableType then
1183 self.add
("{res} = 1; /* easy isset: {a} on {recv.inspect} */")
1187 self.require_declaration
(a
.const_color
)
1188 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1189 self.add
("{res} = {recv}->attrs[{a.const_color}] != NULL; /* {a} on {recv.inspect}*/")
1192 if mtype
.ctype
== "val*" then
1193 self.add
("{res} = {recv}->attrs[{a.const_color}].val != NULL; /* {a} on {recv.inspect} */")
1195 self.add
("{res} = 1; /* NOT YET IMPLEMENTED: isset of primitives: {a} on {recv.inspect} */")
1201 redef fun read_attribute
(a
, recv
)
1203 self.check_recv_notnull
(recv
)
1205 # What is the declared type of the attribute?
1206 var ret
= a
.intro
.static_mtype
.as(not null)
1207 var intromclassdef
= a
.intro
.mclassdef
1208 ret
= ret
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1210 self.require_declaration
(a
.const_color
)
1211 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1212 # Get the attribute or a box (ie. always a val*)
1213 var cret
= self.object_type
.as_nullable
1214 var res
= self.new_var
(cret
)
1217 self.add
("{res} = {recv}->attrs[{a.const_color}]; /* {a} on {recv.inspect} */")
1219 # Check for Uninitialized attribute
1220 if not ret
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then
1221 self.add
("if ({res} == NULL) \{")
1222 self.add_abort
("Uninitialized attribute {a.name}")
1226 # Return the attribute or its unboxed version
1227 # Note: it is mandatory since we reuse the box on write, we do not whant that the box escapes
1228 return self.autobox
(res
, ret
)
1230 var res
= self.new_var
(ret
)
1231 self.add
("{res} = {recv}->attrs[{a.const_color}].{ret.ctypename}; /* {a} on {recv.inspect} */")
1233 # Check for Uninitialized attribute
1234 if ret
.ctype
== "val*" and not ret
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then
1235 self.add
("if ({res} == NULL) \{")
1236 self.add_abort
("Uninitialized attribute {a.name}")
1244 redef fun write_attribute
(a
, recv
, value
)
1246 self.check_recv_notnull
(recv
)
1248 # What is the declared type of the attribute?
1249 var mtype
= a
.intro
.static_mtype
.as(not null)
1250 var intromclassdef
= a
.intro
.mclassdef
1251 mtype
= mtype
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1253 # Adapt the value to the declared type
1254 value
= self.autobox
(value
, mtype
)
1256 self.require_declaration
(a
.const_color
)
1257 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1258 var attr
= "{recv}->attrs[{a.const_color}]"
1259 if mtype
.ctype
!= "val*" then
1260 assert mtype
isa MClassType
1261 # The attribute is primitive, thus we store it in a box
1262 # The trick is to create the box the first time then resuse the box
1263 self.add
("if ({attr} != NULL) \{")
1264 self.add
("((struct instance_{mtype.c_name}*){attr})->value = {value}; /* {a} on {recv.inspect} */")
1265 self.add
("\} else \{")
1266 value
= self.autobox
(value
, self.object_type
.as_nullable
)
1267 self.add
("{attr} = {value}; /* {a} on {recv.inspect} */")
1270 # The attribute is not primitive, thus store it direclty
1271 self.add
("{attr} = {value}; /* {a} on {recv.inspect} */")
1274 self.add
("{recv}->attrs[{a.const_color}].{mtype.ctypename} = {value}; /* {a} on {recv.inspect} */")
1278 # Check that mtype is a live open type
1279 fun hardening_live_open_type
(mtype
: MType)
1281 if not compiler
.modelbuilder
.toolcontext
.opt_hardening
.value
then return
1282 self.require_declaration
(mtype
.const_color
)
1283 var col
= mtype
.const_color
1284 self.add
("if({col} == -1) \{")
1285 self.add
("fprintf(stderr, \"Resolution of a dead open
type: %s\\n\
", \"{mtype.to_s.escape_to_c}\
");")
1286 self.add_abort
("open type dead")
1290 # Check that mtype it a pointer to a live cast type
1291 fun hardening_cast_type
(t
: String)
1293 if not compiler
.modelbuilder
.toolcontext
.opt_hardening
.value
then return
1294 add
("if({t} == NULL) \{")
1295 add_abort
("cast type null")
1297 add
("if({t}->id == -1 || {t}->color == -1) \{")
1298 add
("fprintf(stderr, \"Try to cast on a dead cast
type: %s\\n\
", {t}->name);")
1299 add_abort
("cast type dead")
1303 redef fun init_instance
(mtype
)
1305 self.require_declaration
("NEW_{mtype.mclass.c_name}")
1306 var compiler
= self.compiler
1307 if mtype
isa MGenericType and mtype
.need_anchor
then
1308 hardening_live_open_type
(mtype
)
1309 link_unresolved_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1310 var recv
= self.frame
.arguments
.first
1311 var recv_type_info
= self.type_info
(recv
)
1312 self.require_declaration
(mtype
.const_color
)
1313 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1314 return self.new_expr
("NEW_{mtype.mclass.c_name}({recv_type_info}->resolution_table->types[HASH({recv_type_info}->resolution_table->mask, {mtype.const_color})])", mtype
)
1316 return self.new_expr
("NEW_{mtype.mclass.c_name}({recv_type_info}->resolution_table->types[{mtype.const_color}])", mtype
)
1319 compiler
.undead_types
.add
(mtype
)
1320 self.require_declaration
("type_{mtype.c_name}")
1321 return self.new_expr
("NEW_{mtype.mclass.c_name}(&type_{mtype.c_name})", mtype
)
1324 redef fun type_test
(value
, mtype
, tag
)
1326 self.add
("/* {value.inspect} isa {mtype} */")
1327 var compiler
= self.compiler
1329 var recv
= self.frame
.arguments
.first
1330 var recv_type_info
= self.type_info
(recv
)
1332 var res
= self.new_var
(bool_type
)
1334 var cltype
= self.get_name
("cltype")
1335 self.add_decl
("int {cltype};")
1336 var idtype
= self.get_name
("idtype")
1337 self.add_decl
("int {idtype};")
1339 var maybe_null
= self.maybe_null
(value
)
1340 var accept_null
= "0"
1342 if ntype
isa MNullableType then
1347 if value
.mcasttype
.is_subtype
(self.frame
.mpropdef
.mclassdef
.mmodule
, self.frame
.mpropdef
.mclassdef
.bound_mtype
, mtype
) then
1348 self.add
("{res} = 1; /* easy {value.inspect} isa {mtype}*/")
1349 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1350 self.compiler
.count_type_test_skipped
[tag
] += 1
1351 self.add
("count_type_test_skipped_{tag}++;")
1356 if ntype
.need_anchor
then
1357 var type_struct
= self.get_name
("type_struct")
1358 self.add_decl
("const struct type* {type_struct};")
1360 # Either with resolution_table with a direct resolution
1361 hardening_live_open_type
(mtype
)
1362 link_unresolved_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1363 self.require_declaration
(mtype
.const_color
)
1364 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1365 self.add
("{type_struct} = {recv_type_info}->resolution_table->types[HASH({recv_type_info}->resolution_table->mask, {mtype.const_color})];")
1367 self.add
("{type_struct} = {recv_type_info}->resolution_table->types[{mtype.const_color}];")
1369 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1370 self.compiler
.count_type_test_unresolved
[tag
] += 1
1371 self.add
("count_type_test_unresolved_{tag}++;")
1373 hardening_cast_type
(type_struct
)
1374 self.add
("{cltype} = {type_struct}->color;")
1375 self.add
("{idtype} = {type_struct}->id;")
1376 if maybe_null
and accept_null
== "0" then
1377 var is_nullable
= self.get_name
("is_nullable")
1378 self.add_decl
("short int {is_nullable};")
1379 self.add
("{is_nullable} = {type_struct}->is_nullable;")
1380 accept_null
= is_nullable
.to_s
1382 else if ntype
isa MClassType then
1383 compiler
.undead_types
.add
(mtype
)
1384 self.require_declaration
("type_{mtype.c_name}")
1385 hardening_cast_type
("(&type_{mtype.c_name})")
1386 self.add
("{cltype} = type_{mtype.c_name}.color;")
1387 self.add
("{idtype} = type_{mtype.c_name}.id;")
1388 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1389 self.compiler
.count_type_test_resolved
[tag
] += 1
1390 self.add
("count_type_test_resolved_{tag}++;")
1393 self.add
("printf(\"NOT YET IMPLEMENTED: type_test
(%s
, {mtype}).\\n\
", \"{value.inspect}\
"); show_backtrace(1);")
1396 # check color is in table
1398 self.add
("if({value} == NULL) \{")
1399 self.add
("{res} = {accept_null};")
1400 self.add
("\} else \{")
1402 var value_type_info
= self.type_info
(value
)
1403 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1404 self.add
("{cltype} = HASH({value_type_info}->color, {idtype});")
1406 self.add
("if({cltype} >= {value_type_info}->table_size) \{")
1407 self.add
("{res} = 0;")
1408 self.add
("\} else \{")
1409 self.add
("{res} = {value_type_info}->type_table[{cltype}] == {idtype};")
1418 redef fun is_same_type_test
(value1
, value2
)
1420 var res
= self.new_var
(bool_type
)
1421 # Swap values to be symetric
1422 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1427 if value1
.mtype
.ctype
!= "val*" then
1428 if value2
.mtype
== value1
.mtype
then
1429 self.add
("{res} = 1; /* is_same_type_test: compatible types {value1.mtype} vs. {value2.mtype} */")
1430 else if value2
.mtype
.ctype
!= "val*" then
1431 self.add
("{res} = 0; /* is_same_type_test: incompatible types {value1.mtype} vs. {value2.mtype}*/")
1433 var mtype1
= value1
.mtype
.as(MClassType)
1434 self.require_declaration
("class_{mtype1.c_name}")
1435 self.add
("{res} = ({value2} != NULL) && ({value2}->class == &class_{mtype1.c_name}); /* is_same_type_test */")
1438 self.add
("{res} = ({value1} == {value2}) || ({value1} != NULL && {value2} != NULL && {value1}->class == {value2}->class); /* is_same_type_test */")
1443 redef fun class_name_string
(value
)
1445 var res
= self.get_name
("var_class_name")
1446 self.add_decl
("const char* {res};")
1447 if value
.mtype
.ctype
== "val*" then
1448 self.add
"{res} = {value} == NULL ? \"null\
" : {value}->type->name;"
1449 else if value
.mtype
isa MClassType and value
.mtype
.as(MClassType).mclass
.kind
== extern_kind
then
1450 self.add
"{res} = \"{value.mtype.as(MClassType).mclass}\
";"
1452 self.require_declaration
("type_{value.mtype.c_name}")
1453 self.add
"{res} = type_{value.mtype.c_name}.name;"
1458 redef fun equal_test
(value1
, value2
)
1460 var res
= self.new_var
(bool_type
)
1461 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1466 if value1
.mtype
.ctype
!= "val*" then
1467 if value2
.mtype
== value1
.mtype
then
1468 self.add
("{res} = {value1} == {value2};")
1469 else if value2
.mtype
.ctype
!= "val*" then
1470 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
1472 var mtype1
= value1
.mtype
.as(MClassType)
1473 self.require_declaration
("class_{mtype1.c_name}")
1474 self.add
("{res} = ({value2} != NULL) && ({value2}->class == &class_{mtype1.c_name});")
1475 self.add
("if ({res}) \{")
1476 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
1481 var maybe_null
= true
1482 var test
= new Array[String]
1483 var t1
= value1
.mcasttype
1484 if t1
isa MNullableType then
1485 test
.add
("{value1} != NULL")
1490 var t2
= value2
.mcasttype
1491 if t2
isa MNullableType then
1492 test
.add
("{value2} != NULL")
1498 var incompatible
= false
1500 if t1
.ctype
!= "val*" then
1503 # No need to compare class
1504 else if t2
.ctype
!= "val*" then
1506 else if can_be_primitive
(value2
) then
1507 test
.add
("{value1}->class == {value2}->class")
1511 else if t2
.ctype
!= "val*" then
1513 if can_be_primitive
(value1
) then
1514 test
.add
("{value1}->class == {value2}->class")
1522 if incompatible
then
1524 self.add
("{res} = {value1} == {value2}; /* incompatible types {t1} vs. {t2}; but may be NULL*/")
1527 self.add
("{res} = 0; /* incompatible types {t1} vs. {t2}; cannot be NULL */")
1531 if primitive
!= null then
1532 test
.add
("((struct instance_{primitive.c_name}*){value1})->value == ((struct instance_{primitive.c_name}*){value2})->value")
1533 else if can_be_primitive
(value1
) and can_be_primitive
(value2
) then
1534 test
.add
("{value1}->class == {value2}->class")
1535 var s
= new Array[String]
1536 for t
, v
in self.compiler
.box_kinds
do
1537 s
.add
"({value1}->class->box_kind == {v} && ((struct instance_{t.c_name}*){value1})->value == ((struct instance_{t.c_name}*){value2})->value)"
1539 test
.add
("({s.join(" || ")})")
1541 self.add
("{res} = {value1} == {value2};")
1544 self.add
("{res} = {value1} == {value2} || ({test.join(" && ")});")
1548 fun can_be_primitive
(value
: RuntimeVariable): Bool
1550 var t
= value
.mcasttype
1551 if t
isa MNullableType then t
= t
.mtype
1552 if not t
isa MClassType then return false
1553 var k
= t
.mclass
.kind
1554 return k
== interface_kind
or t
.ctype
!= "val*"
1557 fun maybe_null
(value
: RuntimeVariable): Bool
1559 var t
= value
.mcasttype
1560 return t
isa MNullableType or t
isa MNullType
1563 redef fun array_instance
(array
, elttype
)
1565 var nclass
= self.get_class
("NativeArray")
1566 var arrayclass
= self.get_class
("Array")
1567 var arraytype
= arrayclass
.get_mtype
([elttype
])
1568 var res
= self.init_instance
(arraytype
)
1569 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
1570 var length
= self.int_instance
(array
.length
)
1571 var nat
= native_array_instance
(elttype
, length
)
1572 for i
in [0..array
.length
[ do
1573 var r
= self.autobox
(array
[i
], self.object_type
)
1574 self.add
("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
1576 self.send
(self.get_property
("with_native", arrayclass
.intro
.bound_mtype
), [res
, nat
, length
])
1581 fun native_array_instance
(elttype
: MType, length
: RuntimeVariable): RuntimeVariable
1583 var mtype
= self.get_class
("NativeArray").get_mtype
([elttype
])
1584 self.require_declaration
("NEW_{mtype.mclass.c_name}")
1585 assert mtype
isa MGenericType
1586 var compiler
= self.compiler
1587 if mtype
.need_anchor
then
1588 hardening_live_open_type
(mtype
)
1589 link_unresolved_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1590 var recv
= self.frame
.arguments
.first
1591 var recv_type_info
= self.type_info
(recv
)
1592 self.require_declaration
(mtype
.const_color
)
1593 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1594 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, {recv_type_info}->resolution_table->types[HASH({recv_type_info}->resolution_table->mask, {mtype.const_color})])", mtype
)
1596 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, {recv_type_info}->resolution_table->types[{mtype.const_color}])", mtype
)
1599 compiler
.undead_types
.add
(mtype
)
1600 self.require_declaration
("type_{mtype.c_name}")
1601 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, &type_{mtype.c_name})", mtype
)
1604 redef fun native_array_def
(pname
, ret_type
, arguments
)
1606 var elttype
= arguments
.first
.mtype
1607 var nclass
= self.get_class
("NativeArray")
1608 var recv
= "((struct instance_{nclass.c_name}*){arguments[0]})->values"
1609 if pname
== "[]" then
1610 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
1612 else if pname
== "[]=" then
1613 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
1615 else if pname
== "copy_to" then
1616 var recv1
= "((struct instance_{nclass.c_name}*){arguments[1]})->values"
1617 self.add
("memcpy({recv1}, {recv}, {arguments[2]}*sizeof({elttype.ctype}));")
1622 redef fun calloc_array
(ret_type
, arguments
)
1624 var mclass
= self.get_class
("ArrayCapable")
1625 var ft
= mclass
.mclass_type
.arguments
.first
.as(MParameterType)
1626 var res
= self.native_array_instance
(ft
, arguments
[1])
1630 fun link_unresolved_type
(mclassdef
: MClassDef, mtype
: MType) do
1631 assert mtype
.need_anchor
1632 var compiler
= self.compiler
1633 if not compiler
.live_unresolved_types
.has_key
(self.frame
.mpropdef
.mclassdef
) then
1634 compiler
.live_unresolved_types
[self.frame
.mpropdef
.mclassdef
] = new HashSet[MType]
1636 compiler
.live_unresolved_types
[self.frame
.mpropdef
.mclassdef
].add
(mtype
)
1640 redef class MMethodDef
1641 fun separate_runtime_function
: AbstractRuntimeFunction
1643 var res
= self.separate_runtime_function_cache
1645 res
= new SeparateRuntimeFunction(self)
1646 self.separate_runtime_function_cache
= res
1650 private var separate_runtime_function_cache
: nullable SeparateRuntimeFunction
1652 fun virtual_runtime_function
: AbstractRuntimeFunction
1654 var res
= self.virtual_runtime_function_cache
1656 res
= new VirtualRuntimeFunction(self)
1657 self.virtual_runtime_function_cache
= res
1661 private var virtual_runtime_function_cache
: nullable VirtualRuntimeFunction
1664 # The C function associated to a methoddef separately compiled
1665 class SeparateRuntimeFunction
1666 super AbstractRuntimeFunction
1668 redef fun build_c_name
: String do return "{mmethoddef.c_name}"
1670 redef fun to_s
do return self.mmethoddef
.to_s
1672 redef fun compile_to_c
(compiler
)
1674 var mmethoddef
= self.mmethoddef
1676 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
1677 var v
= compiler
.new_visitor
1678 var selfvar
= new RuntimeVariable("self", recv
, recv
)
1679 var arguments
= new Array[RuntimeVariable]
1680 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
1683 var msignature
= mmethoddef
.msignature
.resolve_for
(mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.mmodule
, true)
1685 var sig
= new Buffer
1686 var comment
= new Buffer
1687 var ret
= msignature
.return_mtype
1689 sig
.append
("{ret.ctype} ")
1690 else if mmethoddef
.mproperty
.is_new
then
1692 sig
.append
("{ret.ctype} ")
1696 sig
.append
(self.c_name
)
1697 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
1698 comment
.append
("({selfvar}: {selfvar.mtype}")
1699 arguments
.add
(selfvar
)
1700 for i
in [0..msignature
.arity
[ do
1701 var mtype
= msignature
.mparameters
[i
].mtype
1702 if i
== msignature
.vararg_rank
then
1703 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
1705 comment
.append
(", {mtype}")
1706 sig
.append
(", {mtype.ctype} p{i}")
1707 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
1708 arguments
.add
(argvar
)
1713 comment
.append
(": {ret}")
1715 compiler
.provide_declaration
(self.c_name
, "{sig};")
1717 v
.add_decl
("/* method {self} for {comment} */")
1718 v
.add_decl
("{sig} \{")
1720 frame
.returnvar
= v
.new_var
(ret
)
1722 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1724 if recv
!= arguments
.first
.mtype
then
1725 #print "{self} {recv} {arguments.first}"
1727 mmethoddef
.compile_inside_to_c
(v
, arguments
)
1729 v
.add
("{frame.returnlabel.as(not null)}:;")
1731 v
.add
("return {frame.returnvar.as(not null)};")
1734 if not self.c_name
.has_substring
("VIRTUAL", 0) then compiler
.names
[self.c_name
] = "{mmethoddef.mclassdef.mmodule.name}::{mmethoddef.mclassdef.mclass.name}::{mmethoddef.mproperty.name} ({mmethoddef.location.file.filename}:{mmethoddef.location.line_start})"
1738 # The C function associated to a methoddef on a primitive type, stored into a VFT of a class
1739 # The first parameter (the reciever) is always typed by val* in order to accept an object value
1740 class VirtualRuntimeFunction
1741 super AbstractRuntimeFunction
1743 redef fun build_c_name
: String do return "VIRTUAL_{mmethoddef.c_name}"
1745 redef fun to_s
do return self.mmethoddef
.to_s
1747 redef fun compile_to_c
(compiler
)
1749 var mmethoddef
= self.mmethoddef
1751 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
1752 var v
= compiler
.new_visitor
1753 var selfvar
= new RuntimeVariable("self", v
.object_type
, recv
)
1754 var arguments
= new Array[RuntimeVariable]
1755 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
1758 var sig
= new Buffer
1759 var comment
= new Buffer
1761 # Because the function is virtual, the signature must match the one of the original class
1762 var intromclassdef
= self.mmethoddef
.mproperty
.intro
.mclassdef
1763 var msignature
= mmethoddef
.mproperty
.intro
.msignature
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1764 var ret
= msignature
.return_mtype
1766 sig
.append
("{ret.ctype} ")
1767 else if mmethoddef
.mproperty
.is_new
then
1769 sig
.append
("{ret.ctype} ")
1773 sig
.append
(self.c_name
)
1774 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
1775 comment
.append
("({selfvar}: {selfvar.mtype}")
1776 arguments
.add
(selfvar
)
1777 for i
in [0..msignature
.arity
[ do
1778 var mtype
= msignature
.mparameters
[i
].mtype
1779 if i
== msignature
.vararg_rank
then
1780 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
1782 comment
.append
(", {mtype}")
1783 sig
.append
(", {mtype.ctype} p{i}")
1784 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
1785 arguments
.add
(argvar
)
1790 comment
.append
(": {ret}")
1792 compiler
.provide_declaration
(self.c_name
, "{sig};")
1794 v
.add_decl
("/* method {self} for {comment} */")
1795 v
.add_decl
("{sig} \{")
1797 frame
.returnvar
= v
.new_var
(ret
)
1799 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1801 var subret
= v
.call
(mmethoddef
, recv
, arguments
)
1803 assert subret
!= null
1804 v
.assign
(frame
.returnvar
.as(not null), subret
)
1807 v
.add
("{frame.returnlabel.as(not null)}:;")
1809 v
.add
("return {frame.returnvar.as(not null)};")
1812 if not self.c_name
.has_substring
("VIRTUAL", 0) then compiler
.names
[self.c_name
] = "{mmethoddef.mclassdef.mmodule.name}::{mmethoddef.mclassdef.mclass.name}::{mmethoddef.mproperty.name} ({mmethoddef.location.file.filename}--{mmethoddef.location.line_start})"
1816 redef fun call
(v
, arguments
) do abort
1820 fun const_color
: String do return "COLOR_{c_name}"
1823 redef class MProperty
1824 fun const_color
: String do return "COLOR_{c_name}"
1827 redef class MPropDef
1828 fun const_color
: String do return "COLOR_{c_name}"