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
30 redef class ModelBuilder
31 # Entry point to performs a global compilation on the AST of a complete program.
32 # `mainmodule` is the main module of the program
33 # `runtime_type_analysis` is a already computer type analysis.
34 fun run_global_compiler
(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis)
37 self.toolcontext
.info
("*** GENERATING C ***", 1)
39 var compiler
= new GlobalCompiler(mainmodule
, self, runtime_type_analysis
)
40 compiler
.compile_header
42 for t
in runtime_type_analysis
.live_types
do
43 compiler
.declare_runtimeclass
(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
)
53 compiler
.generate_box_instance
(t
)
57 # The main function of the C
58 compiler
.compile_main_function
60 # Compile until all runtime_functions are visited
61 while not compiler
.todos
.is_empty
do
62 var m
= compiler
.todos
.shift
63 self.toolcontext
.info
("Compile {m} ({compiler.seen.length-compiler.todos.length}/{compiler.seen.length})", 3)
64 m
.compile_to_c
(compiler
)
66 self.toolcontext
.info
("Total methods to compile to C: {compiler.seen.length}", 2)
68 compiler
.display_stats
71 self.toolcontext
.info
("*** END GENERATING C: {time1-time0} ***", 2)
72 write_and_make
(compiler
)
76 # Compiler that use global compilation and perform hard optimisations like:
81 super AbstractCompiler
83 redef type VISITOR: GlobalCompilerVisitor
85 # The result of the RTA (used to know live types and methods)
86 var runtime_type_analysis
: RapidTypeAnalysis
88 init(mainmodule
: MModule, modelbuilder
: ModelBuilder, runtime_type_analysis
: RapidTypeAnalysis)
90 super(mainmodule
, modelbuilder
)
91 var file
= new_file
("{mainmodule.name}.nitgg")
92 self.header
= new CodeWriter(file
)
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
105 self.header
.add_decl
("extern const char const * class_names[];")
106 v
.add
("const char const * class_names[] = \{")
107 for t
in self.runtime_type_analysis
.live_types
do
108 v
.add
("\"{t}\
", /* {self.classid(t)} */")
113 # Return the C symbol associated to a live type runtime
114 # REQUIRE: self.runtime_type_analysis.live_types.has(mtype)
115 fun classid
(mtype
: MClassType): String
117 if self.classids
.has_key
(mtype
) then
118 return self.classids
[mtype
]
120 print
"No classid for {mtype}"
125 protected var classids
: HashMap[MClassType, String] = new HashMap[MClassType, String]
127 # Declaration of structures the live Nit types
128 # Each live type is generated as an independent C `struct` type.
129 # They only share a common first field `classid` used to implement the polymorphism.
130 # Usualy, all C variables that refers to a Nit object are typed on the abstract struct `val` that contains only the `classid` field.
131 redef fun compile_header_structs
do
132 self.header
.add_decl
("typedef struct \{int classid;\} val; /* general C type representing a Nit instance. */")
135 # Subset of runtime_type_analysis.live_types that contains only primitive types
136 # Used to implement the equal test
137 var live_primitive_types
: Array[MClassType]
139 # Add a new todo task
140 fun todo
(m
: AbstractRuntimeFunction)
142 if seen
.has
(m
) then return
147 # runtime_functions that need to be compiled
148 private var todos
: List[AbstractRuntimeFunction] = new List[AbstractRuntimeFunction]
150 # runtime_functions already seen (todo or done)
151 private var seen
: HashSet[AbstractRuntimeFunction] = new HashSet[AbstractRuntimeFunction]
153 # Declare C structures and identifiers for a runtime class
154 fun declare_runtimeclass
(mtype
: MClassType)
157 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
158 v
.add_decl
("/* runtime class {mtype} */")
159 var idnum
= classids
.length
160 var idname
= "ID_" + mtype
.c_name
161 self.classids
[mtype
] = idname
162 v
.add_decl
("#define {idname} {idnum} /* {mtype} */")
164 v
.add_decl
("struct {mtype.c_name} \{")
165 v
.add_decl
("int classid; /* must be {idname} */")
167 if mtype
.mclass
.name
== "NativeArray" then
168 # NativeArrays are just a instance header followed by an array of values
169 v
.add_decl
("{mtype.arguments.first.ctype} values[1];")
172 if mtype
.ctype
!= "val*" then
173 # Is the Nit type is native then the struct is a box with two fields:
174 # * the `classid` to be polymorph
175 # * the `value` that contains the native value.
176 v
.add_decl
("{mtype.ctype} value;")
179 # Collect all attributes and associate them a field in the structure.
180 # Note: we do not try to optimize the order and helps CC to optimize the client code.
181 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
182 for p
in cd
.intro_mproperties
do
183 if not p
isa MAttribute then continue
184 var t
= p
.intro
.static_mtype
.as(not null)
185 t
= t
.anchor_to
(self.mainmodule
, mtype
)
186 v
.add_decl
("{t.ctype} {p.intro.c_name}; /* {p}: {t} */")
192 # Generate the init-instance of a live type (allocate + init-instance)
193 fun generate_init_instance
(mtype
: MClassType)
195 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
196 assert mtype
.ctype
== "val*"
197 var v
= self.new_visitor
199 var is_native_array
= mtype
.mclass
.name
== "NativeArray"
202 if is_native_array
then
208 self.header
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig});")
209 v
.add_decl
("/* allocate {mtype} */")
210 v
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig}) \{")
211 var res
= v
.new_var
(mtype
)
213 if is_native_array
then
214 var mtype_elt
= mtype
.arguments
.first
215 v
.add
("{res} = nit_alloc(sizeof(struct {mtype.c_name}) + length*sizeof({mtype_elt.ctype}));")
217 v
.add
("{res} = nit_alloc(sizeof(struct {mtype.c_name}));")
219 v
.add
("{res}->classid = {self.classid(mtype)};")
221 self.generate_init_attr
(v
, res
, mtype
)
222 v
.add
("return {res};")
226 fun generate_box_instance
(mtype
: MClassType)
228 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
229 assert mtype
.ctype
!= "val*"
230 var v
= self.new_visitor
232 self.header
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype});")
233 v
.add_decl
("/* allocate {mtype} */")
234 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
235 v
.add
("struct {mtype.c_name}*res = nit_alloc(sizeof(struct {mtype.c_name}));")
236 v
.add
("res->classid = {self.classid(mtype)};")
237 v
.add
("res->value = value;")
238 v
.add
("return (val*)res;")
242 redef fun new_visitor
do return new GlobalCompilerVisitor(self)
244 private var collect_types_cache
: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
246 redef fun compile_nitni_structs
248 self.header
.add_decl
("struct nitni_instance \{ val *value; \};")
251 redef fun supports_ffi
do return true
254 # A visitor on the AST of property definition that generate the C code.
255 # Because of inlining, a visitor can visit more than one property.
256 class GlobalCompilerVisitor
257 super AbstractCompilerVisitor
259 redef type COMPILER: GlobalCompiler
261 redef fun autobox
(value
, mtype
)
263 if value
.mtype
== mtype
then
265 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
267 else if value
.mtype
.ctype
== "val*" then
268 return self.new_expr
("((struct {mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
269 else if mtype
.ctype
== "val*" then
270 var valtype
= value
.mtype
.as(MClassType)
271 var res
= self.new_var
(mtype
)
272 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
273 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
274 self.add
("printf(\"Dead code executed
!\\n\
"); show_backtrace(1);")
277 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
279 else if value
.mtype
.cname_blind
== "void*" and mtype
.cname_blind
== "void*" then
282 # Bad things will appen!
283 var res
= self.new_var
(mtype
)
284 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
285 self.add
("printf(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); show_backtrace(1);")
290 # The runtime types that are acceptable for a given receiver.
291 fun collect_types
(recv
: RuntimeVariable): Array[MClassType]
293 var mtype
= recv
.mcasttype
294 if recv
.is_exact
then
295 assert mtype
isa MClassType
296 assert self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
)
300 var cache
= self.compiler
.collect_types_cache
301 if cache
.has_key
(mtype
) then
304 var types
= new Array[MClassType]
305 var mainmodule
= self.compiler
.mainmodule
306 for t
in self.compiler
.runtime_type_analysis
.live_types
do
307 if not t
.is_subtype
(mainmodule
, null, mtype
) then continue
314 redef fun native_array_def
(pname
, ret_type
, arguments
)
316 var elttype
= arguments
.first
.mtype
317 var recv
= "((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->values"
318 if pname
== "[]" then
319 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
321 else if pname
== "[]=" then
322 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
324 else if pname
== "copy_to" then
325 var recv1
= "((struct {arguments[1].mcasttype.c_name}*){arguments[1]})->values"
326 self.add
("memcpy({recv1},{recv},{arguments[2]}*sizeof({elttype.ctype}));")
331 redef fun calloc_array
(ret_type
, arguments
)
333 self.ret
(self.new_expr
("NEW_{ret_type.c_name}({arguments[1]})", ret_type
))
336 redef fun send
(m
, args
)
338 var types
= self.collect_types
(args
.first
)
340 var res
: nullable RuntimeVariable
341 var ret
= m
.intro
.msignature
.return_mtype
343 ret
= args
.first
.mtype
344 res
= self.new_var
(ret
)
345 else if ret
== null then
348 ret
= self.resolve_for
(ret
, args
.first
)
349 res
= self.new_var
(ret
)
352 self.add
("/* send {m} on {args.first.inspect} */")
353 if args
.first
.mtype
.ctype
!= "val*" then
354 var mclasstype
= args
.first
.mtype
.as(MClassType)
355 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
356 self.add
("/* skip, no method {m} */")
359 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, mclasstype
)
360 var res2
= self.call
(propdef
, mclasstype
, args
)
361 if res
!= null then self.assign
(res
, res2
.as(not null))
364 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
or m
.name
== "==" or m
.name
== "!="
365 if args
.first
.mcasttype
isa MNullableType or args
.first
.mcasttype
isa MNullType and consider_null
then
366 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
367 self.add
("if ({args.first} == NULL) \{ /* Special null case */")
368 if m
.name
== "==" then
370 if args
[1].mcasttype
isa MNullableType then
371 self.add
("{res} = ({args[1]} == NULL);")
372 else if args
[1].mcasttype
isa MNullType then
373 self.add
("{res} = 1; /* is null */")
375 self.add
("{res} = 0; /* {args[1].inspect} cannot be null */")
377 else if m
.name
== "!=" then
379 if args
[1].mcasttype
isa MNullableType then
380 self.add
("{res} = ({args[1]} != NULL);")
381 else if args
[1].mcasttype
isa MNullType then
382 self.add
("{res} = 0; /* is null */")
384 self.add
("{res} = 1; /* {args[1].inspect} cannot be null */")
387 self.add_abort
("Receiver is null")
391 if types
.is_empty
then
393 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
394 self.bugtype
(args
.first
)
399 self.add
("switch({args.first}->classid) \{")
400 var last
= types
.last
401 var defaultpropdef
: nullable MMethodDef = null
403 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, t
)
404 if propdef
.mclassdef
.mclass
.name
== "Object" and t
.ctype
== "val*" then
405 defaultpropdef
= propdef
408 if not self.compiler
.hardening
and t
== last
and defaultpropdef
== null then
409 self.add
("default: /* test {t} */")
411 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
413 var res2
= self.call
(propdef
, t
, args
)
414 if res
!= null then self.assign
(res
, res2
.as(not null))
417 if defaultpropdef
!= null then
418 self.add
("default: /* default is Object */")
419 var res2
= self.call
(defaultpropdef
, defaultpropdef
.mclassdef
.bound_mtype
, args
)
420 if res
!= null then self.assign
(res
, res2
.as(not null))
421 else if self.compiler
.hardening
then
422 self.add
("default: /* bug */")
423 self.bugtype
(args
.first
)
429 fun check_valid_reciever
(recvtype
: MClassType)
431 if self.compiler
.runtime_type_analysis
.live_types
.has
(recvtype
) or recvtype
.mclass
.name
== "Object" then return
432 print
"{recvtype} is not a live type"
436 # Subpart of old call function
438 # Checks if the type of the receiver is valid and corrects it if necessary
439 private fun get_recvtype
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): MClassType
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
449 # Subpart of old call function
450 # Gets the receiver boxed and casted if necessary
451 private fun get_recv
(recvtype
: MClassType, args
: Array[RuntimeVariable]): RuntimeVariable
453 return self.autoadapt
(self.autobox
(args
.first
, recvtype
), recvtype
)
456 # Finalizes a call to a method ´m´ on type ´recvtype´ with arguments ´args´
457 private fun finalize_call
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
459 assert args
.length
== m
.msignature
.arity
+ 1 else debug
("Invalid arity for {m}. {args.length} arguments given.")
461 var rm
= new CustomizedRuntimeFunction(m
, recvtype
)
462 return rm
.call
(self, args
)
465 redef fun call
(m
, recvtype
, args
)
467 var recv_type
= get_recvtype
(m
, recvtype
, args
)
468 var recv
= get_recv
(recv_type
, args
)
469 var new_args
= args
.to_a
470 self.varargize
(m
, m
.msignature
.as(not null), new_args
)
471 new_args
.first
= recv
472 return finalize_call
(m
, recv_type
, new_args
)
475 # Does a call without encapsulating varargs into an array
476 # Avoids multiple encapsulation when calling a super in a variadic function
477 fun call_without_varargize
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
479 var recv_type
= get_recvtype
(m
, recvtype
, args
)
480 var recv
= get_recv
(recv_type
, args
)
481 var new_args
= args
.to_a
482 new_args
.first
= recv
483 return finalize_call
(m
, recv_type
, new_args
)
486 redef fun supercall
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
488 var types
= self.collect_types
(args
.first
)
490 var res
: nullable RuntimeVariable
491 var ret
= m
.mproperty
.intro
.msignature
.return_mtype
495 ret
= self.resolve_for
(ret
, args
.first
)
496 res
= self.new_var
(ret
)
499 self.add
("/* super {m} on {args.first.inspect} */")
500 if args
.first
.mtype
.ctype
!= "val*" then
501 var mclasstype
= args
.first
.mtype
.as(MClassType)
502 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
503 self.add
("/* skip, no method {m} */")
506 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, mclasstype
)
507 var res2
= self.call_without_varargize
(propdef
, mclasstype
, args
)
508 if res
!= null then self.assign
(res
, res2
.as(not null))
512 if types
.is_empty
then
514 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
515 self.bugtype
(args
.first
)
520 self.add
("switch({args.first}->classid) \{")
521 var last
= types
.last
523 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, t
)
524 if not self.compiler
.hardening
and t
== last
then
525 self.add
("default: /* test {t} */")
527 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
529 var res2
= self.call_without_varargize
(propdef
, t
, args
)
530 if res
!= null then self.assign
(res
, res2
.as(not null))
533 if self.compiler
.hardening
then
534 self.add
("default: /* bug */")
535 self.bugtype
(args
.first
)
541 redef fun adapt_signature
(m
, args
)
543 var recv
= args
.first
544 for i
in [0..m
.msignature
.arity
[ do
545 var t
= m
.msignature
.mparameters
[i
].mtype
546 if i
== m
.msignature
.vararg_rank
then
549 t
= self.resolve_for
(t
, recv
)
550 args
[i
+1] = self.autobox
(args
[i
+1], t
)
554 # FIXME: this is currently buggy since recv is not exact
555 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
557 elttype
= self.resolve_for
(elttype
, recv
)
558 return self.array_instance
(varargs
, elttype
)
561 fun bugtype
(recv
: RuntimeVariable)
563 if recv
.mtype
.ctype
!= "val*" then return
564 self.add
("fprintf(stderr, \"BTD BUG: Dynamic type is %s
, static
type is %s\\n\
", class_names[{recv}->classid], \"{recv.mcasttype}\
");")
565 self.add
("show_backtrace(1);")
568 redef fun isset_attribute
(a
, recv
)
570 check_recv_notnull
(recv
)
572 var types
= self.collect_types
(recv
)
573 var res
= self.new_var
(bool_type
)
575 if types
.is_empty
then
576 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
580 self.add
("/* isset {a} on {recv.inspect} */")
581 self.add
("switch({recv}->classid) \{")
582 var last
= types
.last
584 if not self.compiler
.hardening
and t
== last
then
585 self.add
("default: /*{self.compiler.classid(t)}*/")
587 self.add
("case {self.compiler.classid(t)}:")
589 var recv2
= self.autoadapt
(recv
, t
)
590 var ta
= a
.intro
.static_mtype
.as(not null)
591 ta
= self.resolve_for
(ta
, recv2
)
592 var attr
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
593 if not ta
isa MNullableType then
594 if ta
.ctype
== "val*" then
595 self.add
("{res} = ({attr} != NULL);")
597 self.add
("{res} = 1; /*NOTYET isset on primitive attributes*/")
602 if self.compiler
.hardening
then
603 self.add
("default: /* Bug */")
611 redef fun read_attribute
(a
, recv
)
613 check_recv_notnull
(recv
)
615 var types
= self.collect_types
(recv
)
617 var ret
= a
.intro
.static_mtype
.as(not null)
618 ret
= self.resolve_for
(ret
, recv
)
619 var res
= self.new_var
(ret
)
621 if types
.is_empty
then
622 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
626 self.add
("/* read {a} on {recv.inspect} */")
627 self.add
("switch({recv}->classid) \{")
628 var last
= types
.last
630 if not self.compiler
.hardening
and t
== last
then
631 self.add
("default: /*{self.compiler.classid(t)}*/")
633 self.add
("case {self.compiler.classid(t)}:")
635 var recv2
= self.autoadapt
(recv
, t
)
636 var ta
= a
.intro
.static_mtype
.as(not null)
637 ta
= self.resolve_for
(ta
, recv2
)
638 var res2
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
639 if not ta
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
then
640 if ta
.ctype
== "val*" then
641 self.add
("if ({res2} == NULL) \{")
642 self.add_abort
("Uninitialized attribute {a.name}")
645 self.add
("/*NOTYET isset on primitive attributes*/")
648 self.assign
(res
, res2
)
651 if self.compiler
.hardening
then
652 self.add
("default: /* Bug */")
660 redef fun write_attribute
(a
, recv
, value
)
662 check_recv_notnull
(recv
)
664 var types
= self.collect_types
(recv
)
666 if types
.is_empty
then
667 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
671 self.add
("/* write {a} on {recv.inspect} */")
672 self.add
("switch({recv}->classid) \{")
673 var last
= types
.last
675 if not self.compiler
.hardening
and t
== last
then
676 self.add
("default: /*{self.compiler.classid(t)}*/")
678 self.add
("case {self.compiler.classid(t)}:")
680 var recv2
= self.autoadapt
(recv
, t
)
681 var ta
= a
.intro
.static_mtype
.as(not null)
682 ta
= self.resolve_for
(ta
, recv2
)
683 self.add
("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
686 if self.compiler
.hardening
then
687 self.add
("default: /* Bug*/")
693 redef fun init_instance
(mtype
)
695 mtype
= self.anchor
(mtype
).as(MClassType)
696 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
697 debug
"problem: {mtype} was detected dead"
699 var res
= self.new_expr
("NEW_{mtype.c_name}()", mtype
)
704 redef fun type_test
(value
, mtype
, tag
)
706 mtype
= self.anchor
(mtype
)
707 if not self.compiler
.runtime_type_analysis
.live_cast_types
.has
(mtype
) then
708 debug
"problem: {mtype} was detected cast-dead"
712 var types
= self.collect_types
(value
)
713 var res
= self.new_var
(bool_type
)
715 self.add
("/* isa {mtype} on {value.inspect} */")
716 if value
.mtype
.ctype
!= "val*" then
717 if value
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
718 self.add
("{res} = 1;")
720 self.add
("{res} = 0;")
724 if value
.mcasttype
isa MNullableType or value
.mcasttype
isa MNullType then
725 self.add
("if ({value} == NULL) \{")
726 if mtype
isa MNullableType then
727 self.add
("{res} = 1; /* isa {mtype} */")
729 self.add
("{res} = 0; /* not isa {mtype} */")
733 self.add
("switch({value}->classid) \{")
735 if t
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
736 self.add
("case {self.compiler.classid(t)}: /* {t} */")
739 self.add
("{res} = 1;")
742 self.add
("{res} = 0;")
748 redef fun is_same_type_test
(value1
, value2
)
750 var res
= self.new_var
(bool_type
)
751 if value2
.mtype
.ctype
== "val*" then
752 if value1
.mtype
.ctype
== "val*" then
753 self.add
"{res} = {value1}->classid == {value2}->classid;"
755 self.add
"{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
758 if value1
.mtype
.ctype
== "val*" then
759 self.add
"{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
760 else if value1
.mcasttype
== value2
.mcasttype
then
761 self.add
"{res} = 1;"
763 self.add
"{res} = 0;"
769 redef fun class_name_string
(value
)
771 var res
= self.get_name
("var_class_name")
772 self.add_decl
("const char* {res};")
773 if value
.mtype
.ctype
== "val*" then
774 self.add
"{res} = class_names[{value}->classid];"
776 self.add
"{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
781 redef fun equal_test
(value1
, value2
)
783 var res
= self.new_var
(bool_type
)
784 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
789 if value1
.mtype
.ctype
!= "val*" then
790 if value2
.mtype
== value1
.mtype
then
791 self.add
("{res} = {value1} == {value2};")
792 else if value2
.mtype
.ctype
!= "val*" then
793 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
795 var mtype1
= value1
.mtype
.as(MClassType)
796 self.add
("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
797 self.add
("if ({res}) \{")
798 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
802 var s
= new Array[String]
803 for t
in self.compiler
.live_primitive_types
do
804 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value1
.mcasttype
) then continue
805 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value2
.mcasttype
) then continue
806 s
.add
"({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
809 self.add
("{res} = {value1} == {value2};")
811 self.add
("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
817 redef fun array_instance
(array
, elttype
)
819 elttype
= self.anchor
(elttype
)
820 var arraytype
= self.get_class
("Array").get_mtype
([elttype
])
821 var res
= self.init_instance
(arraytype
)
822 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
823 var nat
= self.new_var
(self.get_class
("NativeArray").get_mtype
([elttype
]))
825 self.add
("{nat} = NEW_{nat.mtype.c_name}({array.length});")
826 for i
in [0..array
.length
[ do
827 var r
= self.autobox
(array
[i
], elttype
)
828 self.add
("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
830 var length
= self.int_instance
(array
.length
)
831 self.send
(self.get_property
("with_native", arraytype
), [res
, nat
, length
])
837 # A runtime function customized on a specific monomrph receiver type
838 private class CustomizedRuntimeFunction
839 super AbstractRuntimeFunction
841 redef type COMPILER: GlobalCompiler
842 redef type VISITOR: GlobalCompilerVisitor
844 # The considered reciever
845 # (usually is a live type but no strong guarantee)
848 init(mmethoddef
: MMethodDef, recv
: MClassType)
854 redef fun build_c_name
856 var res
= self.c_name_cache
857 if res
!= null then return res
858 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
859 res
= self.mmethoddef
.c_name
861 res
= "{mmethoddef.c_name}__{recv.c_name}"
863 self.c_name_cache
= res
867 # used in the compiler worklist
870 if not o
isa CustomizedRuntimeFunction then return false
871 if self.mmethoddef
!= o
.mmethoddef
then return false
872 if self.recv
!= o
.recv
then return false
876 # used in the compiler work-list
877 redef fun hash
do return self.mmethoddef
.hash
+ self.recv
.hash
881 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
882 return self.mmethoddef
.to_s
884 return "{self.mmethoddef}@{self.recv}"
888 # compile the code customized for the reciever
889 redef fun compile_to_c
(compiler
)
892 var mmethoddef
= self.mmethoddef
893 if not recv
.is_subtype
(compiler
.mainmodule
, null, mmethoddef
.mclassdef
.bound_mtype
) then
894 print
("problem: why do we compile {self} for {recv}?")
898 var v
= compiler
.new_visitor
899 var selfvar
= new RuntimeVariable("self", recv
, recv
)
900 if compiler
.runtime_type_analysis
.live_types
.has
(recv
) then
901 selfvar
.is_exact
= true
903 var arguments
= new Array[RuntimeVariable]
904 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
907 var sig
= new FlatBuffer
908 var comment
= new FlatBuffer
909 var ret
= mmethoddef
.msignature
.return_mtype
911 ret
= v
.resolve_for
(ret
, selfvar
)
912 sig
.append
("{ret.ctype} ")
913 else if mmethoddef
.mproperty
.is_new
then
915 sig
.append
("{ret.ctype} ")
919 sig
.append
(self.c_name
)
920 sig
.append
("({recv.ctype} {selfvar}")
921 comment
.append
("(self: {recv}")
922 arguments
.add
(selfvar
)
923 for i
in [0..mmethoddef
.msignature
.arity
[ do
924 var mtype
= mmethoddef
.msignature
.mparameters
[i
].mtype
925 if i
== mmethoddef
.msignature
.vararg_rank
then
926 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
928 mtype
= v
.resolve_for
(mtype
, selfvar
)
929 comment
.append
(", {mtype}")
930 sig
.append
(", {mtype.ctype} p{i}")
931 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
932 arguments
.add
(argvar
)
937 comment
.append
(": {ret}")
939 compiler
.header
.add_decl
("{sig};")
941 v
.add_decl
("/* method {self} for {comment} */")
942 v
.add_decl
("{sig} \{")
943 #v.add("printf(\"method {self} for {comment}\\n\");")
945 frame
.returnvar
= v
.new_var
(ret
)
947 frame
.returnlabel
= v
.get_name
("RET_LABEL")
949 mmethoddef
.compile_inside_to_c
(v
, arguments
)
951 v
.add
("{frame.returnlabel.as(not null)}:;")
953 v
.add
("return {frame.returnvar.as(not null)};")
956 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})"
959 redef fun call
(v
: VISITOR, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
961 var ret
= self.mmethoddef
.msignature
.return_mtype
962 if self.mmethoddef
.mproperty
.is_new
then
966 ret
= v
.resolve_for
(ret
, arguments
.first
)
968 if self.mmethoddef
.can_inline
(v
) then
969 var frame
= new Frame(v
, self.mmethoddef
, self.recv
, arguments
)
970 frame
.returnlabel
= v
.get_name
("RET_LABEL")
972 frame
.returnvar
= v
.new_var
(ret
)
974 var old_frame
= v
.frame
976 v
.add
("\{ /* Inline {self} ({arguments.join(",")}) */")
977 self.mmethoddef
.compile_inside_to_c
(v
, arguments
)
978 v
.add
("{frame.returnlabel.as(not null)}:(void)0;")
981 return frame
.returnvar
983 v
.adapt_signature
(self.mmethoddef
, arguments
)
984 v
.compiler
.todo
(self)
986 v
.add
("{self.c_name}({arguments.join(",")});")
989 var res
= v
.new_var
(ret
)
990 v
.add
("{res} = {self.c_name}({arguments.join(",")});")