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
: 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
)
97 compiler
.display_stats
100 self.toolcontext
.info
("*** END GENERATING C: {time1-time0} ***", 2)
101 write_and_make
(compiler
)
105 # Singleton that store the knowledge about the separate compilation process
106 class SeparateCompiler
107 super AbstractCompiler
109 # The result of the RTA (used to know live types and methods)
110 var runtime_type_analysis
: RapidTypeAnalysis
112 private var undead_types
: Set[MType] = new HashSet[MType]
113 private var partial_types
: Set[MType] = new HashSet[MType]
114 private var live_unresolved_types
: Map[MClassDef, Set[MType]] = new HashMap[MClassDef, HashSet[MType]]
116 private var type_layout
: nullable Layout[MType]
117 private var resolution_layout
: nullable Layout[MType]
118 protected var method_layout
: nullable Layout[MMethod]
119 protected var attr_layout
: nullable Layout[MAttribute]
121 init(mainmodule
: MModule, mmbuilder
: ModelBuilder, runtime_type_analysis
: RapidTypeAnalysis) do
122 super(mainmodule
, mmbuilder
)
123 var file
= new_file
("nit.common")
124 self.header
= new CodeWriter(file
)
125 self.runtime_type_analysis
= runtime_type_analysis
126 self.compile_box_kinds
129 redef fun compile_header_structs
do
130 self.header
.add_decl
("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
131 self.compile_header_attribute_structs
132 self.header
.add_decl
("struct class \{ int box_kind; nitmethod_t vft[]; \}; /* general C type representing a Nit class. */")
134 # With resolution_table_table, all live type resolution are stored in a big table: resolution_table
135 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. */")
136 self.header
.add_decl
("struct instance \{ const struct type *type; const struct class *class; nitattribute_t attrs[]; \}; /* general C type representing a Nit instance. */")
138 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
139 self.header
.add_decl
("struct types \{ int mask; const struct type *types[]; \}; /* a list types (used for vts, fts and unresolved lists). */")
141 self.header
.add_decl
("struct types \{ int dummy; const struct type *types[]; \}; /* a list types (used for vts, fts and unresolved lists). */")
144 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
145 self.header
.add_decl
("#define HASH(mask, id) ((mask)%(id))")
146 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
147 self.header
.add_decl
("#define HASH(mask, id) ((mask)&(id))")
150 self.header
.add_decl
("typedef struct instance val; /* general C type representing a Nit instance. */")
153 fun compile_header_attribute_structs
155 if modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
156 self.header
.add_decl
("typedef void* nitattribute_t; /* general C type representing a Nit attribute. */")
158 self.header
.add_decl
("typedef union \{")
159 self.header
.add_decl
("void* val;")
160 for c
, v
in self.box_kinds
do
161 var t
= c
.mclass_type
162 self.header
.add_decl
("{t.ctype} {t.ctypename};")
164 self.header
.add_decl
("\} nitattribute_t; /* general C type representing a Nit attribute. */")
168 fun compile_box_kinds
170 # Collect all bas box class
171 # FIXME: this is not completely fine with a separate compilation scheme
172 for classname
in ["Int", "Bool", "Char", "Float", "NativeString", "Pointer"] do
173 var classes
= self.mainmodule
.model
.get_mclasses_by_name
(classname
)
174 if classes
== null then continue
175 assert classes
.length
== 1 else print classes
.join
(", ")
176 self.box_kinds
[classes
.first
] = self.box_kinds
.length
+ 1
180 var box_kinds
= new HashMap[MClass, Int]
182 fun box_kind_of
(mclass
: MClass): Int
184 if mclass
.mclass_type
.ctype
== "val*" then
186 else if mclass
.kind
== extern_kind
then
187 return self.box_kinds
[self.mainmodule
.get_primitive_class
("Pointer")]
189 return self.box_kinds
[mclass
]
194 fun compile_color_consts
(colors
: Map[Object, Int]) do
196 for m
, c
in colors
do
197 if color_consts_done
.has
(m
) then continue
198 if m
isa MProperty then
199 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
200 self.provide_declaration
(m
.const_color
, "#define {m.const_color} {c}")
202 self.provide_declaration
(m
.const_color
, "extern const int {m.const_color};")
203 v
.add
("const int {m.const_color} = {c};")
205 else if m
isa MType then
206 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
207 self.provide_declaration
(m
.const_color
, "#define {m.const_color} {c}")
209 self.provide_declaration
(m
.const_color
, "extern const int {m.const_color};")
210 v
.add
("const int {m.const_color} = {c};")
213 color_consts_done
.add
(m
)
217 private var color_consts_done
= new HashSet[Object]
219 # colorize classe properties
220 fun do_property_coloring
do
221 var mclasses
= new HashSet[MClass].from
(modelbuilder
.model
.mclasses
)
224 var method_layout_builder
: PropertyLayoutBuilder[MMethod]
225 var attribute_layout_builder
: PropertyLayoutBuilder[MAttribute]
226 #FIXME PH and BM layouts too slow for large programs
227 #if modelbuilder.toolcontext.opt_bm_typing.value then
228 # method_layout_builder = new MMethodBMizer(self.mainmodule)
229 # attribute_layout_builder = new MAttributeBMizer(self.mainmodule)
230 #else if modelbuilder.toolcontext.opt_phmod_typing.value then
231 # method_layout_builder = new MMethodHasher(new PHModOperator, self.mainmodule)
232 # attribute_layout_builder = new MAttributeHasher(new PHModOperator, self.mainmodule)
233 #else if modelbuilder.toolcontext.opt_phand_typing.value then
234 # method_layout_builder = new MMethodHasher(new PHAndOperator, self.mainmodule)
235 # attribute_layout_builder = new MAttributeHasher(new PHAndOperator, self.mainmodule)
238 var class_layout_builder
= new MClassColorer(self.mainmodule
)
239 class_layout_builder
.build_layout
(mclasses
)
240 method_layout_builder
= new MMethodColorer(self.mainmodule
, class_layout_builder
)
241 attribute_layout_builder
= new MAttributeColorer(self.mainmodule
, class_layout_builder
)
245 var method_layout
= method_layout_builder
.build_layout
(mclasses
)
246 self.method_tables
= build_method_tables
(mclasses
, method_layout
)
247 self.compile_color_consts
(method_layout
.pos
)
248 self.method_layout
= method_layout
250 # attributes coloration
251 var attr_layout
= attribute_layout_builder
.build_layout
(mclasses
)
252 self.attr_tables
= build_attr_tables
(mclasses
, attr_layout
)
253 self.compile_color_consts
(attr_layout
.pos
)
254 self.attr_layout
= attr_layout
257 fun build_method_tables
(mclasses
: Set[MClass], layout
: Layout[MProperty]): Map[MClass, Array[nullable MPropDef]] do
258 var tables
= new HashMap[MClass, Array[nullable MPropDef]]
259 for mclass
in mclasses
do
260 var table
= new Array[nullable MPropDef]
261 # first, fill table from parents by reverse linearization order
262 var parents
= new Array[MClass]
263 if mainmodule
.flatten_mclass_hierarchy
.has
(mclass
) then
264 parents
= mclass
.in_hierarchy
(mainmodule
).greaters
.to_a
265 self.mainmodule
.linearize_mclasses
(parents
)
267 for parent
in parents
do
268 if parent
== mclass
then continue
269 for mproperty
in self.mainmodule
.properties
(parent
) do
270 if not mproperty
isa MMethod then continue
271 var color
= layout
.pos
[mproperty
]
272 if table
.length
<= color
then
273 for i
in [table
.length
.. color
[ do
277 for mpropdef
in mproperty
.mpropdefs
do
278 if mpropdef
.mclassdef
.mclass
== parent
then
279 table
[color
] = mpropdef
285 # then override with local properties
286 for mproperty
in self.mainmodule
.properties
(mclass
) do
287 if not mproperty
isa MMethod then continue
288 var color
= layout
.pos
[mproperty
]
289 if table
.length
<= color
then
290 for i
in [table
.length
.. color
[ do
294 for mpropdef
in mproperty
.mpropdefs
do
295 if mpropdef
.mclassdef
.mclass
== mclass
then
296 table
[color
] = mpropdef
300 tables
[mclass
] = table
305 fun build_attr_tables
(mclasses
: Set[MClass], layout
: Layout[MProperty]): Map[MClass, Array[nullable MPropDef]] do
306 var tables
= new HashMap[MClass, Array[nullable MPropDef]]
307 for mclass
in mclasses
do
308 var table
= new Array[nullable MPropDef]
309 # first, fill table from parents by reverse linearization order
310 var parents
= new Array[MClass]
311 if mainmodule
.flatten_mclass_hierarchy
.has
(mclass
) then
312 parents
= mclass
.in_hierarchy
(mainmodule
).greaters
.to_a
313 self.mainmodule
.linearize_mclasses
(parents
)
315 for parent
in parents
do
316 if parent
== mclass
then continue
317 for mproperty
in self.mainmodule
.properties
(parent
) do
318 if not mproperty
isa MAttribute then continue
319 var color
= layout
.pos
[mproperty
]
320 if table
.length
<= color
then
321 for i
in [table
.length
.. color
[ do
325 for mpropdef
in mproperty
.mpropdefs
do
326 if mpropdef
.mclassdef
.mclass
== parent
then
327 table
[color
] = mpropdef
333 # then override with local properties
334 for mproperty
in self.mainmodule
.properties
(mclass
) do
335 if not mproperty
isa MAttribute then continue
336 var color
= layout
.pos
[mproperty
]
337 if table
.length
<= color
then
338 for i
in [table
.length
.. color
[ do
342 for mpropdef
in mproperty
.mpropdefs
do
343 if mpropdef
.mclassdef
.mclass
== mclass
then
344 table
[color
] = mpropdef
348 tables
[mclass
] = table
353 # colorize live types of the program
354 private fun do_type_coloring
: POSet[MType] do
355 var mtypes
= new HashSet[MType]
356 mtypes
.add_all
(self.runtime_type_analysis
.live_types
)
357 mtypes
.add_all
(self.runtime_type_analysis
.live_cast_types
)
358 mtypes
.add_all
(self.undead_types
)
359 for c
in self.box_kinds
.keys
do
360 mtypes
.add
(c
.mclass_type
)
363 for mtype
in mtypes
do
364 retrieve_partial_types
(mtype
)
366 mtypes
.add_all
(self.partial_types
)
369 var layout_builder
: TypingLayoutBuilder[MType]
370 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
371 layout_builder
= new MTypeBMizer(self.mainmodule
)
372 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
373 layout_builder
= new MTypeHasher(new PHModOperator, self.mainmodule
)
374 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
375 layout_builder
= new MTypeHasher(new PHAndOperator, self.mainmodule
)
377 layout_builder
= new MTypeColorer(self.mainmodule
)
381 self.type_layout
= layout_builder
.build_layout
(mtypes
)
382 var poset
= layout_builder
.poset
.as(not null)
383 self.type_tables
= self.build_type_tables
(poset
)
385 # VT and FT are stored with other unresolved types in the big resolution_tables
386 self.compile_resolution_tables
(mtypes
)
392 fun build_type_tables
(mtypes
: POSet[MType]): Map[MType, Array[nullable MType]] do
393 var tables
= new HashMap[MType, Array[nullable MType]]
394 var layout
= self.type_layout
395 for mtype
in mtypes
do
396 var table
= new Array[nullable MType]
397 for sup
in mtypes
[mtype
].greaters
do
399 if layout
isa PHLayout[MType, MType] then
400 color
= layout
.hashes
[mtype
][sup
]
402 color
= layout
.pos
[sup
]
404 if table
.length
<= color
then
405 for i
in [table
.length
.. color
[ do
411 tables
[mtype
] = table
416 protected fun compile_resolution_tables
(mtypes
: Set[MType]) do
417 # resolution_tables is used to perform a type resolution at runtime in O(1)
419 # During the visit of the body of classes, live_unresolved_types are collected
421 # Collect all live_unresolved_types (visited in the body of classes)
423 # Determinate fo each livetype what are its possible requested anchored types
424 var mtype2unresolved
= new HashMap[MClassType, Set[MType]]
425 for mtype
in self.runtime_type_analysis
.live_types
do
426 var set
= new HashSet[MType]
427 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
428 if self.live_unresolved_types
.has_key
(cd
) then
429 set
.add_all
(self.live_unresolved_types
[cd
])
432 mtype2unresolved
[mtype
] = set
435 # Compute the table layout with the prefered method
436 var resolution_builder
: ResolutionLayoutBuilder
437 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
438 resolution_builder
= new ResolutionBMizer
439 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
440 resolution_builder
= new ResolutionHasher(new PHModOperator)
441 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
442 resolution_builder
= new ResolutionHasher(new PHAndOperator)
444 resolution_builder
= new ResolutionColorer
446 self.resolution_layout
= resolution_builder
.build_layout
(mtype2unresolved
)
447 self.resolution_tables
= self.build_resolution_tables
(mtype2unresolved
)
449 # Compile a C constant for each collected unresolved type.
450 # Either to a color, or to -1 if the unresolved type is dead (no live receiver can require it)
451 var all_unresolved
= new HashSet[MType]
452 for t
in self.live_unresolved_types
.values
do
453 all_unresolved
.add_all
(t
)
455 var all_unresolved_types_colors
= new HashMap[MType, Int]
456 for t
in all_unresolved
do
457 if self.resolution_layout
.pos
.has_key
(t
) then
458 all_unresolved_types_colors
[t
] = self.resolution_layout
.pos
[t
]
460 all_unresolved_types_colors
[t
] = -1
463 self.compile_color_consts
(all_unresolved_types_colors
)
466 #for k, v in unresolved_types_tables.as(not null) do
467 # print "{k}: {v.join(", ")}"
472 fun build_resolution_tables
(elements
: Map[MClassType, Set[MType]]): Map[MClassType, Array[nullable MType]] do
473 var tables
= new HashMap[MClassType, Array[nullable MType]]
474 var layout
= self.resolution_layout
475 for mclasstype
, mtypes
in elements
do
476 var table
= new Array[nullable MType]
477 for mtype
in mtypes
do
479 if layout
isa PHLayout[MClassType, MType] then
480 color
= layout
.hashes
[mclasstype
][mtype
]
482 color
= layout
.pos
[mtype
]
484 if table
.length
<= color
then
485 for i
in [table
.length
.. color
[ do
491 tables
[mclasstype
] = table
496 fun retrieve_partial_types
(mtype
: MType) do
497 # add formal types arguments to mtypes
498 if mtype
isa MGenericType then
499 for ft
in mtype
.arguments
do
500 if ft
.need_anchor
then
501 print
("Why do we need anchor here ?")
504 self.partial_types
.add
(ft
)
505 retrieve_partial_types
(ft
)
508 var mclass_type
: MClassType
509 if mtype
isa MNullableType then
510 mclass_type
= mtype
.mtype
.as(MClassType)
512 mclass_type
= mtype
.as(MClassType)
515 # add virtual types to mtypes
516 for vt
in self.mainmodule
.properties
(mclass_type
.mclass
) do
517 if vt
isa MVirtualTypeProp then
518 var anchored
= vt
.mvirtualtype
.lookup_bound
(self.mainmodule
, mclass_type
).anchor_to
(self.mainmodule
, mclass_type
)
519 self.partial_types
.add
(anchored
)
524 # Separately compile all the method definitions of the module
525 fun compile_module_to_c
(mmodule
: MModule)
527 var old_module
= self.mainmodule
528 self.mainmodule
= mmodule
529 for cd
in mmodule
.mclassdefs
do
530 for pd
in cd
.mpropdefs
do
531 if not pd
isa MMethodDef then continue
532 #print "compile {pd} @ {cd} @ {mmodule}"
533 var r
= pd
.separate_runtime_function
535 var r2
= pd
.virtual_runtime_function
536 r2
.compile_to_c
(self)
539 self.mainmodule
= old_module
542 # Globaly compile the type structure of a live type
543 fun compile_type_to_c
(mtype
: MType)
545 var c_name
= mtype
.c_name
546 var v
= new SeparateCompilerVisitor(self)
547 v
.add_decl
("/* runtime type {mtype} */")
549 # extern const struct type_X
550 self.provide_declaration
("type_{c_name}", "extern const struct type type_{c_name};")
552 # const struct type_X
553 v
.add_decl
("const struct type type_{c_name} = \{")
554 v
.add_decl
("{self.type_layout.ids[mtype]},")
555 v
.add_decl
("\"{mtype}\
", /* class_name_string */")
556 var layout
= self.type_layout
557 if layout
isa PHLayout[MType, MType] then
558 v
.add_decl
("{layout.masks[mtype]},")
560 v
.add_decl
("{layout.pos[mtype]},")
562 if mtype
isa MNullableType then
567 if compile_type_resolution_table
(mtype
) then
568 v
.require_declaration
("resolution_table_{c_name}")
569 v
.add_decl
("&resolution_table_{c_name},")
573 v
.add_decl
("{self.type_tables[mtype].length},")
575 for stype
in self.type_tables
[mtype
] do
576 if stype
== null then
577 v
.add_decl
("-1, /* empty */")
579 v
.add_decl
("{self.type_layout.ids[stype]}, /* {stype} */")
586 fun compile_type_resolution_table
(mtype
: MType): Bool do
588 var mclass_type
: MClassType
589 if mtype
isa MNullableType then
590 mclass_type
= mtype
.mtype
.as(MClassType)
592 mclass_type
= mtype
.as(MClassType)
594 if not self.resolution_tables
.has_key
(mclass_type
) then return false
596 var layout
= self.resolution_layout
598 # extern const struct resolution_table_X resolution_table_X
599 self.provide_declaration
("resolution_table_{mtype.c_name}", "extern const struct types resolution_table_{mtype.c_name};")
601 # const struct fts_table_X fts_table_X
603 v
.add_decl
("const struct types resolution_table_{mtype.c_name} = \{")
604 if layout
isa PHLayout[MClassType, MType] then
605 v
.add_decl
("{layout.masks[mclass_type]},")
607 v
.add_decl
("0, /* dummy */")
610 for t
in self.resolution_tables
[mclass_type
] do
612 v
.add_decl
("NULL, /* empty */")
614 # The table stores the result of the type resolution
615 # Therefore, for a receiver `mclass_type`, and a unresolved type `t`
616 # the value stored is tv.
617 var tv
= t
.resolve_for
(mclass_type
, mclass_type
, self.mainmodule
, true)
618 # FIXME: What typeids means here? How can a tv not be live?
619 if self.type_layout
.ids
.has_key
(tv
) then
620 v
.require_declaration
("type_{tv.c_name}")
621 v
.add_decl
("&type_{tv.c_name}, /* {t}: {tv} */")
623 v
.add_decl
("NULL, /* empty ({t}: {tv} not a live type) */")
632 # Globally compile the table of the class mclass
633 # In a link-time optimisation compiler, tables are globally computed
634 # In a true separate compiler (a with dynamic loading) you cannot do this unfortnally
635 fun compile_class_to_c
(mclass
: MClass)
637 var mtype
= mclass
.intro
.bound_mtype
638 var c_name
= mclass
.c_name
640 var vft
= self.method_tables
[mclass
]
641 var attrs
= self.attr_tables
[mclass
]
644 var is_dead
= not runtime_type_analysis
.live_classes
.has
(mclass
) and mtype
.ctype
== "val*" and mclass
.name
!= "NativeArray"
646 v
.add_decl
("/* runtime class {c_name} */")
650 self.provide_declaration
("class_{c_name}", "extern const struct class class_{c_name};")
651 v
.add_decl
("const struct class class_{c_name} = \{")
652 v
.add_decl
("{self.box_kind_of(mclass)}, /* box_kind */")
654 for i
in [0 .. vft
.length
[ do
655 var mpropdef
= vft
[i
]
656 if mpropdef
== null then
657 v
.add_decl
("NULL, /* empty */")
659 assert mpropdef
isa MMethodDef
660 var rf
= mpropdef
.virtual_runtime_function
661 v
.require_declaration
(rf
.c_name
)
662 v
.add_decl
("(nitmethod_t){rf.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
669 if mtype
.ctype
!= "val*" then
670 #Build instance struct
671 self.header
.add_decl
("struct instance_{c_name} \{")
672 self.header
.add_decl
("const struct type *type;")
673 self.header
.add_decl
("const struct class *class;")
674 self.header
.add_decl
("{mtype.ctype} value;")
675 self.header
.add_decl
("\};")
677 if not self.runtime_type_analysis
.live_types
.has
(mtype
) then return
680 self.header
.add_decl
("val* BOX_{c_name}({mtype.ctype});")
681 v
.add_decl
("/* allocate {mtype} */")
682 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
683 v
.add
("struct instance_{c_name}*res = nit_alloc(sizeof(struct instance_{c_name}));")
684 v
.require_declaration
("type_{c_name}")
685 v
.add
("res->type = &type_{c_name};")
686 v
.require_declaration
("class_{c_name}")
687 v
.add
("res->class = &class_{c_name};")
688 v
.add
("res->value = value;")
689 v
.add
("return (val*)res;")
692 else if mclass
.name
== "NativeArray" then
693 #Build instance struct
694 self.header
.add_decl
("struct instance_{c_name} \{")
695 self.header
.add_decl
("const struct type *type;")
696 self.header
.add_decl
("const struct class *class;")
697 # NativeArrays are just a instance header followed by an array of values
698 self.header
.add_decl
("val* values[0];")
699 self.header
.add_decl
("\};")
702 self.provide_declaration
("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(int length, const struct type* type);")
703 v
.add_decl
("/* allocate {mtype} */")
704 v
.add_decl
("{mtype.ctype} NEW_{c_name}(int length, const struct type* type) \{")
705 var res
= v
.new_named_var
(mtype
, "self")
707 var mtype_elt
= mtype
.arguments
.first
708 v
.add
("{res} = nit_alloc(sizeof(struct instance_{c_name}) + length*sizeof({mtype_elt.ctype}));")
709 v
.add
("{res}->type = type;")
710 hardening_live_type
(v
, "type")
711 v
.require_declaration
("class_{c_name}")
712 v
.add
("{res}->class = &class_{c_name};")
713 v
.add
("return {res};")
719 self.provide_declaration
("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(const struct type* type);")
720 v
.add_decl
("/* allocate {mtype} */")
721 v
.add_decl
("{mtype.ctype} NEW_{c_name}(const struct type* type) \{")
723 v
.add_abort
("{mclass} is DEAD")
725 var res
= v
.new_named_var
(mtype
, "self")
727 v
.add
("{res} = nit_alloc(sizeof(struct instance) + {attrs.length}*sizeof(nitattribute_t));")
728 v
.add
("{res}->type = type;")
729 hardening_live_type
(v
, "type")
730 v
.require_declaration
("class_{c_name}")
731 v
.add
("{res}->class = &class_{c_name};")
732 self.generate_init_attr
(v
, res
, mtype
)
733 v
.add
("return {res};")
737 generate_check_init_instance
(mtype
)
740 # Add a dynamic test to ensure that the type referenced by `t` is a live type
741 fun hardening_live_type
(v
: VISITOR, t
: String)
743 if not v
.compiler
.modelbuilder
.toolcontext
.opt_hardening
.value
then return
744 v
.add
("if({t} == NULL) \{")
745 v
.add_abort
("type null")
747 v
.add
("if({t}->resolution_table == NULL) \{")
748 v
.add
("fprintf(stderr, \"Insantiation of a dead
type: %s\\n\
", {t}->name);")
749 v
.add_abort
("type dead")
753 redef fun generate_check_init_instance
(mtype
)
755 if self.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
757 var v
= self.new_visitor
758 var c_name
= mtype
.mclass
.c_name
759 var res
= new RuntimeVariable("self", mtype
, mtype
)
760 self.provide_declaration
("CHECK_NEW_{c_name}", "void CHECK_NEW_{c_name}({mtype.ctype});")
761 v
.add_decl
("/* allocate {mtype} */")
762 v
.add_decl
("void CHECK_NEW_{c_name}({mtype.ctype} {res}) \{")
763 if runtime_type_analysis
.live_classes
.has
(mtype
.mclass
) then
764 self.generate_check_attr
(v
, res
, mtype
)
766 v
.add_abort
("{mtype.mclass} is DEAD")
771 redef fun new_visitor
do return new SeparateCompilerVisitor(self)
775 private var type_tables
: Map[MType, Array[nullable MType]] = new HashMap[MType, Array[nullable MType]]
776 private var resolution_tables
: Map[MClassType, Array[nullable MType]] = new HashMap[MClassType, Array[nullable MType]]
777 protected var method_tables
: Map[MClass, Array[nullable MPropDef]] = new HashMap[MClass, Array[nullable MPropDef]]
778 protected var attr_tables
: Map[MClass, Array[nullable MPropDef]] = new HashMap[MClass, Array[nullable MPropDef]]
780 redef fun display_stats
783 if self.modelbuilder
.toolcontext
.opt_tables_metrics
.value
then
790 print
"# size of subtyping tables"
791 print
"\ttotal \tholes"
794 for t
, table
in type_tables
do
795 total
+= table
.length
796 for e
in table
do if e
== null then holes
+= 1
798 print
"\t{total}\t{holes}"
800 print
"# size of resolution tables"
801 print
"\ttotal \tholes"
804 for t
, table
in resolution_tables
do
805 total
+= table
.length
806 for e
in table
do if e
== null then holes
+= 1
808 print
"\t{total}\t{holes}"
810 print
"# size of methods tables"
811 print
"\ttotal \tholes"
814 for t
, table
in method_tables
do
815 total
+= table
.length
816 for e
in table
do if e
== null then holes
+= 1
818 print
"\t{total}\t{holes}"
820 print
"# size of attributes tables"
821 print
"\ttotal \tholes"
824 for t
, table
in attr_tables
do
825 total
+= table
.length
826 for e
in table
do if e
== null then holes
+= 1
828 print
"\t{total}\t{holes}"
832 # A visitor on the AST of property definition that generate the C code of a separate compilation process.
833 class SeparateCompilerVisitor
834 super AbstractCompilerVisitor
836 redef type COMPILER: SeparateCompiler
838 redef fun adapt_signature
(m
, args
)
840 var msignature
= m
.msignature
.resolve_for
(m
.mclassdef
.bound_mtype
, m
.mclassdef
.bound_mtype
, m
.mclassdef
.mmodule
, true)
841 var recv
= args
.first
842 if recv
.mtype
.ctype
!= m
.mclassdef
.mclass
.mclass_type
.ctype
then
843 args
.first
= self.autobox
(args
.first
, m
.mclassdef
.mclass
.mclass_type
)
845 for i
in [0..msignature
.arity
[ do
846 var t
= msignature
.mparameters
[i
].mtype
847 if i
== msignature
.vararg_rank
then
850 args
[i
+1] = self.autobox
(args
[i
+1], t
)
854 redef fun autobox
(value
, mtype
)
856 if value
.mtype
== mtype
then
858 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
860 else if value
.mtype
.ctype
== "val*" then
861 return self.new_expr
("((struct instance_{mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
862 else if mtype
.ctype
== "val*" then
863 var valtype
= value
.mtype
.as(MClassType)
864 var res
= self.new_var
(mtype
)
865 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
866 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
867 self.add
("printf(\"Dead code executed
!\\n\
"); exit(1);")
870 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
873 # Bad things will appen!
874 var res
= self.new_var
(mtype
)
875 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
876 self.add
("printf(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); exit(1);")
881 # Return a C expression returning the runtime type structure of the value
882 # The point of the method is to works also with primitives types.
883 fun type_info
(value
: RuntimeVariable): String
885 if value
.mtype
.ctype
== "val*" then
886 return "{value}->type"
888 self.require_declaration
("type_{value.mtype.c_name}")
889 return "(&type_{value.mtype.c_name})"
893 redef fun send
(mmethod
, arguments
)
895 if arguments
.first
.mcasttype
.ctype
!= "val*" then
896 # In order to shortcut the primitive, we need to find the most specific method
897 # Howverr, because of performance (no flattening), we always work on the realmainmodule
898 var m
= self.compiler
.mainmodule
899 self.compiler
.mainmodule
= self.compiler
.realmainmodule
900 var res
= self.monomorphic_send
(mmethod
, arguments
.first
.mcasttype
, arguments
)
901 self.compiler
.mainmodule
= m
905 var res
: nullable RuntimeVariable
906 var msignature
= mmethod
.intro
.msignature
.resolve_for
(mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.mmodule
, true)
907 var ret
= msignature
.return_mtype
908 if mmethod
.is_new
then
909 ret
= arguments
.first
.mtype
910 res
= self.new_var
(ret
)
911 else if ret
== null then
914 res
= self.new_var
(ret
)
920 var recv
= arguments
.first
923 self.varargize
(mmethod
.intro
, mmethod
.intro
.msignature
.as(not null), arguments
)
924 for i
in [0..msignature
.arity
[ do
925 var a
= arguments
[i
+1]
926 var t
= msignature
.mparameters
[i
].mtype
927 if i
== msignature
.vararg_rank
then
928 t
= arguments
[i
+1].mcasttype
930 s
.append
(", {t.ctype}")
931 a
= self.autobox
(a
, t
)
935 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
or mmethod
.name
== "==" or mmethod
.name
== "!="
936 var maybenull
= recv
.mcasttype
isa MNullableType and consider_null
938 self.add
("if ({recv} == NULL) \{")
939 if mmethod
.name
== "==" then
941 var arg
= arguments
[1]
942 if arg
.mcasttype
isa MNullableType then
943 self.add
("{res} = ({arg} == NULL);")
944 else if arg
.mcasttype
isa MNullType then
945 self.add
("{res} = 1; /* is null */")
947 self.add
("{res} = 0; /* {arg.inspect} cannot be null */")
949 else if mmethod
.name
== "!=" then
951 var arg
= arguments
[1]
952 if arg
.mcasttype
isa MNullableType then
953 self.add
("{res} = ({arg} != NULL);")
954 else if arg
.mcasttype
isa MNullType then
955 self.add
("{res} = 0; /* is null */")
957 self.add
("{res} = 1; /* {arg.inspect} cannot be null */")
960 self.add_abort
("Reciever is null")
962 self.add
("\} else \{")
964 if not self.compiler
.modelbuilder
.toolcontext
.opt_no_shortcut_equate
.value
and (mmethod
.name
== "==" or mmethod
.name
== "!=") then
966 # Recv is not null, thus is arg is, it is easy to conclude (and respect the invariants)
967 var arg
= arguments
[1]
968 if arg
.mcasttype
isa MNullType then
969 if mmethod
.name
== "==" then
970 self.add
("{res} = 0; /* arg is null but recv is not */")
972 self.add
("{res} = 1; /* arg is null and recv is not */")
982 if ret
== null then r
= "void" else r
= ret
.ctype
983 self.require_declaration
(mmethod
.const_color
)
984 var call
= "(({r} (*)({s}))({arguments.first}->class->vft[{mmethod.const_color}]))({ss}) /* {mmethod} on {arguments.first.inspect}*/"
987 self.add
("{res} = {call};")
999 redef fun call
(mmethoddef
, recvtype
, arguments
)
1001 var res
: nullable RuntimeVariable
1002 var ret
= mmethoddef
.msignature
.return_mtype
1003 if mmethoddef
.mproperty
.is_new
then
1004 ret
= arguments
.first
.mtype
1005 res
= self.new_var
(ret
)
1006 else if ret
== null then
1009 ret
= ret
.resolve_for
(mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.mmodule
, true)
1010 res
= self.new_var
(ret
)
1013 if self.compiler
.modelbuilder
.mpropdef2npropdef
.has_key
(mmethoddef
) and
1014 self.compiler
.modelbuilder
.mpropdef2npropdef
[mmethoddef
] isa AInternMethPropdef and
1015 not compiler
.modelbuilder
.toolcontext
.opt_no_inline_intern
.value
then
1016 var frame
= new Frame(self, mmethoddef
, recvtype
, arguments
)
1017 frame
.returnlabel
= self.get_name
("RET_LABEL")
1018 frame
.returnvar
= res
1019 var old_frame
= self.frame
1021 self.add
("\{ /* Inline {mmethoddef} ({arguments.join(",")}) */")
1022 mmethoddef
.compile_inside_to_c
(self, arguments
)
1023 self.add
("{frame.returnlabel.as(not null)}:(void)0;")
1025 self.frame
= old_frame
1030 self.adapt_signature
(mmethoddef
, arguments
)
1032 self.require_declaration
(mmethoddef
.c_name
)
1034 self.add
("{mmethoddef.c_name}({arguments.join(", ")});")
1037 self.add
("{res} = {mmethoddef.c_name}({arguments.join(", ")});")
1043 redef fun supercall
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
1045 # FIXME implements a polymorphic access in tables
1046 m
= m
.lookup_next_definition
(m
.mclassdef
.mmodule
, m
.mclassdef
.bound_mtype
)
1047 return self.call
(m
, recvtype
, args
)
1050 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
1052 # A vararg must be stored into an new array
1053 # The trick is that the dymaic type of the array may depends on the receiver
1054 # of the method (ie recv) if the static type is unresolved
1055 # This is more complex than usual because the unresolved type must not be resolved
1056 # with the current receiver (ie self).
1057 # Therefore to isolate the resolution from self, a local Frame is created.
1058 # One can see this implementation as an inlined method of the receiver whose only
1059 # job is to allocate the array
1060 var old_frame
= self.frame
1061 var frame
= new Frame(self, mpropdef
, mpropdef
.mclassdef
.bound_mtype
, [recv
])
1063 #print "required Array[{elttype}] for recv {recv.inspect}. bound=Array[{self.resolve_for(elttype, recv)}]. selfvar={frame.arguments.first.inspect}"
1064 var res
= self.array_instance
(varargs
, elttype
)
1065 self.frame
= old_frame
1069 redef fun isset_attribute
(a
, recv
)
1071 self.check_recv_notnull
(recv
)
1072 var res
= self.new_var
(bool_type
)
1074 # What is the declared type of the attribute?
1075 var mtype
= a
.intro
.static_mtype
.as(not null)
1076 var intromclassdef
= a
.intro
.mclassdef
1077 mtype
= mtype
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1079 if mtype
isa MNullableType then
1080 self.add
("{res} = 1; /* easy isset: {a} on {recv.inspect} */")
1084 self.require_declaration
(a
.const_color
)
1085 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1086 self.add
("{res} = {recv}->attrs[{a.const_color}] != NULL; /* {a} on {recv.inspect}*/")
1089 if mtype
.ctype
== "val*" then
1090 self.add
("{res} = {recv}->attrs[{a.const_color}].val != NULL; /* {a} on {recv.inspect} */")
1092 self.add
("{res} = 1; /* NOT YET IMPLEMENTED: isset of primitives: {a} on {recv.inspect} */")
1098 redef fun read_attribute
(a
, recv
)
1100 self.check_recv_notnull
(recv
)
1102 # What is the declared type of the attribute?
1103 var ret
= a
.intro
.static_mtype
.as(not null)
1104 var intromclassdef
= a
.intro
.mclassdef
1105 ret
= ret
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1107 self.require_declaration
(a
.const_color
)
1108 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1109 # Get the attribute or a box (ie. always a val*)
1110 var cret
= self.object_type
.as_nullable
1111 var res
= self.new_var
(cret
)
1114 self.add
("{res} = {recv}->attrs[{a.const_color}]; /* {a} on {recv.inspect} */")
1116 # Check for Uninitialized attribute
1117 if not ret
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then
1118 self.add
("if ({res} == NULL) \{")
1119 self.add_abort
("Uninitialized attribute {a.name}")
1123 # Return the attribute or its unboxed version
1124 # Note: it is mandatory since we reuse the box on write, we do not whant that the box escapes
1125 return self.autobox
(res
, ret
)
1127 var res
= self.new_var
(ret
)
1128 self.add
("{res} = {recv}->attrs[{a.const_color}].{ret.ctypename}; /* {a} on {recv.inspect} */")
1130 # Check for Uninitialized attribute
1131 if ret
.ctype
== "val*" and not ret
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then
1132 self.add
("if ({res} == NULL) \{")
1133 self.add_abort
("Uninitialized attribute {a.name}")
1141 redef fun write_attribute
(a
, recv
, value
)
1143 self.check_recv_notnull
(recv
)
1145 # What is the declared type of the attribute?
1146 var mtype
= a
.intro
.static_mtype
.as(not null)
1147 var intromclassdef
= a
.intro
.mclassdef
1148 mtype
= mtype
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1150 # Adapt the value to the declared type
1151 value
= self.autobox
(value
, mtype
)
1153 self.require_declaration
(a
.const_color
)
1154 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1155 var attr
= "{recv}->attrs[{a.const_color}]"
1156 if mtype
.ctype
!= "val*" then
1157 assert mtype
isa MClassType
1158 # The attribute is primitive, thus we store it in a box
1159 # The trick is to create the box the first time then resuse the box
1160 self.add
("if ({attr} != NULL) \{")
1161 self.add
("((struct instance_{mtype.c_name}*){attr})->value = {value}; /* {a} on {recv.inspect} */")
1162 self.add
("\} else \{")
1163 value
= self.autobox
(value
, self.object_type
.as_nullable
)
1164 self.add
("{attr} = {value}; /* {a} on {recv.inspect} */")
1167 # The attribute is not primitive, thus store it direclty
1168 self.add
("{attr} = {value}; /* {a} on {recv.inspect} */")
1171 self.add
("{recv}->attrs[{a.const_color}].{mtype.ctypename} = {value}; /* {a} on {recv.inspect} */")
1175 redef fun init_instance
(mtype
)
1177 self.require_declaration
("NEW_{mtype.mclass.c_name}")
1178 var compiler
= self.compiler
1179 if mtype
isa MGenericType and mtype
.need_anchor
then
1180 link_unresolved_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1181 var recv
= self.frame
.arguments
.first
1182 var recv_type_info
= self.type_info
(recv
)
1183 self.require_declaration
(mtype
.const_color
)
1184 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1185 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
)
1187 return self.new_expr
("NEW_{mtype.mclass.c_name}({recv_type_info}->resolution_table->types[{mtype.const_color}])", mtype
)
1190 compiler
.undead_types
.add
(mtype
)
1191 self.require_declaration
("type_{mtype.c_name}")
1192 return self.new_expr
("NEW_{mtype.mclass.c_name}(&type_{mtype.c_name})", mtype
)
1195 redef fun check_init_instance
(value
, mtype
)
1197 if self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
1198 self.require_declaration
("CHECK_NEW_{mtype.mclass.c_name}")
1199 self.add
("CHECK_NEW_{mtype.mclass.c_name}({value});")
1202 redef fun type_test
(value
, mtype
, tag
)
1204 self.add
("/* {value.inspect} isa {mtype} */")
1205 var compiler
= self.compiler
1207 var recv
= self.frame
.arguments
.first
1208 var recv_type_info
= self.type_info
(recv
)
1210 var res
= self.new_var
(bool_type
)
1212 var cltype
= self.get_name
("cltype")
1213 self.add_decl
("int {cltype};")
1214 var idtype
= self.get_name
("idtype")
1215 self.add_decl
("int {idtype};")
1217 var maybe_null
= self.maybe_null
(value
)
1218 var accept_null
= "0"
1220 if ntype
isa MNullableType then
1225 if value
.mcasttype
.is_subtype
(self.frame
.mpropdef
.mclassdef
.mmodule
, self.frame
.mpropdef
.mclassdef
.bound_mtype
, mtype
) then
1226 self.add
("{res} = 1; /* easy {value.inspect} isa {mtype}*/")
1227 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1228 self.compiler
.count_type_test_skipped
[tag
] += 1
1229 self.add
("count_type_test_skipped_{tag}++;")
1234 if ntype
.need_anchor
then
1235 var type_struct
= self.get_name
("type_struct")
1236 self.add_decl
("const struct type* {type_struct};")
1238 # Either with resolution_table with a direct resolution
1239 link_unresolved_type
(self.frame
.mpropdef
.mclassdef
, ntype
)
1240 self.require_declaration
(ntype
.const_color
)
1241 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1242 self.add
("{type_struct} = {recv_type_info}->resolution_table->types[HASH({recv_type_info}->resolution_table->mask, {ntype.const_color})];")
1244 self.add
("{type_struct} = {recv_type_info}->resolution_table->types[{ntype.const_color}];")
1246 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1247 self.compiler
.count_type_test_unresolved
[tag
] += 1
1248 self.add
("count_type_test_unresolved_{tag}++;")
1250 self.add
("{cltype} = {type_struct}->color;")
1251 self.add
("{idtype} = {type_struct}->id;")
1252 if maybe_null
and accept_null
== "0" then
1253 var is_nullable
= self.get_name
("is_nullable")
1254 self.add_decl
("short int {is_nullable};")
1255 self.add
("{is_nullable} = {type_struct}->is_nullable;")
1256 accept_null
= is_nullable
.to_s
1258 else if ntype
isa MClassType then
1259 compiler
.undead_types
.add
(mtype
)
1260 self.require_declaration
("type_{mtype.c_name}")
1261 self.add
("{cltype} = type_{mtype.c_name}.color;")
1262 self.add
("{idtype} = type_{mtype.c_name}.id;")
1263 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1264 self.compiler
.count_type_test_resolved
[tag
] += 1
1265 self.add
("count_type_test_resolved_{tag}++;")
1268 self.add
("printf(\"NOT YET IMPLEMENTED: type_test
(%s
, {mtype}).\\n\
", \"{value.inspect}\
"); exit(1);")
1271 # check color is in table
1273 self.add
("if({value} == NULL) \{")
1274 self.add
("{res} = {accept_null};")
1275 self.add
("\} else \{")
1277 var value_type_info
= self.type_info
(value
)
1278 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1279 self.add
("{cltype} = HASH({value_type_info}->color, {idtype});")
1281 self.add
("if({cltype} >= {value_type_info}->table_size) \{")
1282 self.add
("{res} = 0;")
1283 self.add
("\} else \{")
1284 self.add
("{res} = {value_type_info}->type_table[{cltype}] == {idtype};")
1293 redef fun is_same_type_test
(value1
, value2
)
1295 var res
= self.new_var
(bool_type
)
1296 # Swap values to be symetric
1297 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1302 if value1
.mtype
.ctype
!= "val*" then
1303 if value2
.mtype
== value1
.mtype
then
1304 self.add
("{res} = 1; /* is_same_type_test: compatible types {value1.mtype} vs. {value2.mtype} */")
1305 else if value2
.mtype
.ctype
!= "val*" then
1306 self.add
("{res} = 0; /* is_same_type_test: incompatible types {value1.mtype} vs. {value2.mtype}*/")
1308 var mtype1
= value1
.mtype
.as(MClassType)
1309 self.require_declaration
("class_{mtype1.c_name}")
1310 self.add
("{res} = ({value2} != NULL) && ({value2}->class == &class_{mtype1.c_name}); /* is_same_type_test */")
1313 self.add
("{res} = ({value1} == {value2}) || ({value1} != NULL && {value2} != NULL && {value1}->class == {value2}->class); /* is_same_type_test */")
1318 redef fun class_name_string
(value
)
1320 var res
= self.get_name
("var_class_name")
1321 self.add_decl
("const char* {res};")
1322 if value
.mtype
.ctype
== "val*" then
1323 self.add
"{res} = {value} == NULL ? \"null\
" : {value}->type->name;"
1325 self.require_declaration
("type_{value.mtype.c_name}")
1326 self.add
"{res} = type_{value.mtype.c_name}.name;"
1331 redef fun equal_test
(value1
, value2
)
1333 var res
= self.new_var
(bool_type
)
1334 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1339 if value1
.mtype
.ctype
!= "val*" then
1340 if value2
.mtype
== value1
.mtype
then
1341 self.add
("{res} = {value1} == {value2};")
1342 else if value2
.mtype
.ctype
!= "val*" then
1343 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
1345 var mtype1
= value1
.mtype
.as(MClassType)
1346 self.require_declaration
("class_{mtype1.c_name}")
1347 self.add
("{res} = ({value2} != NULL) && ({value2}->class == &class_{mtype1.c_name});")
1348 self.add
("if ({res}) \{")
1349 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
1354 var maybe_null
= true
1355 var test
= new Array[String]
1356 var t1
= value1
.mcasttype
1357 if t1
isa MNullableType then
1358 test
.add
("{value1} != NULL")
1363 var t2
= value2
.mcasttype
1364 if t2
isa MNullableType then
1365 test
.add
("{value2} != NULL")
1371 var incompatible
= false
1373 if t1
.ctype
!= "val*" then
1376 # No need to compare class
1377 else if t2
.ctype
!= "val*" then
1379 else if can_be_primitive
(value2
) then
1380 test
.add
("{value1}->class == {value2}->class")
1384 else if t2
.ctype
!= "val*" then
1386 if can_be_primitive
(value1
) then
1387 test
.add
("{value1}->class == {value2}->class")
1395 if incompatible
then
1397 self.add
("{res} = {value1} == {value2}; /* incompatible types {t1} vs. {t2}; but may be NULL*/")
1400 self.add
("{res} = 0; /* incompatible types {t1} vs. {t2}; cannot be NULL */")
1404 if primitive
!= null then
1405 test
.add
("((struct instance_{primitive.c_name}*){value1})->value == ((struct instance_{primitive.c_name}*){value2})->value")
1406 else if can_be_primitive
(value1
) and can_be_primitive
(value2
) then
1407 test
.add
("{value1}->class == {value2}->class")
1408 var s
= new Array[String]
1409 for t
, v
in self.compiler
.box_kinds
do
1410 s
.add
"({value1}->class->box_kind == {v} && ((struct instance_{t.c_name}*){value1})->value == ((struct instance_{t.c_name}*){value2})->value)"
1412 test
.add
("({s.join(" || ")})")
1414 self.add
("{res} = {value1} == {value2};")
1417 self.add
("{res} = {value1} == {value2} || ({test.join(" && ")});")
1421 fun can_be_primitive
(value
: RuntimeVariable): Bool
1423 var t
= value
.mcasttype
1424 if t
isa MNullableType then t
= t
.mtype
1425 if not t
isa MClassType then return false
1426 var k
= t
.mclass
.kind
1427 return k
== interface_kind
or t
.ctype
!= "val*"
1430 fun maybe_null
(value
: RuntimeVariable): Bool
1432 var t
= value
.mcasttype
1433 return t
isa MNullableType or t
isa MNullType
1436 redef fun array_instance
(array
, elttype
)
1438 var nclass
= self.get_class
("NativeArray")
1439 var arrayclass
= self.get_class
("Array")
1440 var arraytype
= arrayclass
.get_mtype
([elttype
])
1441 var res
= self.init_instance
(arraytype
)
1442 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
1443 var length
= self.int_instance
(array
.length
)
1444 var nat
= native_array_instance
(elttype
, length
)
1445 for i
in [0..array
.length
[ do
1446 var r
= self.autobox
(array
[i
], self.object_type
)
1447 self.add
("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
1449 self.send
(self.get_property
("with_native", arrayclass
.intro
.bound_mtype
), [res
, nat
, length
])
1450 self.check_init_instance
(res
, arraytype
)
1455 fun native_array_instance
(elttype
: MType, length
: RuntimeVariable): RuntimeVariable
1457 var mtype
= self.get_class
("NativeArray").get_mtype
([elttype
])
1458 self.require_declaration
("NEW_{mtype.mclass.c_name}")
1459 assert mtype
isa MGenericType
1460 var compiler
= self.compiler
1461 if mtype
.need_anchor
then
1462 link_unresolved_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1463 var recv
= self.frame
.arguments
.first
1464 var recv_type_info
= self.type_info
(recv
)
1465 self.require_declaration
(mtype
.const_color
)
1466 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1467 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
)
1469 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, {recv_type_info}->resolution_table->types[{mtype.const_color}])", mtype
)
1472 compiler
.undead_types
.add
(mtype
)
1473 self.require_declaration
("type_{mtype.c_name}")
1474 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, &type_{mtype.c_name})", mtype
)
1477 redef fun native_array_def
(pname
, ret_type
, arguments
)
1479 var elttype
= arguments
.first
.mtype
1480 var nclass
= self.get_class
("NativeArray")
1481 var recv
= "((struct instance_{nclass.c_name}*){arguments[0]})->values"
1482 if pname
== "[]" then
1483 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
1485 else if pname
== "[]=" then
1486 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
1488 else if pname
== "copy_to" then
1489 var recv1
= "((struct instance_{nclass.c_name}*){arguments[1]})->values"
1490 self.add
("memcpy({recv1}, {recv}, {arguments[2]}*sizeof({elttype.ctype}));")
1495 redef fun calloc_array
(ret_type
, arguments
)
1497 var mclass
= self.get_class
("ArrayCapable")
1498 var ft
= mclass
.mclass_type
.arguments
.first
.as(MParameterType)
1499 var res
= self.native_array_instance
(ft
, arguments
[1])
1503 fun link_unresolved_type
(mclassdef
: MClassDef, mtype
: MType) do
1504 assert mtype
.need_anchor
1505 var compiler
= self.compiler
1506 if not compiler
.live_unresolved_types
.has_key
(self.frame
.mpropdef
.mclassdef
) then
1507 compiler
.live_unresolved_types
[self.frame
.mpropdef
.mclassdef
] = new HashSet[MType]
1509 compiler
.live_unresolved_types
[self.frame
.mpropdef
.mclassdef
].add
(mtype
)
1513 redef class MMethodDef
1514 fun separate_runtime_function
: AbstractRuntimeFunction
1516 var res
= self.separate_runtime_function_cache
1518 res
= new SeparateRuntimeFunction(self)
1519 self.separate_runtime_function_cache
= res
1523 private var separate_runtime_function_cache
: nullable SeparateRuntimeFunction
1525 fun virtual_runtime_function
: AbstractRuntimeFunction
1527 var res
= self.virtual_runtime_function_cache
1529 res
= new VirtualRuntimeFunction(self)
1530 self.virtual_runtime_function_cache
= res
1534 private var virtual_runtime_function_cache
: nullable VirtualRuntimeFunction
1537 # The C function associated to a methoddef separately compiled
1538 class SeparateRuntimeFunction
1539 super AbstractRuntimeFunction
1541 redef fun build_c_name
: String do return "{mmethoddef.c_name}"
1543 redef fun to_s
do return self.mmethoddef
.to_s
1545 redef fun compile_to_c
(compiler
)
1547 var mmethoddef
= self.mmethoddef
1549 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
1550 var v
= compiler
.new_visitor
1551 var selfvar
= new RuntimeVariable("self", recv
, recv
)
1552 var arguments
= new Array[RuntimeVariable]
1553 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
1556 var msignature
= mmethoddef
.msignature
.resolve_for
(mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.mmodule
, true)
1558 var sig
= new Buffer
1559 var comment
= new Buffer
1560 var ret
= msignature
.return_mtype
1562 sig
.append
("{ret.ctype} ")
1563 else if mmethoddef
.mproperty
.is_new
then
1565 sig
.append
("{ret.ctype} ")
1569 sig
.append
(self.c_name
)
1570 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
1571 comment
.append
("({selfvar}: {selfvar.mtype}")
1572 arguments
.add
(selfvar
)
1573 for i
in [0..msignature
.arity
[ do
1574 var mtype
= msignature
.mparameters
[i
].mtype
1575 if i
== msignature
.vararg_rank
then
1576 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
1578 comment
.append
(", {mtype}")
1579 sig
.append
(", {mtype.ctype} p{i}")
1580 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
1581 arguments
.add
(argvar
)
1586 comment
.append
(": {ret}")
1588 compiler
.provide_declaration
(self.c_name
, "{sig};")
1590 v
.add_decl
("/* method {self} for {comment} */")
1591 v
.add_decl
("{sig} \{")
1593 frame
.returnvar
= v
.new_var
(ret
)
1595 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1597 if recv
!= arguments
.first
.mtype
then
1598 #print "{self} {recv} {arguments.first}"
1600 mmethoddef
.compile_inside_to_c
(v
, arguments
)
1602 v
.add
("{frame.returnlabel.as(not null)}:;")
1604 v
.add
("return {frame.returnvar.as(not null)};")
1610 # The C function associated to a methoddef on a primitive type, stored into a VFT of a class
1611 # The first parameter (the reciever) is always typed by val* in order to accept an object value
1612 class VirtualRuntimeFunction
1613 super AbstractRuntimeFunction
1615 redef fun build_c_name
: String do return "VIRTUAL_{mmethoddef.c_name}"
1617 redef fun to_s
do return self.mmethoddef
.to_s
1619 redef fun compile_to_c
(compiler
)
1621 var mmethoddef
= self.mmethoddef
1623 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
1624 var v
= compiler
.new_visitor
1625 var selfvar
= new RuntimeVariable("self", v
.object_type
, recv
)
1626 var arguments
= new Array[RuntimeVariable]
1627 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
1630 var sig
= new Buffer
1631 var comment
= new Buffer
1633 # Because the function is virtual, the signature must match the one of the original class
1634 var intromclassdef
= self.mmethoddef
.mproperty
.intro
.mclassdef
1635 var msignature
= mmethoddef
.mproperty
.intro
.msignature
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1636 var ret
= msignature
.return_mtype
1638 sig
.append
("{ret.ctype} ")
1639 else if mmethoddef
.mproperty
.is_new
then
1641 sig
.append
("{ret.ctype} ")
1645 sig
.append
(self.c_name
)
1646 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
1647 comment
.append
("({selfvar}: {selfvar.mtype}")
1648 arguments
.add
(selfvar
)
1649 for i
in [0..msignature
.arity
[ do
1650 var mtype
= msignature
.mparameters
[i
].mtype
1651 if i
== msignature
.vararg_rank
then
1652 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
1654 comment
.append
(", {mtype}")
1655 sig
.append
(", {mtype.ctype} p{i}")
1656 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
1657 arguments
.add
(argvar
)
1662 comment
.append
(": {ret}")
1664 compiler
.provide_declaration
(self.c_name
, "{sig};")
1666 v
.add_decl
("/* method {self} for {comment} */")
1667 v
.add_decl
("{sig} \{")
1669 frame
.returnvar
= v
.new_var
(ret
)
1671 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1673 var subret
= v
.call
(mmethoddef
, recv
, arguments
)
1675 assert subret
!= null
1676 v
.assign
(frame
.returnvar
.as(not null), subret
)
1679 v
.add
("{frame.returnlabel.as(not null)}:;")
1681 v
.add
("return {frame.returnvar.as(not null)};")
1687 redef fun call
(v
, arguments
) do abort
1691 fun const_color
: String do return "COLOR_{c_name}"
1694 redef class MProperty
1695 fun const_color
: String do return "COLOR_{c_name}"