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
22 # Add separate compiler specific options
23 redef class ToolContext
25 var opt_separate
: OptionBool = new OptionBool("Use separate compilation", "--separate")
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")
41 var opt_tables_metrics
: OptionBool = new OptionBool("Enable static size measuring of tables used for vft, typing and resolution", "--tables-metrics")
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_tables_metrics
)
58 redef class ModelBuilder
59 fun run_separate_compiler
(mainmodule
: MModule, runtime_type_analysis
: nullable RapidTypeAnalysis)
62 self.toolcontext
.info
("*** GENERATING C ***", 1)
64 var compiler
= new SeparateCompiler(mainmodule
, self, runtime_type_analysis
)
65 compiler
.compile_header
67 # compile class structures
68 self.toolcontext
.info
("Property coloring", 2)
69 compiler
.new_file
("{mainmodule.name}.classes")
70 compiler
.do_property_coloring
71 for m
in mainmodule
.in_importation
.greaters
do
72 for mclass
in m
.intro_mclasses
do
73 if mclass
.kind
== abstract_kind
or mclass
.kind
== interface_kind
then continue
74 compiler
.compile_class_to_c
(mclass
)
78 # The main function of the C
79 compiler
.new_file
("{mainmodule.name}.main")
80 compiler
.compile_main_function
83 for m
in mainmodule
.in_importation
.greaters
do
84 self.toolcontext
.info
("Generate C for module {m}", 2)
85 compiler
.new_file
("{m.name}.sep")
86 compiler
.compile_module_to_c
(m
)
89 # compile live & cast type structures
90 self.toolcontext
.info
("Type coloring", 2)
91 compiler
.new_file
("{mainmodule.name}.types")
92 var mtypes
= compiler
.do_type_coloring
94 compiler
.compile_type_to_c
(t
)
96 # compile remaining types structures (useless but needed for the symbol resolution at link-time)
97 for t
in compiler
.undead_types
do
98 if mtypes
.has
(t
) then continue
99 compiler
.compile_type_to_c
(t
)
102 compiler
.display_stats
105 self.toolcontext
.info
("*** END GENERATING C: {time1-time0} ***", 2)
106 write_and_make
(compiler
)
110 # Singleton that store the knowledge about the separate compilation process
111 class SeparateCompiler
112 super AbstractCompiler
114 redef type VISITOR: SeparateCompilerVisitor
116 # The result of the RTA (used to know live types and methods)
117 var runtime_type_analysis
: nullable RapidTypeAnalysis
119 private var undead_types
: Set[MType] = new HashSet[MType]
120 private var live_unresolved_types
: Map[MClassDef, Set[MType]] = new HashMap[MClassDef, HashSet[MType]]
122 private var type_layout
: nullable Layout[MType]
123 private var resolution_layout
: nullable Layout[MType]
124 protected var method_layout
: nullable Layout[PropertyLayoutElement]
125 protected var attr_layout
: nullable Layout[MAttribute]
127 init(mainmodule
: MModule, mmbuilder
: ModelBuilder, runtime_type_analysis
: nullable RapidTypeAnalysis) do
128 super(mainmodule
, mmbuilder
)
129 var file
= new_file
("nit.common")
130 self.header
= new CodeWriter(file
)
131 self.runtime_type_analysis
= runtime_type_analysis
132 self.compile_box_kinds
135 redef fun compile_header_structs
do
136 self.header
.add_decl
("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
137 self.compile_header_attribute_structs
138 self.header
.add_decl
("struct class \{ int box_kind; nitmethod_t vft[]; \}; /* general C type representing a Nit class. */")
140 # With resolution_table_table, all live type resolution are stored in a big table: resolution_table
141 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. */")
142 self.header
.add_decl
("struct instance \{ const struct type *type; const struct class *class; nitattribute_t attrs[]; \}; /* general C type representing a Nit instance. */")
144 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
145 self.header
.add_decl
("struct types \{ int mask; const struct type *types[]; \}; /* a list types (used for vts, fts and unresolved lists). */")
147 self.header
.add_decl
("struct types \{ int dummy; const struct type *types[]; \}; /* a list types (used for vts, fts and unresolved lists). */")
150 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
151 self.header
.add_decl
("#define HASH(mask, id) ((mask)%(id))")
152 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
153 self.header
.add_decl
("#define HASH(mask, id) ((mask)&(id))")
156 self.header
.add_decl
("typedef struct instance val; /* general C type representing a Nit instance. */")
159 fun compile_header_attribute_structs
161 if modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
162 self.header
.add_decl
("typedef void* nitattribute_t; /* general C type representing a Nit attribute. */")
164 self.header
.add_decl
("typedef union \{")
165 self.header
.add_decl
("void* val;")
166 for c
, v
in self.box_kinds
do
167 var t
= c
.mclass_type
168 self.header
.add_decl
("{t.ctype} {t.ctypename};")
170 self.header
.add_decl
("\} nitattribute_t; /* general C type representing a Nit attribute. */")
174 fun compile_box_kinds
176 # Collect all bas box class
177 # FIXME: this is not completely fine with a separate compilation scheme
178 for classname
in ["Int", "Bool", "Char", "Float", "NativeString", "Pointer"] do
179 var classes
= self.mainmodule
.model
.get_mclasses_by_name
(classname
)
180 if classes
== null then continue
181 assert classes
.length
== 1 else print classes
.join
(", ")
182 self.box_kinds
[classes
.first
] = self.box_kinds
.length
+ 1
186 var box_kinds
= new HashMap[MClass, Int]
188 fun box_kind_of
(mclass
: MClass): Int
190 if mclass
.mclass_type
.ctype
== "val*" then
192 else if mclass
.kind
== extern_kind
then
193 return self.box_kinds
[self.mainmodule
.get_primitive_class
("Pointer")]
195 return self.box_kinds
[mclass
]
200 fun compile_color_consts
(colors
: Map[Object, Int]) do
202 for m
, c
in colors
do
203 compile_color_const
(v
, m
, c
)
207 fun compile_color_const
(v
: SeparateCompilerVisitor, m
: Object, color
: Int) do
208 if color_consts_done
.has
(m
) then return
209 if m
isa MProperty then
210 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
211 self.provide_declaration
(m
.const_color
, "#define {m.const_color} {color}")
213 self.provide_declaration
(m
.const_color
, "extern const int {m.const_color};")
214 v
.add
("const int {m.const_color} = {color};")
216 else if m
isa MPropDef then
217 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
218 self.provide_declaration
(m
.const_color
, "#define {m.const_color} {color}")
220 self.provide_declaration
(m
.const_color
, "extern const int {m.const_color};")
221 v
.add
("const int {m.const_color} = {color};")
223 else if m
isa MType then
224 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
225 self.provide_declaration
(m
.const_color
, "#define {m.const_color} {color}")
227 self.provide_declaration
(m
.const_color
, "extern const int {m.const_color};")
228 v
.add
("const int {m.const_color} = {color};")
231 color_consts_done
.add
(m
)
234 private var color_consts_done
= new HashSet[Object]
236 # colorize classe properties
237 fun do_property_coloring
do
238 var mclasses
= new HashSet[MClass].from
(modelbuilder
.model
.mclasses
)
241 var method_layout_builder
: PropertyLayoutBuilder[PropertyLayoutElement]
242 var attribute_layout_builder
: PropertyLayoutBuilder[MAttribute]
243 #FIXME PH and BM layouts too slow for large programs
244 #if modelbuilder.toolcontext.opt_bm_typing.value then
245 # method_layout_builder = new MMethodBMizer(self.mainmodule)
246 # attribute_layout_builder = new MAttributeBMizer(self.mainmodule)
247 #else if modelbuilder.toolcontext.opt_phmod_typing.value then
248 # method_layout_builder = new MMethodHasher(new PHModOperator, self.mainmodule)
249 # attribute_layout_builder = new MAttributeHasher(new PHModOperator, self.mainmodule)
250 #else if modelbuilder.toolcontext.opt_phand_typing.value then
251 # method_layout_builder = new MMethodHasher(new PHAndOperator, self.mainmodule)
252 # attribute_layout_builder = new MAttributeHasher(new PHAndOperator, self.mainmodule)
255 var class_layout_builder
= new MClassColorer(self.mainmodule
)
256 class_layout_builder
.build_layout
(mclasses
)
257 method_layout_builder
= new MPropertyColorer[PropertyLayoutElement](self.mainmodule
, class_layout_builder
)
258 attribute_layout_builder
= new MPropertyColorer[MAttribute](self.mainmodule
, class_layout_builder
)
261 # lookup properties to build layout with
262 var mmethods
= new HashMap[MClass, Set[PropertyLayoutElement]]
263 var mattributes
= new HashMap[MClass, Set[MAttribute]]
264 for mclass
in mclasses
do
265 mmethods
[mclass
] = new HashSet[PropertyLayoutElement]
266 mattributes
[mclass
] = new HashSet[MAttribute]
267 for mprop
in self.mainmodule
.properties
(mclass
) do
268 if mprop
isa MMethod then
269 mmethods
[mclass
].add
(mprop
)
270 else if mprop
isa MAttribute then
271 mattributes
[mclass
].add
(mprop
)
276 # Collect all super calls (dead or not)
277 var all_super_calls
= new HashSet[MMethodDef]
278 for mmodule
in self.mainmodule
.in_importation
.greaters
do
279 for mclassdef
in mmodule
.mclassdefs
do
280 for mpropdef
in mclassdef
.mpropdefs
do
281 if not mpropdef
isa MMethodDef then continue
282 if mpropdef
.has_supercall
then
283 all_super_calls
.add
(mpropdef
)
289 # lookup super calls and add it to the list of mmethods to build layout with
291 if runtime_type_analysis
!= null then
292 super_calls
= runtime_type_analysis
.live_super_sends
294 super_calls
= all_super_calls
297 for mmethoddef
in super_calls
do
298 var mclass
= mmethoddef
.mclassdef
.mclass
299 mmethods
[mclass
].add
(mmethoddef
)
300 for descendant
in mclass
.in_hierarchy
(self.mainmodule
).smallers
do
301 mmethods
[descendant
].add
(mmethoddef
)
306 self.method_layout
= method_layout_builder
.build_layout
(mmethods
)
307 self.method_tables
= build_method_tables
(mclasses
, super_calls
)
308 self.compile_color_consts
(method_layout
.pos
)
310 # attribute null color to dead supercalls
311 for mpropdef
in all_super_calls
do
312 if super_calls
.has
(mpropdef
) then continue
313 compile_color_const
(new_visitor
, mpropdef
, -1)
316 # attributes coloration
317 self.attr_layout
= attribute_layout_builder
.build_layout
(mattributes
)
318 self.attr_tables
= build_attr_tables
(mclasses
)
319 self.compile_color_consts
(attr_layout
.pos
)
322 fun build_method_tables
(mclasses
: Set[MClass], super_calls
: Set[MMethodDef]): Map[MClass, Array[nullable MPropDef]] do
323 var layout
= self.method_layout
324 var tables
= new HashMap[MClass, Array[nullable MPropDef]]
325 for mclass
in mclasses
do
326 var table
= new Array[nullable MPropDef]
327 var supercalls
= new List[MMethodDef]
329 # first, fill table from parents by reverse linearization order
330 var parents
= new Array[MClass]
331 if mainmodule
.flatten_mclass_hierarchy
.has
(mclass
) then
332 parents
= mclass
.in_hierarchy
(mainmodule
).greaters
.to_a
333 self.mainmodule
.linearize_mclasses
(parents
)
336 for parent
in parents
do
337 if parent
== mclass
then continue
338 for mproperty
in self.mainmodule
.properties
(parent
) do
339 if not mproperty
isa MMethod then continue
340 var color
= layout
.pos
[mproperty
]
341 if table
.length
<= color
then
342 for i
in [table
.length
.. color
[ do
346 for mpropdef
in mproperty
.mpropdefs
do
347 if mpropdef
.mclassdef
.mclass
== parent
then
348 table
[color
] = mpropdef
353 # lookup for super calls in super classes
354 for mmethoddef
in super_calls
do
355 for mclassdef
in parent
.mclassdefs
do
356 if mclassdef
.mpropdefs
.has
(mmethoddef
) then
357 supercalls
.add
(mmethoddef
)
363 # then override with local properties
364 for mproperty
in self.mainmodule
.properties
(mclass
) do
365 if not mproperty
isa MMethod then continue
366 var color
= layout
.pos
[mproperty
]
367 if table
.length
<= color
then
368 for i
in [table
.length
.. color
[ do
372 for mpropdef
in mproperty
.mpropdefs
do
373 if mpropdef
.mclassdef
.mclass
== mclass
then
374 table
[color
] = mpropdef
379 # lookup for super calls in local class
380 for mmethoddef
in super_calls
do
381 for mclassdef
in mclass
.mclassdefs
do
382 if mclassdef
.mpropdefs
.has
(mmethoddef
) then
383 supercalls
.add
(mmethoddef
)
387 # insert super calls in table according to receiver
388 for supercall
in supercalls
do
389 var color
= layout
.pos
[supercall
]
390 if table
.length
<= color
then
391 for i
in [table
.length
.. color
[ do
395 var mmethoddef
= supercall
.lookup_next_definition
(self.mainmodule
, mclass
.intro
.bound_mtype
)
396 table
[color
] = mmethoddef
398 tables
[mclass
] = table
403 fun build_attr_tables
(mclasses
: Set[MClass]): Map[MClass, Array[nullable MPropDef]] do
404 var layout
= self.attr_layout
405 var tables
= new HashMap[MClass, Array[nullable MPropDef]]
406 for mclass
in mclasses
do
407 var table
= new Array[nullable MPropDef]
408 # first, fill table from parents by reverse linearization order
409 var parents
= new Array[MClass]
410 if mainmodule
.flatten_mclass_hierarchy
.has
(mclass
) then
411 parents
= mclass
.in_hierarchy
(mainmodule
).greaters
.to_a
412 self.mainmodule
.linearize_mclasses
(parents
)
414 for parent
in parents
do
415 if parent
== mclass
then continue
416 for mproperty
in self.mainmodule
.properties
(parent
) do
417 if not mproperty
isa MAttribute then continue
418 var color
= layout
.pos
[mproperty
]
419 if table
.length
<= color
then
420 for i
in [table
.length
.. color
[ do
424 for mpropdef
in mproperty
.mpropdefs
do
425 if mpropdef
.mclassdef
.mclass
== parent
then
426 table
[color
] = mpropdef
432 # then override with local properties
433 for mproperty
in self.mainmodule
.properties
(mclass
) do
434 if not mproperty
isa MAttribute then continue
435 var color
= layout
.pos
[mproperty
]
436 if table
.length
<= color
then
437 for i
in [table
.length
.. color
[ do
441 for mpropdef
in mproperty
.mpropdefs
do
442 if mpropdef
.mclassdef
.mclass
== mclass
then
443 table
[color
] = mpropdef
447 tables
[mclass
] = table
452 # colorize live types of the program
453 private fun do_type_coloring
: POSet[MType] do
454 var mtypes
= new HashSet[MType]
455 mtypes
.add_all
(self.runtime_type_analysis
.live_types
)
456 mtypes
.add_all
(self.runtime_type_analysis
.live_cast_types
)
457 for c
in self.box_kinds
.keys
do
458 mtypes
.add
(c
.mclass_type
)
462 var layout_builder
: TypingLayoutBuilder[MType]
463 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
464 layout_builder
= new MTypeBMizer(self.mainmodule
)
465 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
466 layout_builder
= new MTypeHasher(new PHModOperator, self.mainmodule
)
467 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
468 layout_builder
= new MTypeHasher(new PHAndOperator, self.mainmodule
)
470 layout_builder
= new MTypeColorer(self.mainmodule
)
474 self.type_layout
= layout_builder
.build_layout
(mtypes
)
475 var poset
= layout_builder
.poset
.as(not null)
476 self.type_tables
= self.build_type_tables
(poset
)
478 # VT and FT are stored with other unresolved types in the big resolution_tables
479 self.compile_resolution_tables
(mtypes
)
485 fun build_type_tables
(mtypes
: POSet[MType]): Map[MType, Array[nullable MType]] do
486 var tables
= new HashMap[MType, Array[nullable MType]]
487 var layout
= self.type_layout
488 for mtype
in mtypes
do
489 var table
= new Array[nullable MType]
490 for sup
in mtypes
[mtype
].greaters
do
492 if layout
isa PHLayout[MType, MType] then
493 color
= layout
.hashes
[mtype
][sup
]
495 color
= layout
.pos
[sup
]
497 if table
.length
<= color
then
498 for i
in [table
.length
.. color
[ do
504 tables
[mtype
] = table
509 protected fun compile_resolution_tables
(mtypes
: Set[MType]) do
510 # resolution_tables is used to perform a type resolution at runtime in O(1)
512 # During the visit of the body of classes, live_unresolved_types are collected
514 # Collect all live_unresolved_types (visited in the body of classes)
516 # Determinate fo each livetype what are its possible requested anchored types
517 var mtype2unresolved
= new HashMap[MClassType, Set[MType]]
518 for mtype
in self.runtime_type_analysis
.live_types
do
519 var set
= new HashSet[MType]
520 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
521 if self.live_unresolved_types
.has_key
(cd
) then
522 set
.add_all
(self.live_unresolved_types
[cd
])
525 mtype2unresolved
[mtype
] = set
528 # Compute the table layout with the prefered method
529 var resolution_builder
: ResolutionLayoutBuilder
530 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
531 resolution_builder
= new ResolutionBMizer
532 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
533 resolution_builder
= new ResolutionHasher(new PHModOperator)
534 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
535 resolution_builder
= new ResolutionHasher(new PHAndOperator)
537 resolution_builder
= new ResolutionColorer
539 self.resolution_layout
= resolution_builder
.build_layout
(mtype2unresolved
)
540 self.resolution_tables
= self.build_resolution_tables
(mtype2unresolved
)
542 # Compile a C constant for each collected unresolved type.
543 # Either to a color, or to -1 if the unresolved type is dead (no live receiver can require it)
544 var all_unresolved
= new HashSet[MType]
545 for t
in self.live_unresolved_types
.values
do
546 all_unresolved
.add_all
(t
)
548 var all_unresolved_types_colors
= new HashMap[MType, Int]
549 for t
in all_unresolved
do
550 if self.resolution_layout
.pos
.has_key
(t
) then
551 all_unresolved_types_colors
[t
] = self.resolution_layout
.pos
[t
]
553 all_unresolved_types_colors
[t
] = -1
556 self.compile_color_consts
(all_unresolved_types_colors
)
559 #for k, v in unresolved_types_tables.as(not null) do
560 # print "{k}: {v.join(", ")}"
565 fun build_resolution_tables
(elements
: Map[MClassType, Set[MType]]): Map[MClassType, Array[nullable MType]] do
566 var tables
= new HashMap[MClassType, Array[nullable MType]]
567 var layout
= self.resolution_layout
568 for mclasstype
, mtypes
in elements
do
569 var table
= new Array[nullable MType]
570 for mtype
in mtypes
do
572 if layout
isa PHLayout[MClassType, MType] then
573 color
= layout
.hashes
[mclasstype
][mtype
]
575 color
= layout
.pos
[mtype
]
577 if table
.length
<= color
then
578 for i
in [table
.length
.. color
[ do
584 tables
[mclasstype
] = table
589 # Separately compile all the method definitions of the module
590 fun compile_module_to_c
(mmodule
: MModule)
592 var old_module
= self.mainmodule
593 self.mainmodule
= mmodule
594 for cd
in mmodule
.mclassdefs
do
595 for pd
in cd
.mpropdefs
do
596 if not pd
isa MMethodDef then continue
597 #print "compile {pd} @ {cd} @ {mmodule}"
598 var r
= pd
.separate_runtime_function
600 var r2
= pd
.virtual_runtime_function
601 r2
.compile_to_c
(self)
604 self.mainmodule
= old_module
607 # Globaly compile the type structure of a live type
608 fun compile_type_to_c
(mtype
: MType)
610 assert not mtype
.need_anchor
611 var layout
= self.type_layout
612 var is_live
= mtype
isa MClassType and runtime_type_analysis
.live_types
.has
(mtype
)
613 var is_cast_live
= runtime_type_analysis
.live_cast_types
.has
(mtype
)
614 var c_name
= mtype
.c_name
615 var v
= new SeparateCompilerVisitor(self)
616 v
.add_decl
("/* runtime type {mtype} */")
618 # extern const struct type_X
619 self.provide_declaration
("type_{c_name}", "extern const struct type type_{c_name};")
621 # const struct type_X
622 v
.add_decl
("const struct type type_{c_name} = \{")
624 # type id (for cast target)
626 v
.add_decl
("{layout.ids[mtype]},")
628 v
.add_decl
("-1, /*CAST DEAD*/")
632 v
.add_decl
("\"{mtype}\
", /* class_name_string */")
634 # type color (for cast target)
636 if layout
isa PHLayout[MType, MType] then
637 v
.add_decl
("{layout.masks[mtype]},")
639 v
.add_decl
("{layout.pos[mtype]},")
642 v
.add_decl
("-1, /*CAST DEAD*/")
646 if mtype
isa MNullableType then
652 # resolution table (for receiver)
654 var mclass_type
= mtype
655 if mclass_type
isa MNullableType then mclass_type
= mclass_type
.mtype
656 assert mclass_type
isa MClassType
657 if resolution_tables
[mclass_type
].is_empty
then
658 v
.add_decl
("NULL, /*NO RESOLUTIONS*/")
660 compile_type_resolution_table
(mtype
)
661 v
.require_declaration
("resolution_table_{c_name}")
662 v
.add_decl
("&resolution_table_{c_name},")
665 v
.add_decl
("NULL, /*DEAD*/")
668 # cast table (for receiver)
670 v
.add_decl
("{self.type_tables[mtype].length},")
672 for stype
in self.type_tables
[mtype
] do
673 if stype
== null then
674 v
.add_decl
("-1, /* empty */")
676 v
.add_decl
("{layout.ids[stype]}, /* {stype} */")
681 v
.add_decl
("0, \{\}, /*DEAD TYPE*/")
686 fun compile_type_resolution_table
(mtype
: MType) do
688 var mclass_type
: MClassType
689 if mtype
isa MNullableType then
690 mclass_type
= mtype
.mtype
.as(MClassType)
692 mclass_type
= mtype
.as(MClassType)
695 var layout
= self.resolution_layout
697 # extern const struct resolution_table_X resolution_table_X
698 self.provide_declaration
("resolution_table_{mtype.c_name}", "extern const struct types resolution_table_{mtype.c_name};")
700 # const struct fts_table_X fts_table_X
702 v
.add_decl
("const struct types resolution_table_{mtype.c_name} = \{")
703 if layout
isa PHLayout[MClassType, MType] then
704 v
.add_decl
("{layout.masks[mclass_type]},")
706 v
.add_decl
("0, /* dummy */")
709 for t
in self.resolution_tables
[mclass_type
] do
711 v
.add_decl
("NULL, /* empty */")
713 # The table stores the result of the type resolution
714 # Therefore, for a receiver `mclass_type`, and a unresolved type `t`
715 # the value stored is tv.
716 var tv
= t
.resolve_for
(mclass_type
, mclass_type
, self.mainmodule
, true)
717 # FIXME: What typeids means here? How can a tv not be live?
718 if self.type_layout
.ids
.has_key
(tv
) then
719 v
.require_declaration
("type_{tv.c_name}")
720 v
.add_decl
("&type_{tv.c_name}, /* {t}: {tv} */")
722 v
.add_decl
("NULL, /* empty ({t}: {tv} not a live type) */")
730 # Globally compile the table of the class mclass
731 # In a link-time optimisation compiler, tables are globally computed
732 # In a true separate compiler (a with dynamic loading) you cannot do this unfortnally
733 fun compile_class_to_c
(mclass
: MClass)
735 var mtype
= mclass
.intro
.bound_mtype
736 var c_name
= mclass
.c_name
737 var c_instance_name
= mclass
.c_instance_name
739 var vft
= self.method_tables
[mclass
]
740 var attrs
= self.attr_tables
[mclass
]
743 var is_dead
= runtime_type_analysis
!= null and not runtime_type_analysis
.live_classes
.has
(mclass
) and mtype
.ctype
== "val*" and mclass
.name
!= "NativeArray"
745 v
.add_decl
("/* runtime class {c_name} */")
749 self.provide_declaration
("class_{c_name}", "extern const struct class class_{c_name};")
750 v
.add_decl
("const struct class class_{c_name} = \{")
751 v
.add_decl
("{self.box_kind_of(mclass)}, /* box_kind */")
753 for i
in [0 .. vft
.length
[ do
754 var mpropdef
= vft
[i
]
755 if mpropdef
== null then
756 v
.add_decl
("NULL, /* empty */")
758 assert mpropdef
isa MMethodDef
759 var rf
= mpropdef
.virtual_runtime_function
760 v
.require_declaration
(rf
.c_name
)
761 v
.add_decl
("(nitmethod_t){rf.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
768 if mtype
.ctype
!= "val*" then
769 if mtype
.mclass
.name
== "Pointer" or mtype
.mclass
.kind
!= extern_kind
then
770 #Build instance struct
771 self.header
.add_decl
("struct instance_{c_instance_name} \{")
772 self.header
.add_decl
("const struct type *type;")
773 self.header
.add_decl
("const struct class *class;")
774 self.header
.add_decl
("{mtype.ctype} value;")
775 self.header
.add_decl
("\};")
778 if not self.runtime_type_analysis
.live_types
.has
(mtype
) then return
781 self.provide_declaration
("BOX_{c_name}", "val* BOX_{c_name}({mtype.ctype});")
782 v
.add_decl
("/* allocate {mtype} */")
783 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
784 v
.add
("struct instance_{c_instance_name}*res = nit_alloc(sizeof(struct instance_{c_instance_name}));")
785 v
.require_declaration
("type_{c_name}")
786 v
.add
("res->type = &type_{c_name};")
787 v
.require_declaration
("class_{c_name}")
788 v
.add
("res->class = &class_{c_name};")
789 v
.add
("res->value = value;")
790 v
.add
("return (val*)res;")
793 else if mclass
.name
== "NativeArray" then
794 #Build instance struct
795 self.header
.add_decl
("struct instance_{c_instance_name} \{")
796 self.header
.add_decl
("const struct type *type;")
797 self.header
.add_decl
("const struct class *class;")
798 # NativeArrays are just a instance header followed by an array of values
799 self.header
.add_decl
("val* values[0];")
800 self.header
.add_decl
("\};")
803 self.provide_declaration
("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(int length, const struct type* type);")
804 v
.add_decl
("/* allocate {mtype} */")
805 v
.add_decl
("{mtype.ctype} NEW_{c_name}(int length, const struct type* type) \{")
806 var res
= v
.new_named_var
(mtype
, "self")
808 var mtype_elt
= mtype
.arguments
.first
809 v
.add
("{res} = nit_alloc(sizeof(struct instance_{c_instance_name}) + length*sizeof({mtype_elt.ctype}));")
810 v
.add
("{res}->type = type;")
811 hardening_live_type
(v
, "type")
812 v
.require_declaration
("class_{c_name}")
813 v
.add
("{res}->class = &class_{c_name};")
814 v
.add
("return {res};")
820 self.provide_declaration
("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(const struct type* type);")
821 v
.add_decl
("/* allocate {mtype} */")
822 v
.add_decl
("{mtype.ctype} NEW_{c_name}(const struct type* type) \{")
824 v
.add_abort
("{mclass} is DEAD")
826 var res
= v
.new_named_var
(mtype
, "self")
828 v
.add
("{res} = nit_alloc(sizeof(struct instance) + {attrs.length}*sizeof(nitattribute_t));")
829 v
.add
("{res}->type = type;")
830 hardening_live_type
(v
, "type")
831 v
.require_declaration
("class_{c_name}")
832 v
.add
("{res}->class = &class_{c_name};")
833 self.generate_init_attr
(v
, res
, mtype
)
834 v
.add
("return {res};")
839 # Add a dynamic test to ensure that the type referenced by `t` is a live type
840 fun hardening_live_type
(v
: VISITOR, t
: String)
842 if not v
.compiler
.modelbuilder
.toolcontext
.opt_hardening
.value
then return
843 v
.add
("if({t} == NULL) \{")
844 v
.add_abort
("type null")
846 v
.add
("if({t}->table_size == 0) \{")
847 v
.add
("fprintf(stderr, \"Insantiation of a dead
type: %s\\n\
", {t}->name);")
848 v
.add_abort
("type dead")
852 redef fun new_visitor
do return new SeparateCompilerVisitor(self)
856 private var type_tables
: Map[MType, Array[nullable MType]] = new HashMap[MType, Array[nullable MType]]
857 private var resolution_tables
: Map[MClassType, Array[nullable MType]] = new HashMap[MClassType, Array[nullable MType]]
858 protected var method_tables
: Map[MClass, Array[nullable MPropDef]] = new HashMap[MClass, Array[nullable MPropDef]]
859 protected var attr_tables
: Map[MClass, Array[nullable MPropDef]] = new HashMap[MClass, Array[nullable MPropDef]]
861 redef fun display_stats
864 if self.modelbuilder
.toolcontext
.opt_tables_metrics
.value
then
871 print
"# size of subtyping tables"
872 print
"\ttotal \tholes"
875 for t
, table
in type_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 resolution tables"
882 print
"\ttotal \tholes"
885 for t
, table
in resolution_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 methods tables"
892 print
"\ttotal \tholes"
895 for t
, table
in method_tables
do
896 total
+= table
.length
897 for e
in table
do if e
== null then holes
+= 1
899 print
"\t{total}\t{holes}"
901 print
"# size of attributes tables"
902 print
"\ttotal \tholes"
905 for t
, table
in attr_tables
do
906 total
+= table
.length
907 for e
in table
do if e
== null then holes
+= 1
909 print
"\t{total}\t{holes}"
912 redef fun compile_nitni_structs
914 self.header
.add_decl
("struct nitni_instance \{struct instance *value;\};")
917 redef fun finalize_ffi_for_module
(nmodule
)
919 var old_module
= self.mainmodule
920 self.mainmodule
= nmodule
.mmodule
.as(not null)
922 self.mainmodule
= old_module
926 # A visitor on the AST of property definition that generate the C code of a separate compilation process.
927 class SeparateCompilerVisitor
928 super AbstractCompilerVisitor
930 redef type COMPILER: SeparateCompiler
932 redef fun adapt_signature
(m
, args
)
934 var msignature
= m
.msignature
.resolve_for
(m
.mclassdef
.bound_mtype
, m
.mclassdef
.bound_mtype
, m
.mclassdef
.mmodule
, true)
935 var recv
= args
.first
936 if recv
.mtype
.ctype
!= m
.mclassdef
.mclass
.mclass_type
.ctype
then
937 args
.first
= self.autobox
(args
.first
, m
.mclassdef
.mclass
.mclass_type
)
939 for i
in [0..msignature
.arity
[ do
940 var t
= msignature
.mparameters
[i
].mtype
941 if i
== msignature
.vararg_rank
then
944 args
[i
+1] = self.autobox
(args
[i
+1], t
)
948 redef fun autobox
(value
, mtype
)
950 if value
.mtype
== mtype
then
952 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
954 else if value
.mtype
.ctype
== "val*" then
955 return self.new_expr
("((struct instance_{mtype.c_instance_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
956 else if mtype
.ctype
== "val*" then
957 var valtype
= value
.mtype
.as(MClassType)
958 var res
= self.new_var
(mtype
)
959 if compiler
.runtime_type_analysis
!= null and not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
960 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
961 self.add
("printf(\"Dead code executed
!\\n\
"); show_backtrace(1);")
964 self.require_declaration
("BOX_{valtype.c_name}")
965 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
967 else if value
.mtype
.ctype
== "void*" and mtype
.ctype
== "void*" then
970 # Bad things will appen!
971 var res
= self.new_var
(mtype
)
972 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
973 self.add
("printf(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); show_backtrace(1);")
978 # Return a C expression returning the runtime type structure of the value
979 # The point of the method is to works also with primitives types.
980 fun type_info
(value
: RuntimeVariable): String
982 if value
.mtype
.ctype
== "val*" then
983 return "{value}->type"
985 compiler
.undead_types
.add
(value
.mtype
)
986 self.require_declaration
("type_{value.mtype.c_name}")
987 return "(&type_{value.mtype.c_name})"
991 redef fun send
(mmethod
, arguments
)
993 self.varargize
(mmethod
.intro
, mmethod
.intro
.msignature
.as(not null), arguments
)
995 if arguments
.first
.mcasttype
.ctype
!= "val*" then
996 # In order to shortcut the primitive, we need to find the most specific method
997 # Howverr, because of performance (no flattening), we always work on the realmainmodule
998 var m
= self.compiler
.mainmodule
999 self.compiler
.mainmodule
= self.compiler
.realmainmodule
1000 var res
= self.monomorphic_send
(mmethod
, arguments
.first
.mcasttype
, arguments
)
1001 self.compiler
.mainmodule
= m
1005 return table_send
(mmethod
, arguments
, mmethod
.const_color
)
1008 private fun table_send
(mmethod
: MMethod, arguments
: Array[RuntimeVariable], const_color
: String): nullable RuntimeVariable
1010 assert arguments
.length
== mmethod
.intro
.msignature
.arity
+ 1 else debug
("Invalid arity for {mmethod}. {arguments.length} arguments given.")
1012 var res
: nullable RuntimeVariable
1013 var msignature
= mmethod
.intro
.msignature
.resolve_for
(mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.mmodule
, true)
1014 var ret
= msignature
.return_mtype
1015 if mmethod
.is_new
then
1016 ret
= arguments
.first
.mtype
1017 res
= self.new_var
(ret
)
1018 else if ret
== null then
1021 res
= self.new_var
(ret
)
1024 var s
= new FlatBuffer
1025 var ss
= new FlatBuffer
1027 var recv
= arguments
.first
1030 for i
in [0..msignature
.arity
[ do
1031 var a
= arguments
[i
+1]
1032 var t
= msignature
.mparameters
[i
].mtype
1033 if i
== msignature
.vararg_rank
then
1034 t
= arguments
[i
+1].mcasttype
1036 s
.append
(", {t.ctype}")
1037 a
= self.autobox
(a
, t
)
1041 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
or mmethod
.name
== "==" or mmethod
.name
== "!="
1042 var maybenull
= recv
.mcasttype
isa MNullableType and consider_null
1044 self.add
("if ({recv} == NULL) \{")
1045 if mmethod
.name
== "==" then
1047 var arg
= arguments
[1]
1048 if arg
.mcasttype
isa MNullableType then
1049 self.add
("{res} = ({arg} == NULL);")
1050 else if arg
.mcasttype
isa MNullType then
1051 self.add
("{res} = 1; /* is null */")
1053 self.add
("{res} = 0; /* {arg.inspect} cannot be null */")
1055 else if mmethod
.name
== "!=" then
1057 var arg
= arguments
[1]
1058 if arg
.mcasttype
isa MNullableType then
1059 self.add
("{res} = ({arg} != NULL);")
1060 else if arg
.mcasttype
isa MNullType then
1061 self.add
("{res} = 0; /* is null */")
1063 self.add
("{res} = 1; /* {arg.inspect} cannot be null */")
1066 self.add_abort
("Receiver is null")
1068 self.add
("\} else \{")
1070 if not self.compiler
.modelbuilder
.toolcontext
.opt_no_shortcut_equate
.value
and (mmethod
.name
== "==" or mmethod
.name
== "!=") then
1072 # Recv is not null, thus is arg is, it is easy to conclude (and respect the invariants)
1073 var arg
= arguments
[1]
1074 if arg
.mcasttype
isa MNullType then
1075 if mmethod
.name
== "==" then
1076 self.add
("{res} = 0; /* arg is null but recv is not */")
1078 self.add
("{res} = 1; /* arg is null and recv is not */")
1088 if ret
== null then r
= "void" else r
= ret
.ctype
1089 self.require_declaration
(const_color
)
1090 var call
= "(({r} (*)({s}))({arguments.first}->class->vft[{const_color}]))({ss}) /* {mmethod} on {arguments.first.inspect}*/"
1093 self.add
("{res} = {call};")
1105 redef fun call
(mmethoddef
, recvtype
, arguments
)
1107 assert arguments
.length
== mmethoddef
.msignature
.arity
+ 1 else debug
("Invalid arity for {mmethoddef}. {arguments.length} arguments given.")
1109 var res
: nullable RuntimeVariable
1110 var ret
= mmethoddef
.msignature
.return_mtype
1111 if mmethoddef
.mproperty
.is_new
then
1112 ret
= arguments
.first
.mtype
1113 res
= self.new_var
(ret
)
1114 else if ret
== null then
1117 ret
= ret
.resolve_for
(mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.mmodule
, true)
1118 res
= self.new_var
(ret
)
1121 if self.compiler
.modelbuilder
.mpropdef2npropdef
.has_key
(mmethoddef
) and
1122 self.compiler
.modelbuilder
.mpropdef2npropdef
[mmethoddef
] isa AInternMethPropdef and
1123 not compiler
.modelbuilder
.toolcontext
.opt_no_inline_intern
.value
then
1124 var frame
= new Frame(self, mmethoddef
, recvtype
, arguments
)
1125 frame
.returnlabel
= self.get_name
("RET_LABEL")
1126 frame
.returnvar
= res
1127 var old_frame
= self.frame
1129 self.add
("\{ /* Inline {mmethoddef} ({arguments.join(",")}) */")
1130 mmethoddef
.compile_inside_to_c
(self, arguments
)
1131 self.add
("{frame.returnlabel.as(not null)}:(void)0;")
1133 self.frame
= old_frame
1138 self.adapt_signature
(mmethoddef
, arguments
)
1140 self.require_declaration
(mmethoddef
.c_name
)
1142 self.add
("{mmethoddef.c_name}({arguments.join(", ")});")
1145 self.add
("{res} = {mmethoddef.c_name}({arguments.join(", ")});")
1151 redef fun supercall
(m
: MMethodDef, recvtype
: MClassType, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
1153 if arguments
.first
.mcasttype
.ctype
!= "val*" then
1154 # In order to shortcut the primitive, we need to find the most specific method
1155 # However, because of performance (no flattening), we always work on the realmainmodule
1156 var main
= self.compiler
.mainmodule
1157 self.compiler
.mainmodule
= self.compiler
.realmainmodule
1158 var res
= self.monomorphic_super_send
(m
, recvtype
, arguments
)
1159 self.compiler
.mainmodule
= main
1162 return table_send
(m
.mproperty
, arguments
, m
.const_color
)
1165 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
1167 # A vararg must be stored into an new array
1168 # The trick is that the dymaic type of the array may depends on the receiver
1169 # of the method (ie recv) if the static type is unresolved
1170 # This is more complex than usual because the unresolved type must not be resolved
1171 # with the current receiver (ie self).
1172 # Therefore to isolate the resolution from self, a local Frame is created.
1173 # One can see this implementation as an inlined method of the receiver whose only
1174 # job is to allocate the array
1175 var old_frame
= self.frame
1176 var frame
= new Frame(self, mpropdef
, mpropdef
.mclassdef
.bound_mtype
, [recv
])
1178 #print "required Array[{elttype}] for recv {recv.inspect}. bound=Array[{self.resolve_for(elttype, recv)}]. selfvar={frame.arguments.first.inspect}"
1179 var res
= self.array_instance
(varargs
, elttype
)
1180 self.frame
= old_frame
1184 redef fun isset_attribute
(a
, recv
)
1186 self.check_recv_notnull
(recv
)
1187 var res
= self.new_var
(bool_type
)
1189 # What is the declared type of the attribute?
1190 var mtype
= a
.intro
.static_mtype
.as(not null)
1191 var intromclassdef
= a
.intro
.mclassdef
1192 mtype
= mtype
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1194 if mtype
isa MNullableType then
1195 self.add
("{res} = 1; /* easy isset: {a} on {recv.inspect} */")
1199 self.require_declaration
(a
.const_color
)
1200 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1201 self.add
("{res} = {recv}->attrs[{a.const_color}] != NULL; /* {a} on {recv.inspect}*/")
1204 if mtype
.ctype
== "val*" then
1205 self.add
("{res} = {recv}->attrs[{a.const_color}].val != NULL; /* {a} on {recv.inspect} */")
1207 self.add
("{res} = 1; /* NOT YET IMPLEMENTED: isset of primitives: {a} on {recv.inspect} */")
1213 redef fun read_attribute
(a
, recv
)
1215 self.check_recv_notnull
(recv
)
1217 # What is the declared type of the attribute?
1218 var ret
= a
.intro
.static_mtype
.as(not null)
1219 var intromclassdef
= a
.intro
.mclassdef
1220 ret
= ret
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1222 self.require_declaration
(a
.const_color
)
1223 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1224 # Get the attribute or a box (ie. always a val*)
1225 var cret
= self.object_type
.as_nullable
1226 var res
= self.new_var
(cret
)
1229 self.add
("{res} = {recv}->attrs[{a.const_color}]; /* {a} on {recv.inspect} */")
1231 # Check for Uninitialized attribute
1232 if not ret
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then
1233 self.add
("if ({res} == NULL) \{")
1234 self.add_abort
("Uninitialized attribute {a.name}")
1238 # Return the attribute or its unboxed version
1239 # Note: it is mandatory since we reuse the box on write, we do not whant that the box escapes
1240 return self.autobox
(res
, ret
)
1242 var res
= self.new_var
(ret
)
1243 self.add
("{res} = {recv}->attrs[{a.const_color}].{ret.ctypename}; /* {a} on {recv.inspect} */")
1245 # Check for Uninitialized attribute
1246 if ret
.ctype
== "val*" and not ret
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then
1247 self.add
("if ({res} == NULL) \{")
1248 self.add_abort
("Uninitialized attribute {a.name}")
1256 redef fun write_attribute
(a
, recv
, value
)
1258 self.check_recv_notnull
(recv
)
1260 # What is the declared type of the attribute?
1261 var mtype
= a
.intro
.static_mtype
.as(not null)
1262 var intromclassdef
= a
.intro
.mclassdef
1263 mtype
= mtype
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1265 # Adapt the value to the declared type
1266 value
= self.autobox
(value
, mtype
)
1268 self.require_declaration
(a
.const_color
)
1269 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1270 var attr
= "{recv}->attrs[{a.const_color}]"
1271 if mtype
.ctype
!= "val*" then
1272 assert mtype
isa MClassType
1273 # The attribute is primitive, thus we store it in a box
1274 # The trick is to create the box the first time then resuse the box
1275 self.add
("if ({attr} != NULL) \{")
1276 self.add
("((struct instance_{mtype.c_instance_name}*){attr})->value = {value}; /* {a} on {recv.inspect} */")
1277 self.add
("\} else \{")
1278 value
= self.autobox
(value
, self.object_type
.as_nullable
)
1279 self.add
("{attr} = {value}; /* {a} on {recv.inspect} */")
1282 # The attribute is not primitive, thus store it direclty
1283 self.add
("{attr} = {value}; /* {a} on {recv.inspect} */")
1286 self.add
("{recv}->attrs[{a.const_color}].{mtype.ctypename} = {value}; /* {a} on {recv.inspect} */")
1290 # Check that mtype is a live open type
1291 fun hardening_live_open_type
(mtype
: MType)
1293 if not compiler
.modelbuilder
.toolcontext
.opt_hardening
.value
then return
1294 self.require_declaration
(mtype
.const_color
)
1295 var col
= mtype
.const_color
1296 self.add
("if({col} == -1) \{")
1297 self.add
("fprintf(stderr, \"Resolution of a dead open
type: %s\\n\
", \"{mtype.to_s.escape_to_c}\
");")
1298 self.add_abort
("open type dead")
1302 # Check that mtype it a pointer to a live cast type
1303 fun hardening_cast_type
(t
: String)
1305 if not compiler
.modelbuilder
.toolcontext
.opt_hardening
.value
then return
1306 add
("if({t} == NULL) \{")
1307 add_abort
("cast type null")
1309 add
("if({t}->id == -1 || {t}->color == -1) \{")
1310 add
("fprintf(stderr, \"Try to cast on a dead cast
type: %s\\n\
", {t}->name);")
1311 add_abort
("cast type dead")
1315 redef fun init_instance
(mtype
)
1317 self.require_declaration
("NEW_{mtype.mclass.c_name}")
1318 var compiler
= self.compiler
1319 if mtype
isa MGenericType and mtype
.need_anchor
then
1320 hardening_live_open_type
(mtype
)
1321 link_unresolved_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1322 var recv
= self.frame
.arguments
.first
1323 var recv_type_info
= self.type_info
(recv
)
1324 self.require_declaration
(mtype
.const_color
)
1325 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1326 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
)
1328 return self.new_expr
("NEW_{mtype.mclass.c_name}({recv_type_info}->resolution_table->types[{mtype.const_color}])", mtype
)
1331 compiler
.undead_types
.add
(mtype
)
1332 self.require_declaration
("type_{mtype.c_name}")
1333 return self.new_expr
("NEW_{mtype.mclass.c_name}(&type_{mtype.c_name})", mtype
)
1336 redef fun type_test
(value
, mtype
, tag
)
1338 self.add
("/* {value.inspect} isa {mtype} */")
1339 var compiler
= self.compiler
1341 var recv
= self.frame
.arguments
.first
1342 var recv_type_info
= self.type_info
(recv
)
1344 var res
= self.new_var
(bool_type
)
1346 var cltype
= self.get_name
("cltype")
1347 self.add_decl
("int {cltype};")
1348 var idtype
= self.get_name
("idtype")
1349 self.add_decl
("int {idtype};")
1351 var maybe_null
= self.maybe_null
(value
)
1352 var accept_null
= "0"
1354 if ntype
isa MNullableType then
1359 if value
.mcasttype
.is_subtype
(self.frame
.mpropdef
.mclassdef
.mmodule
, self.frame
.mpropdef
.mclassdef
.bound_mtype
, mtype
) then
1360 self.add
("{res} = 1; /* easy {value.inspect} isa {mtype}*/")
1361 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1362 self.compiler
.count_type_test_skipped
[tag
] += 1
1363 self.add
("count_type_test_skipped_{tag}++;")
1368 if ntype
.need_anchor
then
1369 var type_struct
= self.get_name
("type_struct")
1370 self.add_decl
("const struct type* {type_struct};")
1372 # Either with resolution_table with a direct resolution
1373 hardening_live_open_type
(mtype
)
1374 link_unresolved_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1375 self.require_declaration
(mtype
.const_color
)
1376 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1377 self.add
("{type_struct} = {recv_type_info}->resolution_table->types[HASH({recv_type_info}->resolution_table->mask, {mtype.const_color})];")
1379 self.add
("{type_struct} = {recv_type_info}->resolution_table->types[{mtype.const_color}];")
1381 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1382 self.compiler
.count_type_test_unresolved
[tag
] += 1
1383 self.add
("count_type_test_unresolved_{tag}++;")
1385 hardening_cast_type
(type_struct
)
1386 self.add
("{cltype} = {type_struct}->color;")
1387 self.add
("{idtype} = {type_struct}->id;")
1388 if maybe_null
and accept_null
== "0" then
1389 var is_nullable
= self.get_name
("is_nullable")
1390 self.add_decl
("short int {is_nullable};")
1391 self.add
("{is_nullable} = {type_struct}->is_nullable;")
1392 accept_null
= is_nullable
.to_s
1394 else if ntype
isa MClassType then
1395 compiler
.undead_types
.add
(mtype
)
1396 self.require_declaration
("type_{mtype.c_name}")
1397 hardening_cast_type
("(&type_{mtype.c_name})")
1398 self.add
("{cltype} = type_{mtype.c_name}.color;")
1399 self.add
("{idtype} = type_{mtype.c_name}.id;")
1400 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1401 self.compiler
.count_type_test_resolved
[tag
] += 1
1402 self.add
("count_type_test_resolved_{tag}++;")
1405 self.add
("printf(\"NOT YET IMPLEMENTED: type_test
(%s
, {mtype}).\\n\
", \"{value.inspect}\
"); show_backtrace(1);")
1408 # check color is in table
1410 self.add
("if({value} == NULL) \{")
1411 self.add
("{res} = {accept_null};")
1412 self.add
("\} else \{")
1414 var value_type_info
= self.type_info
(value
)
1415 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1416 self.add
("{cltype} = HASH({value_type_info}->color, {idtype});")
1418 self.add
("if({cltype} >= {value_type_info}->table_size) \{")
1419 self.add
("{res} = 0;")
1420 self.add
("\} else \{")
1421 self.add
("{res} = {value_type_info}->type_table[{cltype}] == {idtype};")
1430 redef fun is_same_type_test
(value1
, value2
)
1432 var res
= self.new_var
(bool_type
)
1433 # Swap values to be symetric
1434 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1439 if value1
.mtype
.ctype
!= "val*" then
1440 if value2
.mtype
== value1
.mtype
then
1441 self.add
("{res} = 1; /* is_same_type_test: compatible types {value1.mtype} vs. {value2.mtype} */")
1442 else if value2
.mtype
.ctype
!= "val*" then
1443 self.add
("{res} = 0; /* is_same_type_test: incompatible types {value1.mtype} vs. {value2.mtype}*/")
1445 var mtype1
= value1
.mtype
.as(MClassType)
1446 self.require_declaration
("class_{mtype1.c_name}")
1447 self.add
("{res} = ({value2} != NULL) && ({value2}->class == &class_{mtype1.c_name}); /* is_same_type_test */")
1450 self.add
("{res} = ({value1} == {value2}) || ({value1} != NULL && {value2} != NULL && {value1}->class == {value2}->class); /* is_same_type_test */")
1455 redef fun class_name_string
(value
)
1457 var res
= self.get_name
("var_class_name")
1458 self.add_decl
("const char* {res};")
1459 if value
.mtype
.ctype
== "val*" then
1460 self.add
"{res} = {value} == NULL ? \"null\
" : {value}->type->name;"
1461 else if value
.mtype
isa MClassType and value
.mtype
.as(MClassType).mclass
.kind
== extern_kind
then
1462 self.add
"{res} = \"{value.mtype.as(MClassType).mclass}\
";"
1464 self.require_declaration
("type_{value.mtype.c_name}")
1465 self.add
"{res} = type_{value.mtype.c_name}.name;"
1470 redef fun equal_test
(value1
, value2
)
1472 var res
= self.new_var
(bool_type
)
1473 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1478 if value1
.mtype
.ctype
!= "val*" then
1479 if value2
.mtype
== value1
.mtype
then
1480 self.add
("{res} = {value1} == {value2};")
1481 else if value2
.mtype
.ctype
!= "val*" then
1482 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
1484 var mtype1
= value1
.mtype
.as(MClassType)
1485 self.require_declaration
("class_{mtype1.c_name}")
1486 self.add
("{res} = ({value2} != NULL) && ({value2}->class == &class_{mtype1.c_name});")
1487 self.add
("if ({res}) \{")
1488 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
1493 var maybe_null
= true
1494 var test
= new Array[String]
1495 var t1
= value1
.mcasttype
1496 if t1
isa MNullableType then
1497 test
.add
("{value1} != NULL")
1502 var t2
= value2
.mcasttype
1503 if t2
isa MNullableType then
1504 test
.add
("{value2} != NULL")
1510 var incompatible
= false
1512 if t1
.ctype
!= "val*" then
1515 # No need to compare class
1516 else if t2
.ctype
!= "val*" then
1518 else if can_be_primitive
(value2
) then
1519 test
.add
("{value1}->class == {value2}->class")
1523 else if t2
.ctype
!= "val*" then
1525 if can_be_primitive
(value1
) then
1526 test
.add
("{value1}->class == {value2}->class")
1534 if incompatible
then
1536 self.add
("{res} = {value1} == {value2}; /* incompatible types {t1} vs. {t2}; but may be NULL*/")
1539 self.add
("{res} = 0; /* incompatible types {t1} vs. {t2}; cannot be NULL */")
1543 if primitive
!= null then
1544 test
.add
("((struct instance_{primitive.c_instance_name}*){value1})->value == ((struct instance_{primitive.c_instance_name}*){value2})->value")
1545 else if can_be_primitive
(value1
) and can_be_primitive
(value2
) then
1546 test
.add
("{value1}->class == {value2}->class")
1547 var s
= new Array[String]
1548 for t
, v
in self.compiler
.box_kinds
do
1549 s
.add
"({value1}->class->box_kind == {v} && ((struct instance_{t.c_instance_name}*){value1})->value == ((struct instance_{t.c_instance_name}*){value2})->value)"
1551 test
.add
("({s.join(" || ")})")
1553 self.add
("{res} = {value1} == {value2};")
1556 self.add
("{res} = {value1} == {value2} || ({test.join(" && ")});")
1560 fun can_be_primitive
(value
: RuntimeVariable): Bool
1562 var t
= value
.mcasttype
1563 if t
isa MNullableType then t
= t
.mtype
1564 if not t
isa MClassType then return false
1565 var k
= t
.mclass
.kind
1566 return k
== interface_kind
or t
.ctype
!= "val*"
1569 fun maybe_null
(value
: RuntimeVariable): Bool
1571 var t
= value
.mcasttype
1572 return t
isa MNullableType or t
isa MNullType
1575 redef fun array_instance
(array
, elttype
)
1577 var nclass
= self.get_class
("NativeArray")
1578 var arrayclass
= self.get_class
("Array")
1579 var arraytype
= arrayclass
.get_mtype
([elttype
])
1580 var res
= self.init_instance
(arraytype
)
1581 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
1582 var length
= self.int_instance
(array
.length
)
1583 var nat
= native_array_instance
(elttype
, length
)
1584 for i
in [0..array
.length
[ do
1585 var r
= self.autobox
(array
[i
], self.object_type
)
1586 self.add
("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
1588 self.send
(self.get_property
("with_native", arrayclass
.intro
.bound_mtype
), [res
, nat
, length
])
1593 fun native_array_instance
(elttype
: MType, length
: RuntimeVariable): RuntimeVariable
1595 var mtype
= self.get_class
("NativeArray").get_mtype
([elttype
])
1596 self.require_declaration
("NEW_{mtype.mclass.c_name}")
1597 assert mtype
isa MGenericType
1598 var compiler
= self.compiler
1599 if mtype
.need_anchor
then
1600 hardening_live_open_type
(mtype
)
1601 link_unresolved_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1602 var recv
= self.frame
.arguments
.first
1603 var recv_type_info
= self.type_info
(recv
)
1604 self.require_declaration
(mtype
.const_color
)
1605 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1606 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
)
1608 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, {recv_type_info}->resolution_table->types[{mtype.const_color}])", mtype
)
1611 compiler
.undead_types
.add
(mtype
)
1612 self.require_declaration
("type_{mtype.c_name}")
1613 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, &type_{mtype.c_name})", mtype
)
1616 redef fun native_array_def
(pname
, ret_type
, arguments
)
1618 var elttype
= arguments
.first
.mtype
1619 var nclass
= self.get_class
("NativeArray")
1620 var recv
= "((struct instance_{nclass.c_instance_name}*){arguments[0]})->values"
1621 if pname
== "[]" then
1622 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
1624 else if pname
== "[]=" then
1625 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
1627 else if pname
== "copy_to" then
1628 var recv1
= "((struct instance_{nclass.c_instance_name}*){arguments[1]})->values"
1629 self.add
("memcpy({recv1}, {recv}, {arguments[2]}*sizeof({elttype.ctype}));")
1634 redef fun calloc_array
(ret_type
, arguments
)
1636 var mclass
= self.get_class
("ArrayCapable")
1637 var ft
= mclass
.mclass_type
.arguments
.first
.as(MParameterType)
1638 var res
= self.native_array_instance
(ft
, arguments
[1])
1642 fun link_unresolved_type
(mclassdef
: MClassDef, mtype
: MType) do
1643 assert mtype
.need_anchor
1644 var compiler
= self.compiler
1645 if not compiler
.live_unresolved_types
.has_key
(self.frame
.mpropdef
.mclassdef
) then
1646 compiler
.live_unresolved_types
[self.frame
.mpropdef
.mclassdef
] = new HashSet[MType]
1648 compiler
.live_unresolved_types
[self.frame
.mpropdef
.mclassdef
].add
(mtype
)
1652 redef class MMethodDef
1653 fun separate_runtime_function
: AbstractRuntimeFunction
1655 var res
= self.separate_runtime_function_cache
1657 res
= new SeparateRuntimeFunction(self)
1658 self.separate_runtime_function_cache
= res
1662 private var separate_runtime_function_cache
: nullable SeparateRuntimeFunction
1664 fun virtual_runtime_function
: AbstractRuntimeFunction
1666 var res
= self.virtual_runtime_function_cache
1668 res
= new VirtualRuntimeFunction(self)
1669 self.virtual_runtime_function_cache
= res
1673 private var virtual_runtime_function_cache
: nullable VirtualRuntimeFunction
1676 # The C function associated to a methoddef separately compiled
1677 class SeparateRuntimeFunction
1678 super AbstractRuntimeFunction
1680 redef fun build_c_name
: String do return "{mmethoddef.c_name}"
1682 redef fun to_s
do return self.mmethoddef
.to_s
1684 redef fun compile_to_c
(compiler
)
1686 var mmethoddef
= self.mmethoddef
1688 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
1689 var v
= compiler
.new_visitor
1690 var selfvar
= new RuntimeVariable("self", recv
, recv
)
1691 var arguments
= new Array[RuntimeVariable]
1692 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
1695 var msignature
= mmethoddef
.msignature
.resolve_for
(mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.mmodule
, true)
1697 var sig
= new FlatBuffer
1698 var comment
= new FlatBuffer
1699 var ret
= msignature
.return_mtype
1701 sig
.append
("{ret.ctype} ")
1702 else if mmethoddef
.mproperty
.is_new
then
1704 sig
.append
("{ret.ctype} ")
1708 sig
.append
(self.c_name
)
1709 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
1710 comment
.append
("({selfvar}: {selfvar.mtype}")
1711 arguments
.add
(selfvar
)
1712 for i
in [0..msignature
.arity
[ do
1713 var mtype
= msignature
.mparameters
[i
].mtype
1714 if i
== msignature
.vararg_rank
then
1715 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
1717 comment
.append
(", {mtype}")
1718 sig
.append
(", {mtype.ctype} p{i}")
1719 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
1720 arguments
.add
(argvar
)
1725 comment
.append
(": {ret}")
1727 compiler
.provide_declaration
(self.c_name
, "{sig};")
1729 v
.add_decl
("/* method {self} for {comment} */")
1730 v
.add_decl
("{sig} \{")
1732 frame
.returnvar
= v
.new_var
(ret
)
1734 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1736 if recv
!= arguments
.first
.mtype
then
1737 #print "{self} {recv} {arguments.first}"
1739 mmethoddef
.compile_inside_to_c
(v
, arguments
)
1741 v
.add
("{frame.returnlabel.as(not null)}:;")
1743 v
.add
("return {frame.returnvar.as(not null)};")
1746 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})"
1750 # The C function associated to a methoddef on a primitive type, stored into a VFT of a class
1751 # The first parameter (the reciever) is always typed by val* in order to accept an object value
1752 class VirtualRuntimeFunction
1753 super AbstractRuntimeFunction
1755 redef fun build_c_name
: String do return "VIRTUAL_{mmethoddef.c_name}"
1757 redef fun to_s
do return self.mmethoddef
.to_s
1759 redef fun compile_to_c
(compiler
)
1761 var mmethoddef
= self.mmethoddef
1763 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
1764 var v
= compiler
.new_visitor
1765 var selfvar
= new RuntimeVariable("self", v
.object_type
, recv
)
1766 var arguments
= new Array[RuntimeVariable]
1767 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
1770 var sig
= new FlatBuffer
1771 var comment
= new FlatBuffer
1773 # Because the function is virtual, the signature must match the one of the original class
1774 var intromclassdef
= self.mmethoddef
.mproperty
.intro
.mclassdef
1775 var msignature
= mmethoddef
.mproperty
.intro
.msignature
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1776 var ret
= msignature
.return_mtype
1778 sig
.append
("{ret.ctype} ")
1779 else if mmethoddef
.mproperty
.is_new
then
1781 sig
.append
("{ret.ctype} ")
1785 sig
.append
(self.c_name
)
1786 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
1787 comment
.append
("({selfvar}: {selfvar.mtype}")
1788 arguments
.add
(selfvar
)
1789 for i
in [0..msignature
.arity
[ do
1790 var mtype
= msignature
.mparameters
[i
].mtype
1791 if i
== msignature
.vararg_rank
then
1792 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
1794 comment
.append
(", {mtype}")
1795 sig
.append
(", {mtype.ctype} p{i}")
1796 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
1797 arguments
.add
(argvar
)
1802 comment
.append
(": {ret}")
1804 compiler
.provide_declaration
(self.c_name
, "{sig};")
1806 v
.add_decl
("/* method {self} for {comment} */")
1807 v
.add_decl
("{sig} \{")
1809 frame
.returnvar
= v
.new_var
(ret
)
1811 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1813 var subret
= v
.call
(mmethoddef
, recv
, arguments
)
1815 assert subret
!= null
1816 v
.assign
(frame
.returnvar
.as(not null), subret
)
1819 v
.add
("{frame.returnlabel.as(not null)}:;")
1821 v
.add
("return {frame.returnvar.as(not null)};")
1824 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})"
1828 redef fun call
(v
, arguments
) do abort
1832 fun const_color
: String do return "COLOR_{c_name}"
1834 # C name of the instance type to use
1835 fun c_instance_name
: String do return c_name
1838 redef class MClassType
1839 redef fun c_instance_name
do return mclass
.c_instance_name
1843 # Extern classes use the C instance of kernel::Pointer
1844 fun c_instance_name
: String
1846 if kind
== extern_kind
then
1847 return "kernel__Pointer"
1852 redef class MProperty
1853 fun const_color
: String do return "COLOR_{c_name}"
1856 redef class MPropDef
1857 fun const_color
: String do return "COLOR_{c_name}"