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)
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 propdefs
= m
.lookup_definitions
(self.compiler
.mainmodule
, mclasstype
)
363 if propdefs
.length
== 0 then
364 self.add
("/* skip, no method {m} */")
367 assert propdefs
.length
== 1
368 var propdef
= propdefs
.first
369 var res2
= self.call
(propdef
, mclasstype
, args
)
370 if res
!= null then self.assign
(res
, res2
.as(not null))
373 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
or m
.name
== "==" or m
.name
== "!="
374 if args
.first
.mcasttype
isa MNullableType or args
.first
.mcasttype
isa MNullType and consider_null
then
375 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
376 self.add
("if ({args.first} == NULL) \{ /* Special null case */")
377 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} = 1; /* is null */")
384 self.add
("{res} = 0; /* {args[1].inspect} cannot be null */")
386 else if m
.name
== "!=" then
388 if args
[1].mcasttype
isa MNullableType then
389 self.add
("{res} = ({args[1]} != NULL);")
390 else if args
[1].mcasttype
isa MNullType then
391 self.add
("{res} = 0; /* is null */")
393 self.add
("{res} = 1; /* {args[1].inspect} cannot be null */")
396 self.add_abort
("Reciever is null")
400 if types
.is_empty
then
402 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
403 self.bugtype
(args
.first
)
408 self.add
("switch({args.first}->classid) \{")
409 var last
= types
.last
410 var defaultpropdef
: nullable MMethodDef = null
412 var propdefs
= m
.lookup_definitions
(self.compiler
.mainmodule
, t
)
413 if propdefs
.length
== 0 then
414 self.add
("/* skip {t}, no method {m} */")
417 if propdefs
.length
> 1 then
418 self.debug
("NOT YET IMPLEMENTED conflict for {t}.{m}: {propdefs.join(" ")}. choose the first")
420 var propdef
= propdefs
.first
421 if propdef
.mclassdef
.mclass
.name
== "Object" and t
.ctype
== "val*" then
422 defaultpropdef
= propdef
425 if not self.compiler
.hardening
and t
== last
and defaultpropdef
== null then
426 self.add
("default: /* test {t} */")
428 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
430 var res2
= self.call
(propdef
, t
, args
)
431 if res
!= null then self.assign
(res
, res2
.as(not null))
434 if defaultpropdef
!= null then
435 self.add
("default: /* default is Object */")
436 var res2
= self.call
(defaultpropdef
, defaultpropdef
.mclassdef
.bound_mtype
, args
)
437 if res
!= null then self.assign
(res
, res2
.as(not null))
438 else if self.compiler
.hardening
then
439 self.add
("default: /* bug */")
440 self.bugtype
(args
.first
)
446 fun check_valid_reciever
(recvtype
: MClassType)
448 if self.compiler
.runtime_type_analysis
.live_types
.has
(recvtype
) or recvtype
.mclass
.name
== "Object" then return
449 print
"{recvtype} is not a live type"
453 redef fun call
(m
, recvtype
, args
)
455 check_valid_reciever
(recvtype
)
456 #debug("call {m} on {recvtype} on {args.first}:{args.first.mtype}")
457 if m
.mclassdef
.mclass
.name
== "Object" and recvtype
.ctype
== "val*" then
458 recvtype
= m
.mclassdef
.bound_mtype
460 var recv
= self.autobox
(args
.first
, recvtype
)
461 recv
= self.autoadapt
(recv
, recvtype
)
464 self.varargize
(m
, m
.msignature
.as(not null), args
)
465 if args
.length
!= m
.msignature
.arity
+ 1 then # because of self
466 add
("printf(\"NOT YET IMPLEMENTED: Invalid arity
for {m}. {args.length} arguments given
.\\n\
"); exit(1);")
467 debug
("NOT YET IMPLEMENTED: Invalid arity for {m}. {args.length} arguments given.")
472 var rm
= new CustomizedRuntimeFunction(m
, recvtype
)
473 return rm
.call
(self, args
)
476 redef fun adapt_signature
(m
, args
)
478 var recv
= args
.first
479 for i
in [0..m
.msignature
.arity
[ do
480 var t
= m
.msignature
.mparameters
[i
].mtype
481 if i
== m
.msignature
.vararg_rank
then
484 t
= self.resolve_for
(t
, recv
)
485 args
[i
+1] = self.autobox
(args
[i
+1], t
)
489 # FIXME: this is currently buggy since recv is not exact
490 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
492 elttype
= self.resolve_for
(elttype
, recv
)
493 return self.array_instance
(varargs
, elttype
)
496 fun bugtype
(recv
: RuntimeVariable)
498 if recv
.mtype
.ctype
!= "val*" then return
499 self.add
("fprintf(stderr, \"BTD BUG: Dynamic type is %s
, static
type is %s\\n\
", class_names[{recv}->classid], \"{recv.mcasttype}\
");")
503 redef fun isset_attribute
(a
, recv
)
505 check_recv_notnull
(recv
)
507 var types
= self.collect_types
(recv
)
508 var res
= self.new_var
(bool_type
)
510 if types
.is_empty
then
511 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
515 self.add
("/* isset {a} on {recv.inspect} */")
516 self.add
("switch({recv}->classid) \{")
517 var last
= types
.last
519 if not self.compiler
.hardening
and t
== last
then
520 self.add
("default: /*{self.compiler.classid(t)}*/")
522 self.add
("case {self.compiler.classid(t)}:")
524 var recv2
= self.autoadapt
(recv
, t
)
525 var ta
= a
.intro
.static_mtype
.as(not null)
526 ta
= self.resolve_for
(ta
, recv2
)
527 var attr
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
528 if not ta
isa MNullableType then
529 if ta
.ctype
== "val*" then
530 self.add
("{res} = ({attr} != NULL);")
532 self.add
("{res} = 1; /*NOTYET isset on primitive attributes*/")
537 if self.compiler
.hardening
then
538 self.add
("default: /* Bug */")
546 redef fun read_attribute
(a
, recv
)
548 check_recv_notnull
(recv
)
550 var types
= self.collect_types
(recv
)
552 var ret
= a
.intro
.static_mtype
.as(not null)
553 ret
= self.resolve_for
(ret
, recv
)
554 var res
= self.new_var
(ret
)
556 if types
.is_empty
then
557 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
561 self.add
("/* read {a} on {recv.inspect} */")
562 self.add
("switch({recv}->classid) \{")
563 var last
= types
.last
565 if not self.compiler
.hardening
and t
== last
then
566 self.add
("default: /*{self.compiler.classid(t)}*/")
568 self.add
("case {self.compiler.classid(t)}:")
570 var recv2
= self.autoadapt
(recv
, t
)
571 var ta
= a
.intro
.static_mtype
.as(not null)
572 ta
= self.resolve_for
(ta
, recv2
)
573 var res2
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
574 if not ta
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
then
575 if ta
.ctype
== "val*" then
576 self.add
("if ({res2} == NULL) \{")
577 self.add_abort
("Uninitialized attribute {a.name}")
580 self.add
("/*NOTYET isset on primitive attributes*/")
583 self.assign
(res
, res2
)
586 if self.compiler
.hardening
then
587 self.add
("default: /* Bug */")
595 redef fun write_attribute
(a
, recv
, value
)
597 check_recv_notnull
(recv
)
599 var types
= self.collect_types
(recv
)
601 if types
.is_empty
then
602 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
606 self.add
("/* write {a} on {recv.inspect} */")
607 self.add
("switch({recv}->classid) \{")
608 var last
= types
.last
610 if not self.compiler
.hardening
and t
== last
then
611 self.add
("default: /*{self.compiler.classid(t)}*/")
613 self.add
("case {self.compiler.classid(t)}:")
615 var recv2
= self.autoadapt
(recv
, t
)
616 var ta
= a
.intro
.static_mtype
.as(not null)
617 ta
= self.resolve_for
(ta
, recv2
)
618 self.add
("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
621 if self.compiler
.hardening
then
622 self.add
("default: /* Bug*/")
628 redef fun init_instance
(mtype
)
630 mtype
= self.anchor
(mtype
).as(MClassType)
631 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
632 debug
"problem: {mtype} was detected dead"
634 var res
= self.new_expr
("NEW_{mtype.c_name}()", mtype
)
639 redef fun type_test
(value
, mtype
, tag
)
641 mtype
= self.anchor
(mtype
)
642 var mclasstype
= mtype
643 if mtype
isa MNullableType then mclasstype
= mtype
.mtype
644 assert mclasstype
isa MClassType
645 if not self.compiler
.runtime_type_analysis
.live_cast_types
.has
(mclasstype
) then
646 debug
"problem: {mtype} was detected cast-dead"
650 var types
= self.collect_types
(value
)
651 var res
= self.new_var
(bool_type
)
653 self.add
("/* isa {mtype} on {value.inspect} */")
654 if value
.mtype
.ctype
!= "val*" then
655 if value
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
656 self.add
("{res} = 1;")
658 self.add
("{res} = 0;")
662 if value
.mcasttype
isa MNullableType or value
.mcasttype
isa MNullType then
663 self.add
("if ({value} == NULL) \{")
664 if mtype
isa MNullableType then
665 self.add
("{res} = 1; /* isa {mtype} */")
667 self.add
("{res} = 0; /* not isa {mtype} */")
671 self.add
("switch({value}->classid) \{")
673 if t
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
674 self.add
("case {self.compiler.classid(t)}: /* {t} */")
677 self.add
("{res} = 1;")
680 self.add
("{res} = 0;")
686 redef fun is_same_type_test
(value1
, value2
)
688 var res
= self.new_var
(bool_type
)
689 if value2
.mtype
.ctype
== "val*" then
690 if value1
.mtype
.ctype
== "val*" then
691 self.add
"{res} = {value1}->classid == {value2}->classid;"
693 self.add
"{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
696 if value1
.mtype
.ctype
== "val*" then
697 self.add
"{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
698 else if value1
.mcasttype
== value2
.mcasttype
then
699 self.add
"{res} = 1;"
701 self.add
"{res} = 0;"
707 redef fun class_name_string
(value
)
709 var res
= self.get_name
("var_class_name")
710 self.add_decl
("const char* {res};")
711 if value
.mtype
.ctype
== "val*" then
712 self.add
"{res} = class_names[{value}->classid];"
714 self.add
"{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
719 redef fun equal_test
(value1
, value2
)
721 var res
= self.new_var
(bool_type
)
722 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
727 if value1
.mtype
.ctype
!= "val*" then
728 if value2
.mtype
== value1
.mtype
then
729 self.add
("{res} = {value1} == {value2};")
730 else if value2
.mtype
.ctype
!= "val*" then
731 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
733 var mtype1
= value1
.mtype
.as(MClassType)
734 self.add
("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
735 self.add
("if ({res}) \{")
736 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
740 var s
= new Array[String]
741 for t
in self.compiler
.live_primitive_types
do
742 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value1
.mcasttype
) then continue
743 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value2
.mcasttype
) then continue
744 s
.add
"({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
747 self.add
("{res} = {value1} == {value2};")
749 self.add
("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
755 redef fun check_init_instance
(recv
, mtype
)
757 if self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
759 mtype
= self.anchor
(mtype
).as(MClassType)
760 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
761 debug
"problem: {mtype} was detected dead"
764 self.add
("CHECK_NEW_{mtype.c_name}({recv});")
767 redef fun array_instance
(array
, elttype
)
769 elttype
= self.anchor
(elttype
)
770 var arraytype
= self.get_class
("Array").get_mtype
([elttype
])
771 var res
= self.init_instance
(arraytype
)
772 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
773 var nat
= self.new_var
(self.get_class
("NativeArray").get_mtype
([elttype
]))
775 self.add
("{nat} = NEW_{nat.mtype.c_name}({array.length});")
776 for i
in [0..array
.length
[ do
777 var r
= self.autobox
(array
[i
], elttype
)
778 self.add
("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
780 var length
= self.int_instance
(array
.length
)
781 self.send
(self.get_property
("with_native", arraytype
), [res
, nat
, length
])
782 self.check_init_instance
(res
, arraytype
)
788 # A runtime function customized on a specific monomrph receiver type
789 private class CustomizedRuntimeFunction
790 super AbstractRuntimeFunction
792 redef type COMPILER: GlobalCompiler
793 redef type VISITOR: GlobalCompilerVisitor
795 # The considered reciever
796 # (usually is a live type but no strong guarantee)
799 init(mmethoddef
: MMethodDef, recv
: MClassType)
805 redef fun build_c_name
807 var res
= self.c_name_cache
808 if res
!= null then return res
809 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
810 res
= self.mmethoddef
.c_name
812 res
= "{mmethoddef.c_name}__{recv.c_name}"
814 self.c_name_cache
= res
818 # used in the compiler worklist
821 if not o
isa CustomizedRuntimeFunction then return false
822 if self.mmethoddef
!= o
.mmethoddef
then return false
823 if self.recv
!= o
.recv
then return false
827 # used in the compiler work-list
828 redef fun hash
do return self.mmethoddef
.hash
+ self.recv
.hash
832 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
833 return self.mmethoddef
.to_s
835 return "{self.mmethoddef}@{self.recv}"
839 # compile the code customized for the reciever
840 redef fun compile_to_c
(compiler
)
843 var mmethoddef
= self.mmethoddef
844 if not recv
.is_subtype
(compiler
.mainmodule
, null, mmethoddef
.mclassdef
.bound_mtype
) then
845 print
("problem: why do we compile {self} for {recv}?")
849 var v
= compiler
.new_visitor
850 var selfvar
= new RuntimeVariable("self", recv
, recv
)
851 if compiler
.runtime_type_analysis
.live_types
.has
(recv
) then
852 selfvar
.is_exact
= true
854 var arguments
= new Array[RuntimeVariable]
855 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
859 var comment
= new Buffer
860 var ret
= mmethoddef
.msignature
.return_mtype
862 ret
= v
.resolve_for
(ret
, selfvar
)
863 sig
.append
("{ret.ctype} ")
864 else if mmethoddef
.mproperty
.is_new
then
866 sig
.append
("{ret.ctype} ")
870 sig
.append
(self.c_name
)
871 sig
.append
("({recv.ctype} {selfvar}")
872 comment
.append
("(self: {recv}")
873 arguments
.add
(selfvar
)
874 for i
in [0..mmethoddef
.msignature
.arity
[ do
875 var mtype
= mmethoddef
.msignature
.mparameters
[i
].mtype
876 if i
== mmethoddef
.msignature
.vararg_rank
then
877 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
879 mtype
= v
.resolve_for
(mtype
, selfvar
)
880 comment
.append
(", {mtype}")
881 sig
.append
(", {mtype.ctype} p{i}")
882 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
883 arguments
.add
(argvar
)
888 comment
.append
(": {ret}")
890 compiler
.header
.add_decl
("{sig};")
892 v
.add_decl
("/* method {self} for {comment} */")
893 v
.add_decl
("{sig} \{")
894 #v.add("printf(\"method {self} for {comment}\\n\");")
896 frame
.returnvar
= v
.new_var
(ret
)
898 frame
.returnlabel
= v
.get_name
("RET_LABEL")
900 mmethoddef
.compile_inside_to_c
(v
, arguments
)
902 v
.add
("{frame.returnlabel.as(not null)}:;")
904 v
.add
("return {frame.returnvar.as(not null)};")
909 redef fun call
(v
: VISITOR, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
911 var ret
= self.mmethoddef
.msignature
.return_mtype
912 if self.mmethoddef
.mproperty
.is_new
then
916 ret
= v
.resolve_for
(ret
, arguments
.first
)
918 if self.mmethoddef
.can_inline
(v
) then
919 var frame
= new Frame(v
, self.mmethoddef
, self.recv
, arguments
)
920 frame
.returnlabel
= v
.get_name
("RET_LABEL")
922 frame
.returnvar
= v
.new_var
(ret
)
924 var old_frame
= v
.frame
926 v
.add
("\{ /* Inline {self} ({arguments.join(",")}) */")
927 self.mmethoddef
.compile_inside_to_c
(v
, arguments
)
928 v
.add
("{frame.returnlabel.as(not null)}:(void)0;")
931 return frame
.returnvar
933 v
.adapt_signature
(self.mmethoddef
, arguments
)
934 v
.compiler
.todo
(self)
936 v
.add
("{self.c_name}({arguments.join(",")});")
939 var res
= v
.new_var
(ret
)
940 v
.add
("{res} = {self.c_name}({arguments.join(",")});")