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
("*** GENERATING C ***", 1)
38 var compiler
= new GlobalCompiler(mainmodule
, self, runtime_type_analysis
)
39 compiler
.compile_header
41 for t
in runtime_type_analysis
.live_types
do
42 compiler
.declare_runtimeclass
(t
)
45 compiler
.compile_class_names
47 # Init instance code (allocate and init-arguments)
48 for t
in runtime_type_analysis
.live_types
do
49 if t
.ctype
== "val*" then
50 compiler
.generate_init_instance
(t
)
51 compiler
.generate_check_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
)
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 redef fun generate_check_init_instance
(mtype
)
228 if self.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
230 var v
= self.new_visitor
231 var res
= new RuntimeVariable("self", mtype
, mtype
)
232 self.header
.add_decl
("void CHECK_NEW_{mtype.c_name}({mtype.ctype});")
233 v
.add_decl
("/* allocate {mtype} */")
234 v
.add_decl
("void CHECK_NEW_{mtype.c_name}({mtype.ctype} {res}) \{")
235 self.generate_check_attr
(v
, res
, mtype
)
239 fun generate_box_instance
(mtype
: MClassType)
241 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
242 assert mtype
.ctype
!= "val*"
243 var v
= self.new_visitor
245 self.header
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype});")
246 v
.add_decl
("/* allocate {mtype} */")
247 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
248 v
.add
("struct {mtype.c_name}*res = nit_alloc(sizeof(struct {mtype.c_name}));")
249 v
.add
("res->classid = {self.classid(mtype)};")
250 v
.add
("res->value = value;")
251 v
.add
("return (val*)res;")
256 redef fun new_visitor
do return new GlobalCompilerVisitor(self)
258 private var collect_types_cache
: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
261 # A visitor on the AST of property definition that generate the C code.
262 # Because of inlining, a visitor can visit more than one property.
263 class GlobalCompilerVisitor
264 super AbstractCompilerVisitor
266 redef type COMPILER: GlobalCompiler
268 redef fun autobox
(value
, mtype
)
270 if value
.mtype
== mtype
then
272 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
274 else if value
.mtype
.ctype
== "val*" then
275 return self.new_expr
("((struct {mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
276 else if mtype
.ctype
== "val*" then
277 var valtype
= value
.mtype
.as(MClassType)
278 var res
= self.new_var
(mtype
)
279 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
280 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
281 self.add
("printf(\"Dead code executed
!\\n\
"); exit(1);")
284 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
287 # Bad things will appen!
288 var res
= self.new_var
(mtype
)
289 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
290 self.add
("printf(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); exit(1);")
295 # The runtime types that are acceptable for a given receiver.
296 fun collect_types
(recv
: RuntimeVariable): Array[MClassType]
298 var mtype
= recv
.mcasttype
299 if recv
.is_exact
then
300 assert mtype
isa MClassType
301 assert self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
)
305 var cache
= self.compiler
.collect_types_cache
306 if cache
.has_key
(mtype
) then
309 var types
= new Array[MClassType]
310 var mainmodule
= self.compiler
.mainmodule
311 for t
in self.compiler
.runtime_type_analysis
.live_types
do
312 if not t
.is_subtype
(mainmodule
, null, mtype
) then continue
319 redef fun native_array_def
(pname
, ret_type
, arguments
)
321 var elttype
= arguments
.first
.mtype
322 var recv
= "((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->values"
323 if pname
== "[]" then
324 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
326 else if pname
== "[]=" then
327 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
329 else if pname
== "copy_to" then
330 var recv1
= "((struct {arguments[1].mcasttype.c_name}*){arguments[1]})->values"
331 self.add
("memcpy({recv1},{recv},{arguments[2]}*sizeof({elttype.ctype}));")
336 redef fun calloc_array
(ret_type
, arguments
)
338 self.ret
(self.new_expr
("NEW_{ret_type.c_name}({arguments[1]})", ret_type
))
341 redef fun send
(m
, args
)
343 var types
= self.collect_types
(args
.first
)
345 var res
: nullable RuntimeVariable
346 var ret
= m
.intro
.msignature
.return_mtype
348 ret
= args
.first
.mtype
349 res
= self.new_var
(ret
)
350 else if ret
== null then
353 ret
= self.resolve_for
(ret
, args
.first
)
354 res
= self.new_var
(ret
)
357 self.add
("/* send {m} on {args.first.inspect} */")
358 if args
.first
.mtype
.ctype
!= "val*" then
359 var mclasstype
= args
.first
.mtype
.as(MClassType)
360 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
361 self.add
("/* skip, no method {m} */")
364 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, mclasstype
)
365 var res2
= self.call
(propdef
, mclasstype
, args
)
366 if res
!= null then self.assign
(res
, res2
.as(not null))
369 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
or m
.name
== "==" or m
.name
== "!="
370 if args
.first
.mcasttype
isa MNullableType or args
.first
.mcasttype
isa MNullType and consider_null
then
371 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
372 self.add
("if ({args.first} == NULL) \{ /* Special null case */")
373 if m
.name
== "==" then
375 if args
[1].mcasttype
isa MNullableType then
376 self.add
("{res} = ({args[1]} == NULL);")
377 else if args
[1].mcasttype
isa MNullType then
378 self.add
("{res} = 1; /* is null */")
380 self.add
("{res} = 0; /* {args[1].inspect} cannot be null */")
382 else if m
.name
== "!=" then
384 if args
[1].mcasttype
isa MNullableType then
385 self.add
("{res} = ({args[1]} != NULL);")
386 else if args
[1].mcasttype
isa MNullType then
387 self.add
("{res} = 0; /* is null */")
389 self.add
("{res} = 1; /* {args[1].inspect} cannot be null */")
392 self.add_abort
("Reciever is null")
396 if types
.is_empty
then
398 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
399 self.bugtype
(args
.first
)
404 self.add
("switch({args.first}->classid) \{")
405 var last
= types
.last
406 var defaultpropdef
: nullable MMethodDef = null
408 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, t
)
409 if propdef
.mclassdef
.mclass
.name
== "Object" and t
.ctype
== "val*" then
410 defaultpropdef
= propdef
413 if not self.compiler
.hardening
and t
== last
and defaultpropdef
== null then
414 self.add
("default: /* test {t} */")
416 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
418 var res2
= self.call
(propdef
, t
, args
)
419 if res
!= null then self.assign
(res
, res2
.as(not null))
422 if defaultpropdef
!= null then
423 self.add
("default: /* default is Object */")
424 var res2
= self.call
(defaultpropdef
, defaultpropdef
.mclassdef
.bound_mtype
, args
)
425 if res
!= null then self.assign
(res
, res2
.as(not null))
426 else if self.compiler
.hardening
then
427 self.add
("default: /* bug */")
428 self.bugtype
(args
.first
)
434 fun check_valid_reciever
(recvtype
: MClassType)
436 if self.compiler
.runtime_type_analysis
.live_types
.has
(recvtype
) or recvtype
.mclass
.name
== "Object" then return
437 print
"{recvtype} is not a live type"
441 redef fun call
(m
, recvtype
, args
)
443 check_valid_reciever
(recvtype
)
444 #debug("call {m} on {recvtype} on {args.first}:{args.first.mtype}")
445 if m
.mclassdef
.mclass
.name
== "Object" and recvtype
.ctype
== "val*" then
446 recvtype
= m
.mclassdef
.bound_mtype
448 var recv
= self.autobox
(args
.first
, recvtype
)
449 recv
= self.autoadapt
(recv
, recvtype
)
452 self.varargize
(m
, m
.msignature
.as(not null), args
)
453 if args
.length
!= m
.msignature
.arity
+ 1 then # because of self
454 add
("printf(\"NOT YET IMPLEMENTED: Invalid arity
for {m}. {args.length} arguments given
.\\n\
"); exit(1);")
455 debug
("NOT YET IMPLEMENTED: Invalid arity for {m}. {args.length} arguments given.")
460 var rm
= new CustomizedRuntimeFunction(m
, recvtype
)
461 return rm
.call
(self, args
)
464 redef fun supercall
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
466 var types
= self.collect_types
(args
.first
)
468 var res
: nullable RuntimeVariable
469 var ret
= m
.mproperty
.intro
.msignature
.return_mtype
473 ret
= self.resolve_for
(ret
, args
.first
)
474 res
= self.new_var
(ret
)
477 self.add
("/* super {m} on {args.first.inspect} */")
478 if args
.first
.mtype
.ctype
!= "val*" then
479 var mclasstype
= args
.first
.mtype
.as(MClassType)
480 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
481 self.add
("/* skip, no method {m} */")
484 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, mclasstype
)
485 var res2
= self.call
(propdef
, mclasstype
, args
)
486 if res
!= null then self.assign
(res
, res2
.as(not null))
490 if types
.is_empty
then
492 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
493 self.bugtype
(args
.first
)
498 self.add
("switch({args.first}->classid) \{")
499 var last
= types
.last
501 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, t
)
502 if not self.compiler
.hardening
and t
== last
then
503 self.add
("default: /* test {t} */")
505 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
507 var res2
= self.call
(propdef
, t
, args
)
508 if res
!= null then self.assign
(res
, res2
.as(not null))
511 if self.compiler
.hardening
then
512 self.add
("default: /* bug */")
513 self.bugtype
(args
.first
)
519 redef fun adapt_signature
(m
, args
)
521 var recv
= args
.first
522 for i
in [0..m
.msignature
.arity
[ do
523 var t
= m
.msignature
.mparameters
[i
].mtype
524 if i
== m
.msignature
.vararg_rank
then
527 t
= self.resolve_for
(t
, recv
)
528 args
[i
+1] = self.autobox
(args
[i
+1], t
)
532 # FIXME: this is currently buggy since recv is not exact
533 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
535 elttype
= self.resolve_for
(elttype
, recv
)
536 return self.array_instance
(varargs
, elttype
)
539 fun bugtype
(recv
: RuntimeVariable)
541 if recv
.mtype
.ctype
!= "val*" then return
542 self.add
("fprintf(stderr, \"BTD BUG: Dynamic type is %s
, static
type is %s\\n\
", class_names[{recv}->classid], \"{recv.mcasttype}\
");")
546 redef fun isset_attribute
(a
, recv
)
548 check_recv_notnull
(recv
)
550 var types
= self.collect_types
(recv
)
551 var res
= self.new_var
(bool_type
)
553 if types
.is_empty
then
554 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
558 self.add
("/* isset {a} on {recv.inspect} */")
559 self.add
("switch({recv}->classid) \{")
560 var last
= types
.last
562 if not self.compiler
.hardening
and t
== last
then
563 self.add
("default: /*{self.compiler.classid(t)}*/")
565 self.add
("case {self.compiler.classid(t)}:")
567 var recv2
= self.autoadapt
(recv
, t
)
568 var ta
= a
.intro
.static_mtype
.as(not null)
569 ta
= self.resolve_for
(ta
, recv2
)
570 var attr
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
571 if not ta
isa MNullableType then
572 if ta
.ctype
== "val*" then
573 self.add
("{res} = ({attr} != NULL);")
575 self.add
("{res} = 1; /*NOTYET isset on primitive attributes*/")
580 if self.compiler
.hardening
then
581 self.add
("default: /* Bug */")
589 redef fun read_attribute
(a
, recv
)
591 check_recv_notnull
(recv
)
593 var types
= self.collect_types
(recv
)
595 var ret
= a
.intro
.static_mtype
.as(not null)
596 ret
= self.resolve_for
(ret
, recv
)
597 var res
= self.new_var
(ret
)
599 if types
.is_empty
then
600 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
604 self.add
("/* read {a} on {recv.inspect} */")
605 self.add
("switch({recv}->classid) \{")
606 var last
= types
.last
608 if not self.compiler
.hardening
and t
== last
then
609 self.add
("default: /*{self.compiler.classid(t)}*/")
611 self.add
("case {self.compiler.classid(t)}:")
613 var recv2
= self.autoadapt
(recv
, t
)
614 var ta
= a
.intro
.static_mtype
.as(not null)
615 ta
= self.resolve_for
(ta
, recv2
)
616 var res2
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
617 if not ta
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
then
618 if ta
.ctype
== "val*" then
619 self.add
("if ({res2} == NULL) \{")
620 self.add_abort
("Uninitialized attribute {a.name}")
623 self.add
("/*NOTYET isset on primitive attributes*/")
626 self.assign
(res
, res2
)
629 if self.compiler
.hardening
then
630 self.add
("default: /* Bug */")
638 redef fun write_attribute
(a
, recv
, value
)
640 check_recv_notnull
(recv
)
642 var types
= self.collect_types
(recv
)
644 if types
.is_empty
then
645 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
649 self.add
("/* write {a} on {recv.inspect} */")
650 self.add
("switch({recv}->classid) \{")
651 var last
= types
.last
653 if not self.compiler
.hardening
and t
== last
then
654 self.add
("default: /*{self.compiler.classid(t)}*/")
656 self.add
("case {self.compiler.classid(t)}:")
658 var recv2
= self.autoadapt
(recv
, t
)
659 var ta
= a
.intro
.static_mtype
.as(not null)
660 ta
= self.resolve_for
(ta
, recv2
)
661 self.add
("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
664 if self.compiler
.hardening
then
665 self.add
("default: /* Bug*/")
671 redef fun init_instance
(mtype
)
673 mtype
= self.anchor
(mtype
).as(MClassType)
674 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
675 debug
"problem: {mtype} was detected dead"
677 var res
= self.new_expr
("NEW_{mtype.c_name}()", mtype
)
682 redef fun type_test
(value
, mtype
, tag
)
684 mtype
= self.anchor
(mtype
)
685 var mclasstype
= mtype
686 if mtype
isa MNullableType then mclasstype
= mtype
.mtype
687 assert mclasstype
isa MClassType
688 if not self.compiler
.runtime_type_analysis
.live_cast_types
.has
(mclasstype
) then
689 debug
"problem: {mtype} was detected cast-dead"
693 var types
= self.collect_types
(value
)
694 var res
= self.new_var
(bool_type
)
696 self.add
("/* isa {mtype} on {value.inspect} */")
697 if value
.mtype
.ctype
!= "val*" then
698 if value
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
699 self.add
("{res} = 1;")
701 self.add
("{res} = 0;")
705 if value
.mcasttype
isa MNullableType or value
.mcasttype
isa MNullType then
706 self.add
("if ({value} == NULL) \{")
707 if mtype
isa MNullableType then
708 self.add
("{res} = 1; /* isa {mtype} */")
710 self.add
("{res} = 0; /* not isa {mtype} */")
714 self.add
("switch({value}->classid) \{")
716 if t
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
717 self.add
("case {self.compiler.classid(t)}: /* {t} */")
720 self.add
("{res} = 1;")
723 self.add
("{res} = 0;")
729 redef fun is_same_type_test
(value1
, value2
)
731 var res
= self.new_var
(bool_type
)
732 if value2
.mtype
.ctype
== "val*" then
733 if value1
.mtype
.ctype
== "val*" then
734 self.add
"{res} = {value1}->classid == {value2}->classid;"
736 self.add
"{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
739 if value1
.mtype
.ctype
== "val*" then
740 self.add
"{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
741 else if value1
.mcasttype
== value2
.mcasttype
then
742 self.add
"{res} = 1;"
744 self.add
"{res} = 0;"
750 redef fun class_name_string
(value
)
752 var res
= self.get_name
("var_class_name")
753 self.add_decl
("const char* {res};")
754 if value
.mtype
.ctype
== "val*" then
755 self.add
"{res} = class_names[{value}->classid];"
757 self.add
"{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
762 redef fun equal_test
(value1
, value2
)
764 var res
= self.new_var
(bool_type
)
765 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
770 if value1
.mtype
.ctype
!= "val*" then
771 if value2
.mtype
== value1
.mtype
then
772 self.add
("{res} = {value1} == {value2};")
773 else if value2
.mtype
.ctype
!= "val*" then
774 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
776 var mtype1
= value1
.mtype
.as(MClassType)
777 self.add
("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
778 self.add
("if ({res}) \{")
779 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
783 var s
= new Array[String]
784 for t
in self.compiler
.live_primitive_types
do
785 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value1
.mcasttype
) then continue
786 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value2
.mcasttype
) then continue
787 s
.add
"({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
790 self.add
("{res} = {value1} == {value2};")
792 self.add
("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
798 redef fun check_init_instance
(recv
, mtype
)
800 if self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
802 mtype
= self.anchor
(mtype
).as(MClassType)
803 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
804 debug
"problem: {mtype} was detected dead"
807 self.add
("CHECK_NEW_{mtype.c_name}({recv});")
810 redef fun array_instance
(array
, elttype
)
812 elttype
= self.anchor
(elttype
)
813 var arraytype
= self.get_class
("Array").get_mtype
([elttype
])
814 var res
= self.init_instance
(arraytype
)
815 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
816 var nat
= self.new_var
(self.get_class
("NativeArray").get_mtype
([elttype
]))
818 self.add
("{nat} = NEW_{nat.mtype.c_name}({array.length});")
819 for i
in [0..array
.length
[ do
820 var r
= self.autobox
(array
[i
], elttype
)
821 self.add
("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
823 var length
= self.int_instance
(array
.length
)
824 self.send
(self.get_property
("with_native", arraytype
), [res
, nat
, length
])
825 self.check_init_instance
(res
, arraytype
)
831 # A runtime function customized on a specific monomrph receiver type
832 private class CustomizedRuntimeFunction
833 super AbstractRuntimeFunction
835 redef type COMPILER: GlobalCompiler
836 redef type VISITOR: GlobalCompilerVisitor
838 # The considered reciever
839 # (usually is a live type but no strong guarantee)
842 init(mmethoddef
: MMethodDef, recv
: MClassType)
848 redef fun build_c_name
850 var res
= self.c_name_cache
851 if res
!= null then return res
852 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
853 res
= self.mmethoddef
.c_name
855 res
= "{mmethoddef.c_name}__{recv.c_name}"
857 self.c_name_cache
= res
861 # used in the compiler worklist
864 if not o
isa CustomizedRuntimeFunction then return false
865 if self.mmethoddef
!= o
.mmethoddef
then return false
866 if self.recv
!= o
.recv
then return false
870 # used in the compiler work-list
871 redef fun hash
do return self.mmethoddef
.hash
+ self.recv
.hash
875 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
876 return self.mmethoddef
.to_s
878 return "{self.mmethoddef}@{self.recv}"
882 # compile the code customized for the reciever
883 redef fun compile_to_c
(compiler
)
886 var mmethoddef
= self.mmethoddef
887 if not recv
.is_subtype
(compiler
.mainmodule
, null, mmethoddef
.mclassdef
.bound_mtype
) then
888 print
("problem: why do we compile {self} for {recv}?")
892 var v
= compiler
.new_visitor
893 var selfvar
= new RuntimeVariable("self", recv
, recv
)
894 if compiler
.runtime_type_analysis
.live_types
.has
(recv
) then
895 selfvar
.is_exact
= true
897 var arguments
= new Array[RuntimeVariable]
898 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
902 var comment
= new Buffer
903 var ret
= mmethoddef
.msignature
.return_mtype
905 ret
= v
.resolve_for
(ret
, selfvar
)
906 sig
.append
("{ret.ctype} ")
907 else if mmethoddef
.mproperty
.is_new
then
909 sig
.append
("{ret.ctype} ")
913 sig
.append
(self.c_name
)
914 sig
.append
("({recv.ctype} {selfvar}")
915 comment
.append
("(self: {recv}")
916 arguments
.add
(selfvar
)
917 for i
in [0..mmethoddef
.msignature
.arity
[ do
918 var mtype
= mmethoddef
.msignature
.mparameters
[i
].mtype
919 if i
== mmethoddef
.msignature
.vararg_rank
then
920 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
922 mtype
= v
.resolve_for
(mtype
, selfvar
)
923 comment
.append
(", {mtype}")
924 sig
.append
(", {mtype.ctype} p{i}")
925 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
926 arguments
.add
(argvar
)
931 comment
.append
(": {ret}")
933 compiler
.header
.add_decl
("{sig};")
935 v
.add_decl
("/* method {self} for {comment} */")
936 v
.add_decl
("{sig} \{")
937 #v.add("printf(\"method {self} for {comment}\\n\");")
939 frame
.returnvar
= v
.new_var
(ret
)
941 frame
.returnlabel
= v
.get_name
("RET_LABEL")
943 mmethoddef
.compile_inside_to_c
(v
, arguments
)
945 v
.add
("{frame.returnlabel.as(not null)}:;")
947 v
.add
("return {frame.returnvar.as(not null)};")
952 redef fun call
(v
: VISITOR, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
954 var ret
= self.mmethoddef
.msignature
.return_mtype
955 if self.mmethoddef
.mproperty
.is_new
then
959 ret
= v
.resolve_for
(ret
, arguments
.first
)
961 if self.mmethoddef
.can_inline
(v
) then
962 var frame
= new Frame(v
, self.mmethoddef
, self.recv
, arguments
)
963 frame
.returnlabel
= v
.get_name
("RET_LABEL")
965 frame
.returnvar
= v
.new_var
(ret
)
967 var old_frame
= v
.frame
969 v
.add
("\{ /* Inline {self} ({arguments.join(",")}) */")
970 self.mmethoddef
.compile_inside_to_c
(v
, arguments
)
971 v
.add
("{frame.returnlabel.as(not null)}:(void)0;")
974 return frame
.returnvar
976 v
.adapt_signature
(self.mmethoddef
, arguments
)
977 v
.compiler
.todo
(self)
979 v
.add
("{self.c_name}({arguments.join(",")});")
982 var res
= v
.new_var
(ret
)
983 v
.add
("{res} = {self.c_name}({arguments.join(",")});")