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
)
99 compiler
.display_stats
102 self.toolcontext
.info
("*** END GENERATING C: {time1-time0} ***", 2)
103 write_and_make
(compiler
)
107 # Singleton that store the knowledge about the separate compilation process
108 class SeparateCompiler
109 super AbstractCompiler
111 redef type VISITOR: SeparateCompilerVisitor
113 # The result of the RTA (used to know live types and methods)
114 var runtime_type_analysis
: nullable RapidTypeAnalysis
116 private var undead_types
: Set[MType] = new HashSet[MType]
117 private var partial_types
: Set[MType] = new HashSet[MType]
118 private var live_unresolved_types
: Map[MClassDef, Set[MType]] = new HashMap[MClassDef, HashSet[MType]]
120 private var type_layout
: nullable Layout[MType]
121 private var resolution_layout
: nullable Layout[MType]
122 protected var method_layout
: nullable Layout[PropertyLayoutElement]
123 protected var attr_layout
: nullable Layout[MAttribute]
125 init(mainmodule
: MModule, mmbuilder
: ModelBuilder, runtime_type_analysis
: nullable RapidTypeAnalysis) do
126 super(mainmodule
, mmbuilder
)
127 var file
= new_file
("nit.common")
128 self.header
= new CodeWriter(file
)
129 self.runtime_type_analysis
= runtime_type_analysis
130 self.compile_box_kinds
133 redef fun compile_header_structs
do
134 self.header
.add_decl
("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
135 self.compile_header_attribute_structs
136 self.header
.add_decl
("struct class \{ int box_kind; nitmethod_t vft[]; \}; /* general C type representing a Nit class. */")
138 # With resolution_table_table, all live type resolution are stored in a big table: resolution_table
139 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. */")
140 self.header
.add_decl
("struct instance \{ const struct type *type; const struct class *class; nitattribute_t attrs[]; \}; /* general C type representing a Nit instance. */")
142 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
143 self.header
.add_decl
("struct types \{ int mask; const struct type *types[]; \}; /* a list types (used for vts, fts and unresolved lists). */")
145 self.header
.add_decl
("struct types \{ int dummy; const struct type *types[]; \}; /* a list types (used for vts, fts and unresolved lists). */")
148 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
149 self.header
.add_decl
("#define HASH(mask, id) ((mask)%(id))")
150 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
151 self.header
.add_decl
("#define HASH(mask, id) ((mask)&(id))")
154 self.header
.add_decl
("typedef struct instance val; /* general C type representing a Nit instance. */")
157 fun compile_header_attribute_structs
159 if modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
160 self.header
.add_decl
("typedef void* nitattribute_t; /* general C type representing a Nit attribute. */")
162 self.header
.add_decl
("typedef union \{")
163 self.header
.add_decl
("void* val;")
164 for c
, v
in self.box_kinds
do
165 var t
= c
.mclass_type
166 self.header
.add_decl
("{t.ctype} {t.ctypename};")
168 self.header
.add_decl
("\} nitattribute_t; /* general C type representing a Nit attribute. */")
172 fun compile_box_kinds
174 # Collect all bas box class
175 # FIXME: this is not completely fine with a separate compilation scheme
176 for classname
in ["Int", "Bool", "Char", "Float", "NativeString", "Pointer"] do
177 var classes
= self.mainmodule
.model
.get_mclasses_by_name
(classname
)
178 if classes
== null then continue
179 assert classes
.length
== 1 else print classes
.join
(", ")
180 self.box_kinds
[classes
.first
] = self.box_kinds
.length
+ 1
184 var box_kinds
= new HashMap[MClass, Int]
186 fun box_kind_of
(mclass
: MClass): Int
188 if mclass
.mclass_type
.ctype
== "val*" then
190 else if mclass
.kind
== extern_kind
then
191 return self.box_kinds
[self.mainmodule
.get_primitive_class
("Pointer")]
193 return self.box_kinds
[mclass
]
198 fun compile_color_consts
(colors
: Map[Object, Int]) do
200 for m
, c
in colors
do
201 compile_color_const
(v
, m
, c
)
205 fun compile_color_const
(v
: SeparateCompilerVisitor, m
: Object, color
: Int) do
206 if color_consts_done
.has
(m
) then return
207 if m
isa MProperty then
208 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
209 self.provide_declaration
(m
.const_color
, "#define {m.const_color} {color}")
211 self.provide_declaration
(m
.const_color
, "extern const int {m.const_color};")
212 v
.add
("const int {m.const_color} = {color};")
214 else if m
isa MPropDef then
215 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
216 self.provide_declaration
(m
.const_color
, "#define {m.const_color} {color}")
218 self.provide_declaration
(m
.const_color
, "extern const int {m.const_color};")
219 v
.add
("const int {m.const_color} = {color};")
221 else if m
isa MType then
222 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
223 self.provide_declaration
(m
.const_color
, "#define {m.const_color} {color}")
225 self.provide_declaration
(m
.const_color
, "extern const int {m.const_color};")
226 v
.add
("const int {m.const_color} = {color};")
229 color_consts_done
.add
(m
)
232 private var color_consts_done
= new HashSet[Object]
234 # colorize classe properties
235 fun do_property_coloring
do
236 var mclasses
= new HashSet[MClass].from
(modelbuilder
.model
.mclasses
)
239 var method_layout_builder
: PropertyLayoutBuilder[PropertyLayoutElement]
240 var attribute_layout_builder
: PropertyLayoutBuilder[MAttribute]
241 #FIXME PH and BM layouts too slow for large programs
242 #if modelbuilder.toolcontext.opt_bm_typing.value then
243 # method_layout_builder = new MMethodBMizer(self.mainmodule)
244 # attribute_layout_builder = new MAttributeBMizer(self.mainmodule)
245 #else if modelbuilder.toolcontext.opt_phmod_typing.value then
246 # method_layout_builder = new MMethodHasher(new PHModOperator, self.mainmodule)
247 # attribute_layout_builder = new MAttributeHasher(new PHModOperator, self.mainmodule)
248 #else if modelbuilder.toolcontext.opt_phand_typing.value then
249 # method_layout_builder = new MMethodHasher(new PHAndOperator, self.mainmodule)
250 # attribute_layout_builder = new MAttributeHasher(new PHAndOperator, self.mainmodule)
253 var class_layout_builder
= new MClassColorer(self.mainmodule
)
254 class_layout_builder
.build_layout
(mclasses
)
255 method_layout_builder
= new MPropertyColorer[PropertyLayoutElement](self.mainmodule
, class_layout_builder
)
256 attribute_layout_builder
= new MPropertyColorer[MAttribute](self.mainmodule
, class_layout_builder
)
259 # lookup properties to build layout with
260 var mmethods
= new HashMap[MClass, Set[PropertyLayoutElement]]
261 var mattributes
= new HashMap[MClass, Set[MAttribute]]
262 for mclass
in mclasses
do
263 mmethods
[mclass
] = new HashSet[PropertyLayoutElement]
264 mattributes
[mclass
] = new HashSet[MAttribute]
265 for mprop
in self.mainmodule
.properties
(mclass
) do
266 if mprop
isa MMethod then
267 mmethods
[mclass
].add
(mprop
)
268 else if mprop
isa MAttribute then
269 mattributes
[mclass
].add
(mprop
)
274 # lookup super calls and add it to the list of mmethods to build layout with
276 if runtime_type_analysis
!= null then
277 super_calls
= runtime_type_analysis
.live_super_sends
279 super_calls
= modelbuilder
.collect_super_sends
281 for mmethoddef
in super_calls
do
282 var mclass
= mmethoddef
.mclassdef
.mclass
283 mmethods
[mclass
].add
(mmethoddef
)
284 for descendant
in mclass
.in_hierarchy
(self.mainmodule
).smallers
do
285 mmethods
[descendant
].add
(mmethoddef
)
290 self.method_layout
= method_layout_builder
.build_layout
(mmethods
)
291 self.method_tables
= build_method_tables
(mclasses
, super_calls
)
292 self.compile_color_consts
(method_layout
.pos
)
294 # attribute null color to dead supercalls
295 for mmodule
in self.mainmodule
.in_importation
.greaters
do
296 for mclassdef
in mmodule
.mclassdefs
do
297 for mpropdef
in mclassdef
.mpropdefs
do
298 if mpropdef
.has_supercall
then
299 compile_color_const
(new_visitor
, mpropdef
, -1)
305 # attributes coloration
306 self.attr_layout
= attribute_layout_builder
.build_layout
(mattributes
)
307 self.attr_tables
= build_attr_tables
(mclasses
)
308 self.compile_color_consts
(attr_layout
.pos
)
311 fun build_method_tables
(mclasses
: Set[MClass], super_calls
: Set[MMethodDef]): Map[MClass, Array[nullable MPropDef]] do
312 var layout
= self.method_layout
313 var tables
= new HashMap[MClass, Array[nullable MPropDef]]
314 for mclass
in mclasses
do
315 var table
= new Array[nullable MPropDef]
316 var supercalls
= new List[MMethodDef]
318 # first, fill table from parents by reverse linearization order
319 var parents
= new Array[MClass]
320 if mainmodule
.flatten_mclass_hierarchy
.has
(mclass
) then
321 parents
= mclass
.in_hierarchy
(mainmodule
).greaters
.to_a
322 self.mainmodule
.linearize_mclasses
(parents
)
325 for parent
in parents
do
326 if parent
== mclass
then continue
327 for mproperty
in self.mainmodule
.properties
(parent
) do
328 if not mproperty
isa MMethod then continue
329 var color
= layout
.pos
[mproperty
]
330 if table
.length
<= color
then
331 for i
in [table
.length
.. color
[ do
335 for mpropdef
in mproperty
.mpropdefs
do
336 if mpropdef
.mclassdef
.mclass
== parent
then
337 table
[color
] = mpropdef
342 # lookup for super calls in super classes
343 for mmethoddef
in super_calls
do
344 for mclassdef
in parent
.mclassdefs
do
345 if mclassdef
.mpropdefs
.has
(mmethoddef
) then
346 supercalls
.add
(mmethoddef
)
352 # then override with local properties
353 for mproperty
in self.mainmodule
.properties
(mclass
) do
354 if not mproperty
isa MMethod then continue
355 var color
= layout
.pos
[mproperty
]
356 if table
.length
<= color
then
357 for i
in [table
.length
.. color
[ do
361 for mpropdef
in mproperty
.mpropdefs
do
362 if mpropdef
.mclassdef
.mclass
== mclass
then
363 table
[color
] = mpropdef
368 # lookup for super calls in local class
369 for mmethoddef
in super_calls
do
370 for mclassdef
in mclass
.mclassdefs
do
371 if mclassdef
.mpropdefs
.has
(mmethoddef
) then
372 supercalls
.add
(mmethoddef
)
376 # insert super calls in table according to receiver
377 for supercall
in supercalls
do
378 var color
= layout
.pos
[supercall
]
379 if table
.length
<= color
then
380 for i
in [table
.length
.. color
[ do
384 var mmethoddef
= supercall
.lookup_next_definition
(self.mainmodule
, mclass
.intro
.bound_mtype
)
385 table
[color
] = mmethoddef
387 tables
[mclass
] = table
392 fun build_attr_tables
(mclasses
: Set[MClass]): Map[MClass, Array[nullable MPropDef]] do
393 var layout
= self.attr_layout
394 var tables
= new HashMap[MClass, Array[nullable MPropDef]]
395 for mclass
in mclasses
do
396 var table
= new Array[nullable MPropDef]
397 # first, fill table from parents by reverse linearization order
398 var parents
= new Array[MClass]
399 if mainmodule
.flatten_mclass_hierarchy
.has
(mclass
) then
400 parents
= mclass
.in_hierarchy
(mainmodule
).greaters
.to_a
401 self.mainmodule
.linearize_mclasses
(parents
)
403 for parent
in parents
do
404 if parent
== mclass
then continue
405 for mproperty
in self.mainmodule
.properties
(parent
) do
406 if not mproperty
isa MAttribute then continue
407 var color
= layout
.pos
[mproperty
]
408 if table
.length
<= color
then
409 for i
in [table
.length
.. color
[ do
413 for mpropdef
in mproperty
.mpropdefs
do
414 if mpropdef
.mclassdef
.mclass
== parent
then
415 table
[color
] = mpropdef
421 # then override with local properties
422 for mproperty
in self.mainmodule
.properties
(mclass
) do
423 if not mproperty
isa MAttribute then continue
424 var color
= layout
.pos
[mproperty
]
425 if table
.length
<= color
then
426 for i
in [table
.length
.. color
[ do
430 for mpropdef
in mproperty
.mpropdefs
do
431 if mpropdef
.mclassdef
.mclass
== mclass
then
432 table
[color
] = mpropdef
436 tables
[mclass
] = table
441 # colorize live types of the program
442 private fun do_type_coloring
: POSet[MType] do
443 var mtypes
= new HashSet[MType]
444 mtypes
.add_all
(self.runtime_type_analysis
.live_types
)
445 mtypes
.add_all
(self.runtime_type_analysis
.live_cast_types
)
446 mtypes
.add_all
(self.undead_types
)
447 for c
in self.box_kinds
.keys
do
448 mtypes
.add
(c
.mclass_type
)
451 for mtype
in mtypes
do
452 retrieve_partial_types
(mtype
)
454 mtypes
.add_all
(self.partial_types
)
457 var layout_builder
: TypingLayoutBuilder[MType]
458 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
459 layout_builder
= new MTypeBMizer(self.mainmodule
)
460 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
461 layout_builder
= new MTypeHasher(new PHModOperator, self.mainmodule
)
462 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
463 layout_builder
= new MTypeHasher(new PHAndOperator, self.mainmodule
)
465 layout_builder
= new MTypeColorer(self.mainmodule
)
469 self.type_layout
= layout_builder
.build_layout
(mtypes
)
470 var poset
= layout_builder
.poset
.as(not null)
471 self.type_tables
= self.build_type_tables
(poset
)
473 # VT and FT are stored with other unresolved types in the big resolution_tables
474 self.compile_resolution_tables
(mtypes
)
480 fun build_type_tables
(mtypes
: POSet[MType]): Map[MType, Array[nullable MType]] do
481 var tables
= new HashMap[MType, Array[nullable MType]]
482 var layout
= self.type_layout
483 for mtype
in mtypes
do
484 var table
= new Array[nullable MType]
485 for sup
in mtypes
[mtype
].greaters
do
487 if layout
isa PHLayout[MType, MType] then
488 color
= layout
.hashes
[mtype
][sup
]
490 color
= layout
.pos
[sup
]
492 if table
.length
<= color
then
493 for i
in [table
.length
.. color
[ do
499 tables
[mtype
] = table
504 protected fun compile_resolution_tables
(mtypes
: Set[MType]) do
505 # resolution_tables is used to perform a type resolution at runtime in O(1)
507 # During the visit of the body of classes, live_unresolved_types are collected
509 # Collect all live_unresolved_types (visited in the body of classes)
511 # Determinate fo each livetype what are its possible requested anchored types
512 var mtype2unresolved
= new HashMap[MClassType, Set[MType]]
513 for mtype
in self.runtime_type_analysis
.live_types
do
514 var set
= new HashSet[MType]
515 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
516 if self.live_unresolved_types
.has_key
(cd
) then
517 set
.add_all
(self.live_unresolved_types
[cd
])
520 mtype2unresolved
[mtype
] = set
523 # Compute the table layout with the prefered method
524 var resolution_builder
: ResolutionLayoutBuilder
525 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
526 resolution_builder
= new ResolutionBMizer
527 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
528 resolution_builder
= new ResolutionHasher(new PHModOperator)
529 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
530 resolution_builder
= new ResolutionHasher(new PHAndOperator)
532 resolution_builder
= new ResolutionColorer
534 self.resolution_layout
= resolution_builder
.build_layout
(mtype2unresolved
)
535 self.resolution_tables
= self.build_resolution_tables
(mtype2unresolved
)
537 # Compile a C constant for each collected unresolved type.
538 # Either to a color, or to -1 if the unresolved type is dead (no live receiver can require it)
539 var all_unresolved
= new HashSet[MType]
540 for t
in self.live_unresolved_types
.values
do
541 all_unresolved
.add_all
(t
)
543 var all_unresolved_types_colors
= new HashMap[MType, Int]
544 for t
in all_unresolved
do
545 if self.resolution_layout
.pos
.has_key
(t
) then
546 all_unresolved_types_colors
[t
] = self.resolution_layout
.pos
[t
]
548 all_unresolved_types_colors
[t
] = -1
551 self.compile_color_consts
(all_unresolved_types_colors
)
554 #for k, v in unresolved_types_tables.as(not null) do
555 # print "{k}: {v.join(", ")}"
560 fun build_resolution_tables
(elements
: Map[MClassType, Set[MType]]): Map[MClassType, Array[nullable MType]] do
561 var tables
= new HashMap[MClassType, Array[nullable MType]]
562 var layout
= self.resolution_layout
563 for mclasstype
, mtypes
in elements
do
564 var table
= new Array[nullable MType]
565 for mtype
in mtypes
do
567 if layout
isa PHLayout[MClassType, MType] then
568 color
= layout
.hashes
[mclasstype
][mtype
]
570 color
= layout
.pos
[mtype
]
572 if table
.length
<= color
then
573 for i
in [table
.length
.. color
[ do
579 tables
[mclasstype
] = table
584 fun retrieve_partial_types
(mtype
: MType) do
585 # add formal types arguments to mtypes
586 if mtype
isa MGenericType then
587 for ft
in mtype
.arguments
do
588 if ft
.need_anchor
then
589 print
("Why do we need anchor here ?")
592 self.partial_types
.add
(ft
)
593 retrieve_partial_types
(ft
)
596 var mclass_type
: MClassType
597 if mtype
isa MNullableType then
598 mclass_type
= mtype
.mtype
.as(MClassType)
600 mclass_type
= mtype
.as(MClassType)
603 # add virtual types to mtypes
604 for vt
in self.mainmodule
.properties
(mclass_type
.mclass
) do
605 if vt
isa MVirtualTypeProp then
606 var anchored
= vt
.mvirtualtype
.lookup_bound
(self.mainmodule
, mclass_type
).anchor_to
(self.mainmodule
, mclass_type
)
607 self.partial_types
.add
(anchored
)
612 # Separately compile all the method definitions of the module
613 fun compile_module_to_c
(mmodule
: MModule)
615 var old_module
= self.mainmodule
616 self.mainmodule
= mmodule
617 for cd
in mmodule
.mclassdefs
do
618 for pd
in cd
.mpropdefs
do
619 if not pd
isa MMethodDef then continue
620 #print "compile {pd} @ {cd} @ {mmodule}"
621 var r
= pd
.separate_runtime_function
623 var r2
= pd
.virtual_runtime_function
624 r2
.compile_to_c
(self)
627 self.mainmodule
= old_module
630 # Globaly compile the type structure of a live type
631 fun compile_type_to_c
(mtype
: MType)
633 var c_name
= mtype
.c_name
634 var v
= new SeparateCompilerVisitor(self)
635 v
.add_decl
("/* runtime type {mtype} */")
637 # extern const struct type_X
638 self.provide_declaration
("type_{c_name}", "extern const struct type type_{c_name};")
640 # const struct type_X
641 v
.add_decl
("const struct type type_{c_name} = \{")
642 v
.add_decl
("{self.type_layout.ids[mtype]},")
643 v
.add_decl
("\"{mtype}\
", /* class_name_string */")
644 var layout
= self.type_layout
645 if layout
isa PHLayout[MType, MType] then
646 v
.add_decl
("{layout.masks[mtype]},")
648 v
.add_decl
("{layout.pos[mtype]},")
650 if mtype
isa MNullableType then
655 if compile_type_resolution_table
(mtype
) then
656 v
.require_declaration
("resolution_table_{c_name}")
657 v
.add_decl
("&resolution_table_{c_name},")
661 v
.add_decl
("{self.type_tables[mtype].length},")
663 for stype
in self.type_tables
[mtype
] do
664 if stype
== null then
665 v
.add_decl
("-1, /* empty */")
667 v
.add_decl
("{self.type_layout.ids[stype]}, /* {stype} */")
674 fun compile_type_resolution_table
(mtype
: MType): Bool do
676 var mclass_type
: MClassType
677 if mtype
isa MNullableType then
678 mclass_type
= mtype
.mtype
.as(MClassType)
680 mclass_type
= mtype
.as(MClassType)
682 if not self.resolution_tables
.has_key
(mclass_type
) then return false
684 var layout
= self.resolution_layout
686 # extern const struct resolution_table_X resolution_table_X
687 self.provide_declaration
("resolution_table_{mtype.c_name}", "extern const struct types resolution_table_{mtype.c_name};")
689 # const struct fts_table_X fts_table_X
691 v
.add_decl
("const struct types resolution_table_{mtype.c_name} = \{")
692 if layout
isa PHLayout[MClassType, MType] then
693 v
.add_decl
("{layout.masks[mclass_type]},")
695 v
.add_decl
("0, /* dummy */")
698 for t
in self.resolution_tables
[mclass_type
] do
700 v
.add_decl
("NULL, /* empty */")
702 # The table stores the result of the type resolution
703 # Therefore, for a receiver `mclass_type`, and a unresolved type `t`
704 # the value stored is tv.
705 var tv
= t
.resolve_for
(mclass_type
, mclass_type
, self.mainmodule
, true)
706 # FIXME: What typeids means here? How can a tv not be live?
707 if self.type_layout
.ids
.has_key
(tv
) then
708 v
.require_declaration
("type_{tv.c_name}")
709 v
.add_decl
("&type_{tv.c_name}, /* {t}: {tv} */")
711 v
.add_decl
("NULL, /* empty ({t}: {tv} not a live type) */")
720 # Globally compile the table of the class mclass
721 # In a link-time optimisation compiler, tables are globally computed
722 # In a true separate compiler (a with dynamic loading) you cannot do this unfortnally
723 fun compile_class_to_c
(mclass
: MClass)
725 var mtype
= mclass
.intro
.bound_mtype
726 var c_name
= mclass
.c_name
728 var vft
= self.method_tables
[mclass
]
729 var attrs
= self.attr_tables
[mclass
]
732 var is_dead
= runtime_type_analysis
!= null and not runtime_type_analysis
.live_classes
.has
(mclass
) and mtype
.ctype
== "val*" and mclass
.name
!= "NativeArray"
734 v
.add_decl
("/* runtime class {c_name} */")
738 self.provide_declaration
("class_{c_name}", "extern const struct class class_{c_name};")
739 v
.add_decl
("const struct class class_{c_name} = \{")
740 v
.add_decl
("{self.box_kind_of(mclass)}, /* box_kind */")
742 for i
in [0 .. vft
.length
[ do
743 var mpropdef
= vft
[i
]
744 if mpropdef
== null then
745 v
.add_decl
("NULL, /* empty */")
747 assert mpropdef
isa MMethodDef
748 var rf
= mpropdef
.virtual_runtime_function
749 v
.require_declaration
(rf
.c_name
)
750 v
.add_decl
("(nitmethod_t){rf.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
757 if mtype
.ctype
!= "val*" then
758 #Build instance struct
759 self.header
.add_decl
("struct instance_{c_name} \{")
760 self.header
.add_decl
("const struct type *type;")
761 self.header
.add_decl
("const struct class *class;")
762 self.header
.add_decl
("{mtype.ctype} value;")
763 self.header
.add_decl
("\};")
765 if not self.runtime_type_analysis
.live_types
.has
(mtype
) then return
768 self.header
.add_decl
("val* BOX_{c_name}({mtype.ctype});")
769 v
.add_decl
("/* allocate {mtype} */")
770 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
771 v
.add
("struct instance_{c_name}*res = nit_alloc(sizeof(struct instance_{c_name}));")
772 v
.require_declaration
("type_{c_name}")
773 v
.add
("res->type = &type_{c_name};")
774 v
.require_declaration
("class_{c_name}")
775 v
.add
("res->class = &class_{c_name};")
776 v
.add
("res->value = value;")
777 v
.add
("return (val*)res;")
780 else if mclass
.name
== "NativeArray" then
781 #Build instance struct
782 self.header
.add_decl
("struct instance_{c_name} \{")
783 self.header
.add_decl
("const struct type *type;")
784 self.header
.add_decl
("const struct class *class;")
785 # NativeArrays are just a instance header followed by an array of values
786 self.header
.add_decl
("val* values[0];")
787 self.header
.add_decl
("\};")
790 self.provide_declaration
("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(int length, const struct type* type);")
791 v
.add_decl
("/* allocate {mtype} */")
792 v
.add_decl
("{mtype.ctype} NEW_{c_name}(int length, const struct type* type) \{")
793 var res
= v
.new_named_var
(mtype
, "self")
795 var mtype_elt
= mtype
.arguments
.first
796 v
.add
("{res} = nit_alloc(sizeof(struct instance_{c_name}) + length*sizeof({mtype_elt.ctype}));")
797 v
.add
("{res}->type = type;")
798 hardening_live_type
(v
, "type")
799 v
.require_declaration
("class_{c_name}")
800 v
.add
("{res}->class = &class_{c_name};")
801 v
.add
("return {res};")
807 self.provide_declaration
("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(const struct type* type);")
808 v
.add_decl
("/* allocate {mtype} */")
809 v
.add_decl
("{mtype.ctype} NEW_{c_name}(const struct type* type) \{")
811 v
.add_abort
("{mclass} is DEAD")
813 var res
= v
.new_named_var
(mtype
, "self")
815 v
.add
("{res} = nit_alloc(sizeof(struct instance) + {attrs.length}*sizeof(nitattribute_t));")
816 v
.add
("{res}->type = type;")
817 hardening_live_type
(v
, "type")
818 v
.require_declaration
("class_{c_name}")
819 v
.add
("{res}->class = &class_{c_name};")
820 self.generate_init_attr
(v
, res
, mtype
)
821 v
.add
("return {res};")
826 # Add a dynamic test to ensure that the type referenced by `t` is a live type
827 fun hardening_live_type
(v
: VISITOR, t
: String)
829 if not v
.compiler
.modelbuilder
.toolcontext
.opt_hardening
.value
then return
830 v
.add
("if({t} == NULL) \{")
831 v
.add_abort
("type null")
833 v
.add
("if({t}->resolution_table == NULL) \{")
834 v
.add
("fprintf(stderr, \"Insantiation of a dead
type: %s\\n\
", {t}->name);")
835 v
.add_abort
("type dead")
839 redef fun new_visitor
do return new SeparateCompilerVisitor(self)
843 private var type_tables
: Map[MType, Array[nullable MType]] = new HashMap[MType, Array[nullable MType]]
844 private var resolution_tables
: Map[MClassType, Array[nullable MType]] = new HashMap[MClassType, Array[nullable MType]]
845 protected var method_tables
: Map[MClass, Array[nullable MPropDef]] = new HashMap[MClass, Array[nullable MPropDef]]
846 protected var attr_tables
: Map[MClass, Array[nullable MPropDef]] = new HashMap[MClass, Array[nullable MPropDef]]
848 redef fun display_stats
851 if self.modelbuilder
.toolcontext
.opt_tables_metrics
.value
then
858 print
"# size of subtyping tables"
859 print
"\ttotal \tholes"
862 for t
, table
in type_tables
do
863 total
+= table
.length
864 for e
in table
do if e
== null then holes
+= 1
866 print
"\t{total}\t{holes}"
868 print
"# size of resolution tables"
869 print
"\ttotal \tholes"
872 for t
, table
in resolution_tables
do
873 total
+= table
.length
874 for e
in table
do if e
== null then holes
+= 1
876 print
"\t{total}\t{holes}"
878 print
"# size of methods tables"
879 print
"\ttotal \tholes"
882 for t
, table
in method_tables
do
883 total
+= table
.length
884 for e
in table
do if e
== null then holes
+= 1
886 print
"\t{total}\t{holes}"
888 print
"# size of attributes tables"
889 print
"\ttotal \tholes"
892 for t
, table
in attr_tables
do
893 total
+= table
.length
894 for e
in table
do if e
== null then holes
+= 1
896 print
"\t{total}\t{holes}"
899 redef fun compile_nitni_structs
901 self.header
.add_decl
("struct nitni_instance \{struct instance *value;\};")
904 redef fun finalize_ffi_for_module
(nmodule
)
906 var old_module
= self.mainmodule
907 self.mainmodule
= nmodule
.mmodule
.as(not null)
909 self.mainmodule
= old_module
913 # A visitor on the AST of property definition that generate the C code of a separate compilation process.
914 class SeparateCompilerVisitor
915 super AbstractCompilerVisitor
917 redef type COMPILER: SeparateCompiler
919 redef fun adapt_signature
(m
, args
)
921 var msignature
= m
.msignature
.resolve_for
(m
.mclassdef
.bound_mtype
, m
.mclassdef
.bound_mtype
, m
.mclassdef
.mmodule
, true)
922 var recv
= args
.first
923 if recv
.mtype
.ctype
!= m
.mclassdef
.mclass
.mclass_type
.ctype
then
924 args
.first
= self.autobox
(args
.first
, m
.mclassdef
.mclass
.mclass_type
)
926 for i
in [0..msignature
.arity
[ do
927 var t
= msignature
.mparameters
[i
].mtype
928 if i
== msignature
.vararg_rank
then
931 args
[i
+1] = self.autobox
(args
[i
+1], t
)
935 redef fun autobox
(value
, mtype
)
937 if value
.mtype
== mtype
then
939 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
941 else if value
.mtype
.ctype
== "val*" then
942 return self.new_expr
("((struct instance_{mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
943 else if mtype
.ctype
== "val*" then
944 var valtype
= value
.mtype
.as(MClassType)
945 var res
= self.new_var
(mtype
)
946 if compiler
.runtime_type_analysis
!= null and not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
947 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
948 self.add
("printf(\"Dead code executed
!\\n\
"); show_backtrace(1);")
951 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
953 else if value
.mtype
.cname_blind
== "void*" and mtype
.cname_blind
== "void*" then
956 # Bad things will appen!
957 var res
= self.new_var
(mtype
)
958 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
959 self.add
("printf(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); show_backtrace(1);")
964 # Return a C expression returning the runtime type structure of the value
965 # The point of the method is to works also with primitives types.
966 fun type_info
(value
: RuntimeVariable): String
968 if value
.mtype
.ctype
== "val*" then
969 return "{value}->type"
971 self.require_declaration
("type_{value.mtype.c_name}")
972 return "(&type_{value.mtype.c_name})"
976 redef fun send
(mmethod
, arguments
)
978 self.varargize
(mmethod
.intro
, mmethod
.intro
.msignature
.as(not null), arguments
)
980 if arguments
.first
.mcasttype
.ctype
!= "val*" then
981 # In order to shortcut the primitive, we need to find the most specific method
982 # Howverr, because of performance (no flattening), we always work on the realmainmodule
983 var m
= self.compiler
.mainmodule
984 self.compiler
.mainmodule
= self.compiler
.realmainmodule
985 var res
= self.monomorphic_send
(mmethod
, arguments
.first
.mcasttype
, arguments
)
986 self.compiler
.mainmodule
= m
990 return table_send
(mmethod
, arguments
, mmethod
.const_color
)
993 private fun table_send
(mmethod
: MMethod, arguments
: Array[RuntimeVariable], const_color
: String): nullable RuntimeVariable
995 assert arguments
.length
== mmethod
.intro
.msignature
.arity
+ 1 else debug
("Invalid arity for {mmethod}. {arguments.length} arguments given.")
997 var res
: nullable RuntimeVariable
998 var msignature
= mmethod
.intro
.msignature
.resolve_for
(mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.mmodule
, true)
999 var ret
= msignature
.return_mtype
1000 if mmethod
.is_new
then
1001 ret
= arguments
.first
.mtype
1002 res
= self.new_var
(ret
)
1003 else if ret
== null then
1006 res
= self.new_var
(ret
)
1012 var recv
= arguments
.first
1015 for i
in [0..msignature
.arity
[ do
1016 var a
= arguments
[i
+1]
1017 var t
= msignature
.mparameters
[i
].mtype
1018 if i
== msignature
.vararg_rank
then
1019 t
= arguments
[i
+1].mcasttype
1021 s
.append
(", {t.ctype}")
1022 a
= self.autobox
(a
, t
)
1026 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
or mmethod
.name
== "==" or mmethod
.name
== "!="
1027 var maybenull
= recv
.mcasttype
isa MNullableType and consider_null
1029 self.add
("if ({recv} == NULL) \{")
1030 if mmethod
.name
== "==" then
1032 var arg
= arguments
[1]
1033 if arg
.mcasttype
isa MNullableType then
1034 self.add
("{res} = ({arg} == NULL);")
1035 else if arg
.mcasttype
isa MNullType then
1036 self.add
("{res} = 1; /* is null */")
1038 self.add
("{res} = 0; /* {arg.inspect} cannot be null */")
1040 else if mmethod
.name
== "!=" then
1042 var arg
= arguments
[1]
1043 if arg
.mcasttype
isa MNullableType then
1044 self.add
("{res} = ({arg} != NULL);")
1045 else if arg
.mcasttype
isa MNullType then
1046 self.add
("{res} = 0; /* is null */")
1048 self.add
("{res} = 1; /* {arg.inspect} cannot be null */")
1051 self.add_abort
("Receiver is null")
1053 self.add
("\} else \{")
1055 if not self.compiler
.modelbuilder
.toolcontext
.opt_no_shortcut_equate
.value
and (mmethod
.name
== "==" or mmethod
.name
== "!=") then
1057 # Recv is not null, thus is arg is, it is easy to conclude (and respect the invariants)
1058 var arg
= arguments
[1]
1059 if arg
.mcasttype
isa MNullType then
1060 if mmethod
.name
== "==" then
1061 self.add
("{res} = 0; /* arg is null but recv is not */")
1063 self.add
("{res} = 1; /* arg is null and recv is not */")
1073 if ret
== null then r
= "void" else r
= ret
.ctype
1074 self.require_declaration
(const_color
)
1075 var call
= "(({r} (*)({s}))({arguments.first}->class->vft[{const_color}]))({ss}) /* {mmethod} on {arguments.first.inspect}*/"
1078 self.add
("{res} = {call};")
1090 redef fun call
(mmethoddef
, recvtype
, arguments
)
1092 assert arguments
.length
== mmethoddef
.msignature
.arity
+ 1 else debug
("Invalid arity for {mmethoddef}. {arguments.length} arguments given.")
1094 var res
: nullable RuntimeVariable
1095 var ret
= mmethoddef
.msignature
.return_mtype
1096 if mmethoddef
.mproperty
.is_new
then
1097 ret
= arguments
.first
.mtype
1098 res
= self.new_var
(ret
)
1099 else if ret
== null then
1102 ret
= ret
.resolve_for
(mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.mmodule
, true)
1103 res
= self.new_var
(ret
)
1106 if self.compiler
.modelbuilder
.mpropdef2npropdef
.has_key
(mmethoddef
) and
1107 self.compiler
.modelbuilder
.mpropdef2npropdef
[mmethoddef
] isa AInternMethPropdef and
1108 not compiler
.modelbuilder
.toolcontext
.opt_no_inline_intern
.value
then
1109 var frame
= new Frame(self, mmethoddef
, recvtype
, arguments
)
1110 frame
.returnlabel
= self.get_name
("RET_LABEL")
1111 frame
.returnvar
= res
1112 var old_frame
= self.frame
1114 self.add
("\{ /* Inline {mmethoddef} ({arguments.join(",")}) */")
1115 mmethoddef
.compile_inside_to_c
(self, arguments
)
1116 self.add
("{frame.returnlabel.as(not null)}:(void)0;")
1118 self.frame
= old_frame
1123 self.adapt_signature
(mmethoddef
, arguments
)
1125 self.require_declaration
(mmethoddef
.c_name
)
1127 self.add
("{mmethoddef.c_name}({arguments.join(", ")});")
1130 self.add
("{res} = {mmethoddef.c_name}({arguments.join(", ")});")
1136 redef fun supercall
(m
: MMethodDef, recvtype
: MClassType, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
1138 if arguments
.first
.mcasttype
.ctype
!= "val*" then
1139 # In order to shortcut the primitive, we need to find the most specific method
1140 # However, because of performance (no flattening), we always work on the realmainmodule
1141 var main
= self.compiler
.mainmodule
1142 self.compiler
.mainmodule
= self.compiler
.realmainmodule
1143 var res
= self.monomorphic_super_send
(m
, recvtype
, arguments
)
1144 self.compiler
.mainmodule
= main
1147 return table_send
(m
.mproperty
, arguments
, m
.const_color
)
1150 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
1152 # A vararg must be stored into an new array
1153 # The trick is that the dymaic type of the array may depends on the receiver
1154 # of the method (ie recv) if the static type is unresolved
1155 # This is more complex than usual because the unresolved type must not be resolved
1156 # with the current receiver (ie self).
1157 # Therefore to isolate the resolution from self, a local Frame is created.
1158 # One can see this implementation as an inlined method of the receiver whose only
1159 # job is to allocate the array
1160 var old_frame
= self.frame
1161 var frame
= new Frame(self, mpropdef
, mpropdef
.mclassdef
.bound_mtype
, [recv
])
1163 #print "required Array[{elttype}] for recv {recv.inspect}. bound=Array[{self.resolve_for(elttype, recv)}]. selfvar={frame.arguments.first.inspect}"
1164 var res
= self.array_instance
(varargs
, elttype
)
1165 self.frame
= old_frame
1169 redef fun isset_attribute
(a
, recv
)
1171 self.check_recv_notnull
(recv
)
1172 var res
= self.new_var
(bool_type
)
1174 # What is the declared type of the attribute?
1175 var mtype
= a
.intro
.static_mtype
.as(not null)
1176 var intromclassdef
= a
.intro
.mclassdef
1177 mtype
= mtype
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1179 if mtype
isa MNullableType then
1180 self.add
("{res} = 1; /* easy isset: {a} on {recv.inspect} */")
1184 self.require_declaration
(a
.const_color
)
1185 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1186 self.add
("{res} = {recv}->attrs[{a.const_color}] != NULL; /* {a} on {recv.inspect}*/")
1189 if mtype
.ctype
== "val*" then
1190 self.add
("{res} = {recv}->attrs[{a.const_color}].val != NULL; /* {a} on {recv.inspect} */")
1192 self.add
("{res} = 1; /* NOT YET IMPLEMENTED: isset of primitives: {a} on {recv.inspect} */")
1198 redef fun read_attribute
(a
, recv
)
1200 self.check_recv_notnull
(recv
)
1202 # What is the declared type of the attribute?
1203 var ret
= a
.intro
.static_mtype
.as(not null)
1204 var intromclassdef
= a
.intro
.mclassdef
1205 ret
= ret
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1207 self.require_declaration
(a
.const_color
)
1208 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1209 # Get the attribute or a box (ie. always a val*)
1210 var cret
= self.object_type
.as_nullable
1211 var res
= self.new_var
(cret
)
1214 self.add
("{res} = {recv}->attrs[{a.const_color}]; /* {a} on {recv.inspect} */")
1216 # Check for Uninitialized attribute
1217 if not ret
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then
1218 self.add
("if ({res} == NULL) \{")
1219 self.add_abort
("Uninitialized attribute {a.name}")
1223 # Return the attribute or its unboxed version
1224 # Note: it is mandatory since we reuse the box on write, we do not whant that the box escapes
1225 return self.autobox
(res
, ret
)
1227 var res
= self.new_var
(ret
)
1228 self.add
("{res} = {recv}->attrs[{a.const_color}].{ret.ctypename}; /* {a} on {recv.inspect} */")
1230 # Check for Uninitialized attribute
1231 if ret
.ctype
== "val*" and not ret
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then
1232 self.add
("if ({res} == NULL) \{")
1233 self.add_abort
("Uninitialized attribute {a.name}")
1241 redef fun write_attribute
(a
, recv
, value
)
1243 self.check_recv_notnull
(recv
)
1245 # What is the declared type of the attribute?
1246 var mtype
= a
.intro
.static_mtype
.as(not null)
1247 var intromclassdef
= a
.intro
.mclassdef
1248 mtype
= mtype
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1250 # Adapt the value to the declared type
1251 value
= self.autobox
(value
, mtype
)
1253 self.require_declaration
(a
.const_color
)
1254 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1255 var attr
= "{recv}->attrs[{a.const_color}]"
1256 if mtype
.ctype
!= "val*" then
1257 assert mtype
isa MClassType
1258 # The attribute is primitive, thus we store it in a box
1259 # The trick is to create the box the first time then resuse the box
1260 self.add
("if ({attr} != NULL) \{")
1261 self.add
("((struct instance_{mtype.c_name}*){attr})->value = {value}; /* {a} on {recv.inspect} */")
1262 self.add
("\} else \{")
1263 value
= self.autobox
(value
, self.object_type
.as_nullable
)
1264 self.add
("{attr} = {value}; /* {a} on {recv.inspect} */")
1267 # The attribute is not primitive, thus store it direclty
1268 self.add
("{attr} = {value}; /* {a} on {recv.inspect} */")
1271 self.add
("{recv}->attrs[{a.const_color}].{mtype.ctypename} = {value}; /* {a} on {recv.inspect} */")
1275 redef fun init_instance
(mtype
)
1277 self.require_declaration
("NEW_{mtype.mclass.c_name}")
1278 var compiler
= self.compiler
1279 if mtype
isa MGenericType and mtype
.need_anchor
then
1280 link_unresolved_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1281 var recv
= self.frame
.arguments
.first
1282 var recv_type_info
= self.type_info
(recv
)
1283 self.require_declaration
(mtype
.const_color
)
1284 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1285 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
)
1287 return self.new_expr
("NEW_{mtype.mclass.c_name}({recv_type_info}->resolution_table->types[{mtype.const_color}])", mtype
)
1290 compiler
.undead_types
.add
(mtype
)
1291 self.require_declaration
("type_{mtype.c_name}")
1292 return self.new_expr
("NEW_{mtype.mclass.c_name}(&type_{mtype.c_name})", mtype
)
1295 redef fun type_test
(value
, mtype
, tag
)
1297 self.add
("/* {value.inspect} isa {mtype} */")
1298 var compiler
= self.compiler
1300 var recv
= self.frame
.arguments
.first
1301 var recv_type_info
= self.type_info
(recv
)
1303 var res
= self.new_var
(bool_type
)
1305 var cltype
= self.get_name
("cltype")
1306 self.add_decl
("int {cltype};")
1307 var idtype
= self.get_name
("idtype")
1308 self.add_decl
("int {idtype};")
1310 var maybe_null
= self.maybe_null
(value
)
1311 var accept_null
= "0"
1313 if ntype
isa MNullableType then
1318 if value
.mcasttype
.is_subtype
(self.frame
.mpropdef
.mclassdef
.mmodule
, self.frame
.mpropdef
.mclassdef
.bound_mtype
, mtype
) then
1319 self.add
("{res} = 1; /* easy {value.inspect} isa {mtype}*/")
1320 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1321 self.compiler
.count_type_test_skipped
[tag
] += 1
1322 self.add
("count_type_test_skipped_{tag}++;")
1327 if ntype
.need_anchor
then
1328 var type_struct
= self.get_name
("type_struct")
1329 self.add_decl
("const struct type* {type_struct};")
1331 # Either with resolution_table with a direct resolution
1332 link_unresolved_type
(self.frame
.mpropdef
.mclassdef
, ntype
)
1333 self.require_declaration
(ntype
.const_color
)
1334 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1335 self.add
("{type_struct} = {recv_type_info}->resolution_table->types[HASH({recv_type_info}->resolution_table->mask, {ntype.const_color})];")
1337 self.add
("{type_struct} = {recv_type_info}->resolution_table->types[{ntype.const_color}];")
1339 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1340 self.compiler
.count_type_test_unresolved
[tag
] += 1
1341 self.add
("count_type_test_unresolved_{tag}++;")
1343 self.add
("{cltype} = {type_struct}->color;")
1344 self.add
("{idtype} = {type_struct}->id;")
1345 if maybe_null
and accept_null
== "0" then
1346 var is_nullable
= self.get_name
("is_nullable")
1347 self.add_decl
("short int {is_nullable};")
1348 self.add
("{is_nullable} = {type_struct}->is_nullable;")
1349 accept_null
= is_nullable
.to_s
1351 else if ntype
isa MClassType then
1352 compiler
.undead_types
.add
(mtype
)
1353 self.require_declaration
("type_{mtype.c_name}")
1354 self.add
("{cltype} = type_{mtype.c_name}.color;")
1355 self.add
("{idtype} = type_{mtype.c_name}.id;")
1356 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1357 self.compiler
.count_type_test_resolved
[tag
] += 1
1358 self.add
("count_type_test_resolved_{tag}++;")
1361 self.add
("printf(\"NOT YET IMPLEMENTED: type_test
(%s
, {mtype}).\\n\
", \"{value.inspect}\
"); show_backtrace(1);")
1364 # check color is in table
1366 self.add
("if({value} == NULL) \{")
1367 self.add
("{res} = {accept_null};")
1368 self.add
("\} else \{")
1370 var value_type_info
= self.type_info
(value
)
1371 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1372 self.add
("{cltype} = HASH({value_type_info}->color, {idtype});")
1374 self.add
("if({cltype} >= {value_type_info}->table_size) \{")
1375 self.add
("{res} = 0;")
1376 self.add
("\} else \{")
1377 self.add
("{res} = {value_type_info}->type_table[{cltype}] == {idtype};")
1386 redef fun is_same_type_test
(value1
, value2
)
1388 var res
= self.new_var
(bool_type
)
1389 # Swap values to be symetric
1390 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1395 if value1
.mtype
.ctype
!= "val*" then
1396 if value2
.mtype
== value1
.mtype
then
1397 self.add
("{res} = 1; /* is_same_type_test: compatible types {value1.mtype} vs. {value2.mtype} */")
1398 else if value2
.mtype
.ctype
!= "val*" then
1399 self.add
("{res} = 0; /* is_same_type_test: incompatible types {value1.mtype} vs. {value2.mtype}*/")
1401 var mtype1
= value1
.mtype
.as(MClassType)
1402 self.require_declaration
("class_{mtype1.c_name}")
1403 self.add
("{res} = ({value2} != NULL) && ({value2}->class == &class_{mtype1.c_name}); /* is_same_type_test */")
1406 self.add
("{res} = ({value1} == {value2}) || ({value1} != NULL && {value2} != NULL && {value1}->class == {value2}->class); /* is_same_type_test */")
1411 redef fun class_name_string
(value
)
1413 var res
= self.get_name
("var_class_name")
1414 self.add_decl
("const char* {res};")
1415 if value
.mtype
.ctype
== "val*" then
1416 self.add
"{res} = {value} == NULL ? \"null\
" : {value}->type->name;"
1417 else if value
.mtype
isa MClassType and value
.mtype
.as(MClassType).mclass
.kind
== extern_kind
then
1418 self.add
"{res} = \"{value.mtype.as(MClassType).mclass}\
";"
1420 self.require_declaration
("type_{value.mtype.c_name}")
1421 self.add
"{res} = type_{value.mtype.c_name}.name;"
1426 redef fun equal_test
(value1
, value2
)
1428 var res
= self.new_var
(bool_type
)
1429 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1434 if value1
.mtype
.ctype
!= "val*" then
1435 if value2
.mtype
== value1
.mtype
then
1436 self.add
("{res} = {value1} == {value2};")
1437 else if value2
.mtype
.ctype
!= "val*" then
1438 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
1440 var mtype1
= value1
.mtype
.as(MClassType)
1441 self.require_declaration
("class_{mtype1.c_name}")
1442 self.add
("{res} = ({value2} != NULL) && ({value2}->class == &class_{mtype1.c_name});")
1443 self.add
("if ({res}) \{")
1444 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
1449 var maybe_null
= true
1450 var test
= new Array[String]
1451 var t1
= value1
.mcasttype
1452 if t1
isa MNullableType then
1453 test
.add
("{value1} != NULL")
1458 var t2
= value2
.mcasttype
1459 if t2
isa MNullableType then
1460 test
.add
("{value2} != NULL")
1466 var incompatible
= false
1468 if t1
.ctype
!= "val*" then
1471 # No need to compare class
1472 else if t2
.ctype
!= "val*" then
1474 else if can_be_primitive
(value2
) then
1475 test
.add
("{value1}->class == {value2}->class")
1479 else if t2
.ctype
!= "val*" then
1481 if can_be_primitive
(value1
) then
1482 test
.add
("{value1}->class == {value2}->class")
1490 if incompatible
then
1492 self.add
("{res} = {value1} == {value2}; /* incompatible types {t1} vs. {t2}; but may be NULL*/")
1495 self.add
("{res} = 0; /* incompatible types {t1} vs. {t2}; cannot be NULL */")
1499 if primitive
!= null then
1500 test
.add
("((struct instance_{primitive.c_name}*){value1})->value == ((struct instance_{primitive.c_name}*){value2})->value")
1501 else if can_be_primitive
(value1
) and can_be_primitive
(value2
) then
1502 test
.add
("{value1}->class == {value2}->class")
1503 var s
= new Array[String]
1504 for t
, v
in self.compiler
.box_kinds
do
1505 s
.add
"({value1}->class->box_kind == {v} && ((struct instance_{t.c_name}*){value1})->value == ((struct instance_{t.c_name}*){value2})->value)"
1507 test
.add
("({s.join(" || ")})")
1509 self.add
("{res} = {value1} == {value2};")
1512 self.add
("{res} = {value1} == {value2} || ({test.join(" && ")});")
1516 fun can_be_primitive
(value
: RuntimeVariable): Bool
1518 var t
= value
.mcasttype
1519 if t
isa MNullableType then t
= t
.mtype
1520 if not t
isa MClassType then return false
1521 var k
= t
.mclass
.kind
1522 return k
== interface_kind
or t
.ctype
!= "val*"
1525 fun maybe_null
(value
: RuntimeVariable): Bool
1527 var t
= value
.mcasttype
1528 return t
isa MNullableType or t
isa MNullType
1531 redef fun array_instance
(array
, elttype
)
1533 var nclass
= self.get_class
("NativeArray")
1534 var arrayclass
= self.get_class
("Array")
1535 var arraytype
= arrayclass
.get_mtype
([elttype
])
1536 var res
= self.init_instance
(arraytype
)
1537 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
1538 var length
= self.int_instance
(array
.length
)
1539 var nat
= native_array_instance
(elttype
, length
)
1540 for i
in [0..array
.length
[ do
1541 var r
= self.autobox
(array
[i
], self.object_type
)
1542 self.add
("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
1544 self.send
(self.get_property
("with_native", arrayclass
.intro
.bound_mtype
), [res
, nat
, length
])
1549 fun native_array_instance
(elttype
: MType, length
: RuntimeVariable): RuntimeVariable
1551 var mtype
= self.get_class
("NativeArray").get_mtype
([elttype
])
1552 self.require_declaration
("NEW_{mtype.mclass.c_name}")
1553 assert mtype
isa MGenericType
1554 var compiler
= self.compiler
1555 if mtype
.need_anchor
then
1556 link_unresolved_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1557 var recv
= self.frame
.arguments
.first
1558 var recv_type_info
= self.type_info
(recv
)
1559 self.require_declaration
(mtype
.const_color
)
1560 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1561 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
)
1563 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, {recv_type_info}->resolution_table->types[{mtype.const_color}])", mtype
)
1566 compiler
.undead_types
.add
(mtype
)
1567 self.require_declaration
("type_{mtype.c_name}")
1568 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, &type_{mtype.c_name})", mtype
)
1571 redef fun native_array_def
(pname
, ret_type
, arguments
)
1573 var elttype
= arguments
.first
.mtype
1574 var nclass
= self.get_class
("NativeArray")
1575 var recv
= "((struct instance_{nclass.c_name}*){arguments[0]})->values"
1576 if pname
== "[]" then
1577 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
1579 else if pname
== "[]=" then
1580 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
1582 else if pname
== "copy_to" then
1583 var recv1
= "((struct instance_{nclass.c_name}*){arguments[1]})->values"
1584 self.add
("memcpy({recv1}, {recv}, {arguments[2]}*sizeof({elttype.ctype}));")
1589 redef fun calloc_array
(ret_type
, arguments
)
1591 var mclass
= self.get_class
("ArrayCapable")
1592 var ft
= mclass
.mclass_type
.arguments
.first
.as(MParameterType)
1593 var res
= self.native_array_instance
(ft
, arguments
[1])
1597 fun link_unresolved_type
(mclassdef
: MClassDef, mtype
: MType) do
1598 assert mtype
.need_anchor
1599 var compiler
= self.compiler
1600 if not compiler
.live_unresolved_types
.has_key
(self.frame
.mpropdef
.mclassdef
) then
1601 compiler
.live_unresolved_types
[self.frame
.mpropdef
.mclassdef
] = new HashSet[MType]
1603 compiler
.live_unresolved_types
[self.frame
.mpropdef
.mclassdef
].add
(mtype
)
1607 redef class MMethodDef
1608 fun separate_runtime_function
: AbstractRuntimeFunction
1610 var res
= self.separate_runtime_function_cache
1612 res
= new SeparateRuntimeFunction(self)
1613 self.separate_runtime_function_cache
= res
1617 private var separate_runtime_function_cache
: nullable SeparateRuntimeFunction
1619 fun virtual_runtime_function
: AbstractRuntimeFunction
1621 var res
= self.virtual_runtime_function_cache
1623 res
= new VirtualRuntimeFunction(self)
1624 self.virtual_runtime_function_cache
= res
1628 private var virtual_runtime_function_cache
: nullable VirtualRuntimeFunction
1631 # The C function associated to a methoddef separately compiled
1632 class SeparateRuntimeFunction
1633 super AbstractRuntimeFunction
1635 redef fun build_c_name
: String do return "{mmethoddef.c_name}"
1637 redef fun to_s
do return self.mmethoddef
.to_s
1639 redef fun compile_to_c
(compiler
)
1641 var mmethoddef
= self.mmethoddef
1643 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
1644 var v
= compiler
.new_visitor
1645 var selfvar
= new RuntimeVariable("self", recv
, recv
)
1646 var arguments
= new Array[RuntimeVariable]
1647 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
1650 var msignature
= mmethoddef
.msignature
.resolve_for
(mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.mmodule
, true)
1652 var sig
= new Buffer
1653 var comment
= new Buffer
1654 var ret
= msignature
.return_mtype
1656 sig
.append
("{ret.ctype} ")
1657 else if mmethoddef
.mproperty
.is_new
then
1659 sig
.append
("{ret.ctype} ")
1663 sig
.append
(self.c_name
)
1664 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
1665 comment
.append
("({selfvar}: {selfvar.mtype}")
1666 arguments
.add
(selfvar
)
1667 for i
in [0..msignature
.arity
[ do
1668 var mtype
= msignature
.mparameters
[i
].mtype
1669 if i
== msignature
.vararg_rank
then
1670 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
1672 comment
.append
(", {mtype}")
1673 sig
.append
(", {mtype.ctype} p{i}")
1674 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
1675 arguments
.add
(argvar
)
1680 comment
.append
(": {ret}")
1682 compiler
.provide_declaration
(self.c_name
, "{sig};")
1684 v
.add_decl
("/* method {self} for {comment} */")
1685 v
.add_decl
("{sig} \{")
1687 frame
.returnvar
= v
.new_var
(ret
)
1689 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1691 if recv
!= arguments
.first
.mtype
then
1692 #print "{self} {recv} {arguments.first}"
1694 mmethoddef
.compile_inside_to_c
(v
, arguments
)
1696 v
.add
("{frame.returnlabel.as(not null)}:;")
1698 v
.add
("return {frame.returnvar.as(not null)};")
1701 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})"
1705 # The C function associated to a methoddef on a primitive type, stored into a VFT of a class
1706 # The first parameter (the reciever) is always typed by val* in order to accept an object value
1707 class VirtualRuntimeFunction
1708 super AbstractRuntimeFunction
1710 redef fun build_c_name
: String do return "VIRTUAL_{mmethoddef.c_name}"
1712 redef fun to_s
do return self.mmethoddef
.to_s
1714 redef fun compile_to_c
(compiler
)
1716 var mmethoddef
= self.mmethoddef
1718 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
1719 var v
= compiler
.new_visitor
1720 var selfvar
= new RuntimeVariable("self", v
.object_type
, recv
)
1721 var arguments
= new Array[RuntimeVariable]
1722 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
1725 var sig
= new Buffer
1726 var comment
= new Buffer
1728 # Because the function is virtual, the signature must match the one of the original class
1729 var intromclassdef
= self.mmethoddef
.mproperty
.intro
.mclassdef
1730 var msignature
= mmethoddef
.mproperty
.intro
.msignature
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1731 var ret
= msignature
.return_mtype
1733 sig
.append
("{ret.ctype} ")
1734 else if mmethoddef
.mproperty
.is_new
then
1736 sig
.append
("{ret.ctype} ")
1740 sig
.append
(self.c_name
)
1741 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
1742 comment
.append
("({selfvar}: {selfvar.mtype}")
1743 arguments
.add
(selfvar
)
1744 for i
in [0..msignature
.arity
[ do
1745 var mtype
= msignature
.mparameters
[i
].mtype
1746 if i
== msignature
.vararg_rank
then
1747 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
1749 comment
.append
(", {mtype}")
1750 sig
.append
(", {mtype.ctype} p{i}")
1751 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
1752 arguments
.add
(argvar
)
1757 comment
.append
(": {ret}")
1759 compiler
.provide_declaration
(self.c_name
, "{sig};")
1761 v
.add_decl
("/* method {self} for {comment} */")
1762 v
.add_decl
("{sig} \{")
1764 frame
.returnvar
= v
.new_var
(ret
)
1766 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1768 var subret
= v
.call
(mmethoddef
, recv
, arguments
)
1770 assert subret
!= null
1771 v
.assign
(frame
.returnvar
.as(not null), subret
)
1774 v
.add
("{frame.returnlabel.as(not null)}:;")
1776 v
.add
("return {frame.returnvar.as(not null)};")
1779 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})"
1783 redef fun call
(v
, arguments
) do abort
1787 fun const_color
: String do return "COLOR_{c_name}"
1790 redef class MProperty
1791 fun const_color
: String do return "COLOR_{c_name}"
1794 redef class MPropDef
1795 fun const_color
: String do return "COLOR_{c_name}"