1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2012 Jean Privat <jean@pryen.org>
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 # Global compilation of a Nit program
19 # Techniques used are:
20 # * heterogeneous generics
24 module global_compiler
26 import abstract_compiler
27 import rapid_type_analysis
29 redef class ModelBuilder
30 # Entry point to performs a global compilation on the AST of a complete program.
31 # `mainmodule` is the main module of the program
32 # `runtime_type_analysis` is a already computer type analysis.
33 fun run_global_compiler
(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis)
36 self.toolcontext
.info
("*** COMPILING TO C ***", 1)
38 var compiler
= new GlobalCompiler(mainmodule
, self, runtime_type_analysis
)
39 compiler
.compile_header
40 var v
= compiler
.header
42 for t
in runtime_type_analysis
.live_types
do
43 compiler
.declare_runtimeclass
(v
, t
)
46 compiler
.compile_class_names
48 # Init instance code (allocate and init-arguments)
49 for t
in runtime_type_analysis
.live_types
do
50 if t
.ctype
== "val*" then
51 compiler
.generate_init_instance
(t
)
52 compiler
.generate_check_init_instance
(t
)
54 compiler
.generate_box_instance
(t
)
58 # The main function of the C
59 compiler
.compile_main_function
61 # Compile until all runtime_functions are visited
62 while not compiler
.todos
.is_empty
do
63 var m
= compiler
.todos
.shift
64 self.toolcontext
.info
("Compile {m} ({compiler.seen.length-compiler.todos.length}/{compiler.seen.length})", 3)
65 m
.compile_to_c
(compiler
)
67 self.toolcontext
.info
("Total methods to compile to C: {compiler.visitors.length}", 2)
69 compiler
.display_stats
72 self.toolcontext
.info
("*** END VISITING: {time1-time0} ***", 2)
73 write_and_make
(compiler
)
77 # Compiler that use global compilation and perform hard optimisations like:
82 super AbstractCompiler
84 redef type VISITOR: GlobalCompilerVisitor
86 # The result of the RTA (used to know live types and methods)
87 var runtime_type_analysis
: RapidTypeAnalysis
89 init(mainmodule
: MModule, modelbuilder
: ModelBuilder, runtime_type_analysis
: RapidTypeAnalysis)
91 super(mainmodule
, modelbuilder
)
92 self.header
= new_visitor
93 self.runtime_type_analysis
= runtime_type_analysis
94 self.live_primitive_types
= new Array[MClassType]
95 for t
in runtime_type_analysis
.live_types
do
96 if t
.ctype
!= "val*" then
97 self.live_primitive_types
.add
(t
)
102 # Compile class names (for the class_name and output_class_name methods)
103 protected fun compile_class_names
do
104 self.header
.add_decl
("extern const char const * class_names[];")
105 self.header
.add
("const char const * class_names[] = \{")
106 for t
in self.runtime_type_analysis
.live_types
do
107 self.header
.add
("\"{t}\
", /* {self.classid(t)} */")
109 self.header
.add
("\};")
112 # Return the C symbol associated to a live type runtime
113 # REQUIRE: self.runtime_type_analysis.live_types.has(mtype)
114 fun classid
(mtype
: MClassType): String
116 if self.classids
.has_key
(mtype
) then
117 return self.classids
[mtype
]
119 print
"No classid for {mtype}"
124 protected var classids
: HashMap[MClassType, String] = new HashMap[MClassType, String]
126 # Declaration of structures the live Nit types
127 # Each live type is generated as an independent C `struct' type.
128 # They only share a common first field `classid` used to implement the polymorphism.
129 # Usualy, all C variables that refers to a Nit object are typed on the abstract struct `val' that contains only the `classid` field.
130 redef fun compile_header_structs
do
131 self.header
.add_decl
("typedef struct \{int classid;\} val; /* general C type representing a Nit instance. */")
134 # Subset of runtime_type_analysis.live_types that contains only primitive types
135 # Used to implement the equal test
136 var live_primitive_types
: Array[MClassType]
138 # Add a new todo task
139 fun todo
(m
: AbstractRuntimeFunction)
141 if seen
.has
(m
) then return
146 # runtime_functions that need to be compiled
147 private var todos
: List[AbstractRuntimeFunction] = new List[AbstractRuntimeFunction]
149 # runtime_functions already seen (todo or done)
150 private var seen
: HashSet[AbstractRuntimeFunction] = new HashSet[AbstractRuntimeFunction]
152 # Declare C structures and identifiers for a runtime class
153 fun declare_runtimeclass
(v
: VISITOR, mtype
: MClassType)
155 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
156 v
.add_decl
("/* runtime class {mtype} */")
157 var idnum
= classids
.length
158 var idname
= "ID_" + mtype
.c_name
159 self.classids
[mtype
] = idname
160 v
.add_decl
("#define {idname} {idnum} /* {mtype} */")
162 v
.add_decl
("struct {mtype.c_name} \{")
163 v
.add_decl
("int classid; /* must be {idname} */")
165 if mtype
.mclass
.name
== "NativeArray" then
166 # NativeArrays are just a instance header followed by an array of values
167 v
.add_decl
("{mtype.arguments.first.ctype} values[1];")
170 if mtype
.ctype
!= "val*" then
171 # Is the Nit type is native then the struct is a box with two fields:
172 # * the `classid` to be polymorph
173 # * the `value` that contains the native value.
174 v
.add_decl
("{mtype.ctype} value;")
177 # Collect all attributes and associate them a field in the structure.
178 # Note: we do not try to optimize the order and helps CC to optimize the client code.
179 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
180 for p
in cd
.intro_mproperties
do
181 if not p
isa MAttribute then continue
182 var t
= p
.intro
.static_mtype
.as(not null)
183 t
= t
.anchor_to
(self.mainmodule
, mtype
)
184 v
.add_decl
("{t.ctype} {p.intro.c_name}; /* {p}: {t} */")
190 # Generate the init-instance of a live type (allocate + init-instance)
191 fun generate_init_instance
(mtype
: MClassType)
193 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
194 assert mtype
.ctype
== "val*"
195 var v
= self.new_visitor
197 var is_native_array
= mtype
.mclass
.name
== "NativeArray"
200 if is_native_array
then
206 self.header
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig});")
207 v
.add_decl
("/* allocate {mtype} */")
208 v
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig}) \{")
209 var res
= v
.new_var
(mtype
)
211 if is_native_array
then
212 var mtype_elt
= mtype
.arguments
.first
213 v
.add
("{res} = GC_MALLOC(sizeof(struct {mtype.c_name}) + length*sizeof({mtype_elt.ctype}));")
215 v
.add
("{res} = GC_MALLOC(sizeof(struct {mtype.c_name}));")
217 v
.add
("{res}->classid = {self.classid(mtype)};")
219 self.generate_init_attr
(v
, res
, mtype
)
220 v
.add
("return {res};")
224 redef fun generate_check_init_instance
(mtype
)
226 if self.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
228 var v
= self.new_visitor
229 var res
= new RuntimeVariable("self", mtype
, mtype
)
230 self.header
.add_decl
("void CHECK_NEW_{mtype.c_name}({mtype.ctype});")
231 v
.add_decl
("/* allocate {mtype} */")
232 v
.add_decl
("void CHECK_NEW_{mtype.c_name}({mtype.ctype} {res}) \{")
233 self.generate_check_attr
(v
, res
, mtype
)
237 fun generate_box_instance
(mtype
: MClassType)
239 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
240 assert mtype
.ctype
!= "val*"
241 var v
= self.new_visitor
243 self.header
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype});")
244 v
.add_decl
("/* allocate {mtype} */")
245 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
246 v
.add
("struct {mtype.c_name}*res = GC_MALLOC(sizeof(struct {mtype.c_name}));")
247 v
.add
("res->classid = {self.classid(mtype)};")
248 v
.add
("res->value = value;")
249 v
.add
("return (val*)res;")
254 redef fun new_visitor
do return new GlobalCompilerVisitor(self)
256 private var collect_types_cache
: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
259 # A visitor on the AST of property definition that generate the C code.
260 # Because of inlining, a visitor can visit more than one property.
261 class GlobalCompilerVisitor
262 super AbstractCompilerVisitor
264 redef type COMPILER: GlobalCompiler
266 redef fun autobox
(value
, mtype
)
268 if value
.mtype
== mtype
then
270 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
272 else if value
.mtype
.ctype
== "val*" then
273 return self.new_expr
("((struct {mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
274 else if mtype
.ctype
== "val*" then
275 var valtype
= value
.mtype
.as(MClassType)
276 var res
= self.new_var
(mtype
)
277 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
278 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
279 self.add
("printf(\"Dead code executed
!\\n\
"); exit(1);")
282 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
285 # Bad things will appen!
286 var res
= self.new_var
(mtype
)
287 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
288 self.add
("printf(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); exit(1);")
293 # The runtime types that are acceptable for a given receiver.
294 fun collect_types
(recv
: RuntimeVariable): Array[MClassType]
296 var mtype
= recv
.mcasttype
297 if recv
.is_exact
then
298 assert mtype
isa MClassType
299 assert self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
)
303 var cache
= self.compiler
.collect_types_cache
304 if cache
.has_key
(mtype
) then
307 var types
= new Array[MClassType]
308 var mainmodule
= self.compiler
.mainmodule
309 for t
in self.compiler
.runtime_type_analysis
.live_types
do
310 if not t
.is_subtype
(mainmodule
, null, mtype
) then continue
317 redef fun native_array_def
(pname
, ret_type
, arguments
)
319 var elttype
= arguments
.first
.mtype
320 var recv
= "((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->values"
321 if pname
== "[]" then
322 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
324 else if pname
== "[]=" then
325 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
327 else if pname
== "copy_to" then
328 var recv1
= "((struct {arguments[1].mcasttype.c_name}*){arguments[1]})->values"
329 self.add
("memcpy({recv1},{recv},{arguments[2]}*sizeof({elttype.ctype}));")
334 redef fun calloc_array
(ret_type
, arguments
)
336 self.ret
(self.new_expr
("NEW_{ret_type.c_name}({arguments[1]})", ret_type
))
339 redef fun send
(m
, args
)
341 var types
= self.collect_types
(args
.first
)
343 var res
: nullable RuntimeVariable
344 var ret
= m
.intro
.msignature
.return_mtype
346 ret
= args
.first
.mtype
347 res
= self.new_var
(ret
)
348 else if ret
== null then
351 ret
= self.resolve_for
(ret
, args
.first
)
352 res
= self.new_var
(ret
)
355 self.add
("/* send {m} on {args.first.inspect} */")
356 if args
.first
.mtype
.ctype
!= "val*" then
357 var mclasstype
= args
.first
.mtype
.as(MClassType)
358 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
359 self.add
("/* skip, no method {m} */")
362 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, mclasstype
)
363 var res2
= self.call
(propdef
, mclasstype
, args
)
364 if res
!= null then self.assign
(res
, res2
.as(not null))
367 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
or m
.name
== "==" or m
.name
== "!="
368 if args
.first
.mcasttype
isa MNullableType or args
.first
.mcasttype
isa MNullType and consider_null
then
369 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
370 self.add
("if ({args.first} == NULL) \{ /* Special null case */")
371 if m
.name
== "==" then
373 if args
[1].mcasttype
isa MNullableType then
374 self.add
("{res} = ({args[1]} == NULL);")
375 else if args
[1].mcasttype
isa MNullType then
376 self.add
("{res} = 1; /* is null */")
378 self.add
("{res} = 0; /* {args[1].inspect} cannot be null */")
380 else if m
.name
== "!=" then
382 if args
[1].mcasttype
isa MNullableType then
383 self.add
("{res} = ({args[1]} != NULL);")
384 else if args
[1].mcasttype
isa MNullType then
385 self.add
("{res} = 0; /* is null */")
387 self.add
("{res} = 1; /* {args[1].inspect} cannot be null */")
390 self.add_abort
("Reciever is null")
394 if types
.is_empty
then
396 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
397 self.bugtype
(args
.first
)
402 self.add
("switch({args.first}->classid) \{")
403 var last
= types
.last
404 var defaultpropdef
: nullable MMethodDef = null
406 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, t
)
407 if propdef
.mclassdef
.mclass
.name
== "Object" and t
.ctype
== "val*" then
408 defaultpropdef
= propdef
411 if not self.compiler
.hardening
and t
== last
and defaultpropdef
== null then
412 self.add
("default: /* test {t} */")
414 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
416 var res2
= self.call
(propdef
, t
, args
)
417 if res
!= null then self.assign
(res
, res2
.as(not null))
420 if defaultpropdef
!= null then
421 self.add
("default: /* default is Object */")
422 var res2
= self.call
(defaultpropdef
, defaultpropdef
.mclassdef
.bound_mtype
, args
)
423 if res
!= null then self.assign
(res
, res2
.as(not null))
424 else if self.compiler
.hardening
then
425 self.add
("default: /* bug */")
426 self.bugtype
(args
.first
)
432 fun check_valid_reciever
(recvtype
: MClassType)
434 if self.compiler
.runtime_type_analysis
.live_types
.has
(recvtype
) or recvtype
.mclass
.name
== "Object" then return
435 print
"{recvtype} is not a live type"
439 redef fun call
(m
, recvtype
, args
)
441 check_valid_reciever
(recvtype
)
442 #debug("call {m} on {recvtype} on {args.first}:{args.first.mtype}")
443 if m
.mclassdef
.mclass
.name
== "Object" and recvtype
.ctype
== "val*" then
444 recvtype
= m
.mclassdef
.bound_mtype
446 var recv
= self.autobox
(args
.first
, recvtype
)
447 recv
= self.autoadapt
(recv
, recvtype
)
450 self.varargize
(m
, m
.msignature
.as(not null), args
)
451 if args
.length
!= m
.msignature
.arity
+ 1 then # because of self
452 add
("printf(\"NOT YET IMPLEMENTED: Invalid arity
for {m}. {args.length} arguments given
.\\n\
"); exit(1);")
453 debug
("NOT YET IMPLEMENTED: Invalid arity for {m}. {args.length} arguments given.")
458 var rm
= new CustomizedRuntimeFunction(m
, recvtype
)
459 return rm
.call
(self, args
)
462 redef fun supercall
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
464 var types
= self.collect_types
(args
.first
)
466 var res
: nullable RuntimeVariable
467 var ret
= m
.mproperty
.intro
.msignature
.return_mtype
471 ret
= self.resolve_for
(ret
, args
.first
)
472 res
= self.new_var
(ret
)
475 self.add
("/* super {m} on {args.first.inspect} */")
476 if args
.first
.mtype
.ctype
!= "val*" then
477 var mclasstype
= args
.first
.mtype
.as(MClassType)
478 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
479 self.add
("/* skip, no method {m} */")
482 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, mclasstype
)
483 var res2
= self.call
(propdef
, mclasstype
, args
)
484 if res
!= null then self.assign
(res
, res2
.as(not null))
488 if types
.is_empty
then
490 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
491 self.bugtype
(args
.first
)
496 self.add
("switch({args.first}->classid) \{")
497 var last
= types
.last
499 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, t
)
500 if not self.compiler
.hardening
and t
== last
then
501 self.add
("default: /* test {t} */")
503 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
505 var res2
= self.call
(propdef
, t
, args
)
506 if res
!= null then self.assign
(res
, res2
.as(not null))
509 if self.compiler
.hardening
then
510 self.add
("default: /* bug */")
511 self.bugtype
(args
.first
)
517 redef fun adapt_signature
(m
, args
)
519 var recv
= args
.first
520 for i
in [0..m
.msignature
.arity
[ do
521 var t
= m
.msignature
.mparameters
[i
].mtype
522 if i
== m
.msignature
.vararg_rank
then
525 t
= self.resolve_for
(t
, recv
)
526 args
[i
+1] = self.autobox
(args
[i
+1], t
)
530 # FIXME: this is currently buggy since recv is not exact
531 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
533 elttype
= self.resolve_for
(elttype
, recv
)
534 return self.array_instance
(varargs
, elttype
)
537 fun bugtype
(recv
: RuntimeVariable)
539 if recv
.mtype
.ctype
!= "val*" then return
540 self.add
("fprintf(stderr, \"BTD BUG: Dynamic type is %s
, static
type is %s\\n\
", class_names[{recv}->classid], \"{recv.mcasttype}\
");")
544 redef fun isset_attribute
(a
, recv
)
546 check_recv_notnull
(recv
)
548 var types
= self.collect_types
(recv
)
549 var res
= self.new_var
(bool_type
)
551 if types
.is_empty
then
552 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
556 self.add
("/* isset {a} on {recv.inspect} */")
557 self.add
("switch({recv}->classid) \{")
558 var last
= types
.last
560 if not self.compiler
.hardening
and t
== last
then
561 self.add
("default: /*{self.compiler.classid(t)}*/")
563 self.add
("case {self.compiler.classid(t)}:")
565 var recv2
= self.autoadapt
(recv
, t
)
566 var ta
= a
.intro
.static_mtype
.as(not null)
567 ta
= self.resolve_for
(ta
, recv2
)
568 var attr
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
569 if not ta
isa MNullableType then
570 if ta
.ctype
== "val*" then
571 self.add
("{res} = ({attr} != NULL);")
573 self.add
("{res} = 1; /*NOTYET isset on primitive attributes*/")
578 if self.compiler
.hardening
then
579 self.add
("default: /* Bug */")
587 redef fun read_attribute
(a
, recv
)
589 check_recv_notnull
(recv
)
591 var types
= self.collect_types
(recv
)
593 var ret
= a
.intro
.static_mtype
.as(not null)
594 ret
= self.resolve_for
(ret
, recv
)
595 var res
= self.new_var
(ret
)
597 if types
.is_empty
then
598 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
602 self.add
("/* read {a} on {recv.inspect} */")
603 self.add
("switch({recv}->classid) \{")
604 var last
= types
.last
606 if not self.compiler
.hardening
and t
== last
then
607 self.add
("default: /*{self.compiler.classid(t)}*/")
609 self.add
("case {self.compiler.classid(t)}:")
611 var recv2
= self.autoadapt
(recv
, t
)
612 var ta
= a
.intro
.static_mtype
.as(not null)
613 ta
= self.resolve_for
(ta
, recv2
)
614 var res2
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
615 if not ta
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
then
616 if ta
.ctype
== "val*" then
617 self.add
("if ({res2} == NULL) \{")
618 self.add_abort
("Uninitialized attribute {a.name}")
621 self.add
("/*NOTYET isset on primitive attributes*/")
624 self.assign
(res
, res2
)
627 if self.compiler
.hardening
then
628 self.add
("default: /* Bug */")
636 redef fun write_attribute
(a
, recv
, value
)
638 check_recv_notnull
(recv
)
640 var types
= self.collect_types
(recv
)
642 if types
.is_empty
then
643 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
647 self.add
("/* write {a} on {recv.inspect} */")
648 self.add
("switch({recv}->classid) \{")
649 var last
= types
.last
651 if not self.compiler
.hardening
and t
== last
then
652 self.add
("default: /*{self.compiler.classid(t)}*/")
654 self.add
("case {self.compiler.classid(t)}:")
656 var recv2
= self.autoadapt
(recv
, t
)
657 var ta
= a
.intro
.static_mtype
.as(not null)
658 ta
= self.resolve_for
(ta
, recv2
)
659 self.add
("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
662 if self.compiler
.hardening
then
663 self.add
("default: /* Bug*/")
669 redef fun init_instance
(mtype
)
671 mtype
= self.anchor
(mtype
).as(MClassType)
672 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
673 debug
"problem: {mtype} was detected dead"
675 var res
= self.new_expr
("NEW_{mtype.c_name}()", mtype
)
680 redef fun type_test
(value
, mtype
, tag
)
682 mtype
= self.anchor
(mtype
)
683 var mclasstype
= mtype
684 if mtype
isa MNullableType then mclasstype
= mtype
.mtype
685 assert mclasstype
isa MClassType
686 if not self.compiler
.runtime_type_analysis
.live_cast_types
.has
(mclasstype
) then
687 debug
"problem: {mtype} was detected cast-dead"
691 var types
= self.collect_types
(value
)
692 var res
= self.new_var
(bool_type
)
694 self.add
("/* isa {mtype} on {value.inspect} */")
695 if value
.mtype
.ctype
!= "val*" then
696 if value
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
697 self.add
("{res} = 1;")
699 self.add
("{res} = 0;")
703 if value
.mcasttype
isa MNullableType or value
.mcasttype
isa MNullType then
704 self.add
("if ({value} == NULL) \{")
705 if mtype
isa MNullableType then
706 self.add
("{res} = 1; /* isa {mtype} */")
708 self.add
("{res} = 0; /* not isa {mtype} */")
712 self.add
("switch({value}->classid) \{")
714 if t
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
715 self.add
("case {self.compiler.classid(t)}: /* {t} */")
718 self.add
("{res} = 1;")
721 self.add
("{res} = 0;")
727 redef fun is_same_type_test
(value1
, value2
)
729 var res
= self.new_var
(bool_type
)
730 if value2
.mtype
.ctype
== "val*" then
731 if value1
.mtype
.ctype
== "val*" then
732 self.add
"{res} = {value1}->classid == {value2}->classid;"
734 self.add
"{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
737 if value1
.mtype
.ctype
== "val*" then
738 self.add
"{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
739 else if value1
.mcasttype
== value2
.mcasttype
then
740 self.add
"{res} = 1;"
742 self.add
"{res} = 0;"
748 redef fun class_name_string
(value
)
750 var res
= self.get_name
("var_class_name")
751 self.add_decl
("const char* {res};")
752 if value
.mtype
.ctype
== "val*" then
753 self.add
"{res} = class_names[{value}->classid];"
755 self.add
"{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
760 redef fun equal_test
(value1
, value2
)
762 var res
= self.new_var
(bool_type
)
763 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
768 if value1
.mtype
.ctype
!= "val*" then
769 if value2
.mtype
== value1
.mtype
then
770 self.add
("{res} = {value1} == {value2};")
771 else if value2
.mtype
.ctype
!= "val*" then
772 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
774 var mtype1
= value1
.mtype
.as(MClassType)
775 self.add
("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
776 self.add
("if ({res}) \{")
777 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
781 var s
= new Array[String]
782 for t
in self.compiler
.live_primitive_types
do
783 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value1
.mcasttype
) then continue
784 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value2
.mcasttype
) then continue
785 s
.add
"({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
788 self.add
("{res} = {value1} == {value2};")
790 self.add
("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
796 redef fun check_init_instance
(recv
, mtype
)
798 if self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
800 mtype
= self.anchor
(mtype
).as(MClassType)
801 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
802 debug
"problem: {mtype} was detected dead"
805 self.add
("CHECK_NEW_{mtype.c_name}({recv});")
808 redef fun array_instance
(array
, elttype
)
810 elttype
= self.anchor
(elttype
)
811 var arraytype
= self.get_class
("Array").get_mtype
([elttype
])
812 var res
= self.init_instance
(arraytype
)
813 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
814 var nat
= self.new_var
(self.get_class
("NativeArray").get_mtype
([elttype
]))
816 self.add
("{nat} = NEW_{nat.mtype.c_name}({array.length});")
817 for i
in [0..array
.length
[ do
818 var r
= self.autobox
(array
[i
], elttype
)
819 self.add
("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
821 var length
= self.int_instance
(array
.length
)
822 self.send
(self.get_property
("with_native", arraytype
), [res
, nat
, length
])
823 self.check_init_instance
(res
, arraytype
)
829 # A runtime function customized on a specific monomrph receiver type
830 private class CustomizedRuntimeFunction
831 super AbstractRuntimeFunction
833 redef type COMPILER: GlobalCompiler
834 redef type VISITOR: GlobalCompilerVisitor
836 # The considered reciever
837 # (usually is a live type but no strong guarantee)
840 init(mmethoddef
: MMethodDef, recv
: MClassType)
846 redef fun build_c_name
848 var res
= self.c_name_cache
849 if res
!= null then return res
850 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
851 res
= self.mmethoddef
.c_name
853 res
= "{mmethoddef.c_name}__{recv.c_name}"
855 self.c_name_cache
= res
859 # used in the compiler worklist
862 if not o
isa CustomizedRuntimeFunction then return false
863 if self.mmethoddef
!= o
.mmethoddef
then return false
864 if self.recv
!= o
.recv
then return false
868 # used in the compiler work-list
869 redef fun hash
do return self.mmethoddef
.hash
+ self.recv
.hash
873 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
874 return self.mmethoddef
.to_s
876 return "{self.mmethoddef}@{self.recv}"
880 # compile the code customized for the reciever
881 redef fun compile_to_c
(compiler
)
884 var mmethoddef
= self.mmethoddef
885 if not recv
.is_subtype
(compiler
.mainmodule
, null, mmethoddef
.mclassdef
.bound_mtype
) then
886 print
("problem: why do we compile {self} for {recv}?")
890 var v
= compiler
.new_visitor
891 var selfvar
= new RuntimeVariable("self", recv
, recv
)
892 if compiler
.runtime_type_analysis
.live_types
.has
(recv
) then
893 selfvar
.is_exact
= true
895 var arguments
= new Array[RuntimeVariable]
896 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
900 var comment
= new Buffer
901 var ret
= mmethoddef
.msignature
.return_mtype
903 ret
= v
.resolve_for
(ret
, selfvar
)
904 sig
.append
("{ret.ctype} ")
905 else if mmethoddef
.mproperty
.is_new
then
907 sig
.append
("{ret.ctype} ")
911 sig
.append
(self.c_name
)
912 sig
.append
("({recv.ctype} {selfvar}")
913 comment
.append
("(self: {recv}")
914 arguments
.add
(selfvar
)
915 for i
in [0..mmethoddef
.msignature
.arity
[ do
916 var mtype
= mmethoddef
.msignature
.mparameters
[i
].mtype
917 if i
== mmethoddef
.msignature
.vararg_rank
then
918 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
920 mtype
= v
.resolve_for
(mtype
, selfvar
)
921 comment
.append
(", {mtype}")
922 sig
.append
(", {mtype.ctype} p{i}")
923 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
924 arguments
.add
(argvar
)
929 comment
.append
(": {ret}")
931 compiler
.header
.add_decl
("{sig};")
933 v
.add_decl
("/* method {self} for {comment} */")
934 v
.add_decl
("{sig} \{")
935 #v.add("printf(\"method {self} for {comment}\\n\");")
937 frame
.returnvar
= v
.new_var
(ret
)
939 frame
.returnlabel
= v
.get_name
("RET_LABEL")
941 mmethoddef
.compile_inside_to_c
(v
, arguments
)
943 v
.add
("{frame.returnlabel.as(not null)}:;")
945 v
.add
("return {frame.returnvar.as(not null)};")
950 redef fun call
(v
: VISITOR, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
952 var ret
= self.mmethoddef
.msignature
.return_mtype
953 if self.mmethoddef
.mproperty
.is_new
then
957 ret
= v
.resolve_for
(ret
, arguments
.first
)
959 if self.mmethoddef
.can_inline
(v
) then
960 var frame
= new Frame(v
, self.mmethoddef
, self.recv
, arguments
)
961 frame
.returnlabel
= v
.get_name
("RET_LABEL")
963 frame
.returnvar
= v
.new_var
(ret
)
965 var old_frame
= v
.frame
967 v
.add
("\{ /* Inline {self} ({arguments.join(",")}) */")
968 self.mmethoddef
.compile_inside_to_c
(v
, arguments
)
969 v
.add
("{frame.returnlabel.as(not null)}:(void)0;")
972 return frame
.returnvar
974 v
.adapt_signature
(self.mmethoddef
, arguments
)
975 v
.compiler
.todo
(self)
977 v
.add
("{self.c_name}({arguments.join(",")});")
980 var res
= v
.new_var
(ret
)
981 v
.add
("{res} = {self.c_name}({arguments.join(",")});")