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 ToolContext
31 var opt_global
= new OptionBool("Use global compilation", "--global")
33 var global_compiler_phase
= new GlobalCompilerPhase(self, null)
37 option_context
.add_option
(opt_global
)
41 class GlobalCompilerPhase
43 redef fun process_mainmodule
(mainmodule
, given_mmodules
) do
44 if not toolcontext
.opt_global
.value
then return
46 var modelbuilder
= toolcontext
.modelbuilder
47 var analysis
= modelbuilder
.do_rapid_type_analysis
(mainmodule
)
48 modelbuilder
.run_global_compiler
(mainmodule
, analysis
)
52 redef class ModelBuilder
53 # Entry point to performs a global compilation on the AST of a complete program.
54 # `mainmodule` is the main module of the program
55 # `runtime_type_analysis` is a already computer type analysis.
56 fun run_global_compiler
(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis)
59 self.toolcontext
.info
("*** GENERATING C ***", 1)
61 var compiler
= new GlobalCompiler(mainmodule
, self, runtime_type_analysis
)
62 compiler
.compile_header
64 for t
in runtime_type_analysis
.live_types
do
65 compiler
.declare_runtimeclass
(t
)
68 compiler
.compile_class_names
70 # Init instance code (allocate and init-arguments)
71 for t
in runtime_type_analysis
.live_types
do
72 if t
.ctype
== "val*" then
73 compiler
.generate_init_instance
(t
)
75 compiler
.generate_box_instance
(t
)
79 # The main function of the C
80 compiler
.compile_main_function
82 # Compile until all runtime_functions are visited
83 while not compiler
.todos
.is_empty
do
84 var m
= compiler
.todos
.shift
85 self.toolcontext
.info
("Compile {m} ({compiler.seen.length-compiler.todos.length}/{compiler.seen.length})", 3)
86 m
.compile_to_c
(compiler
)
88 self.toolcontext
.info
("Total methods to compile to C: {compiler.seen.length}", 2)
90 compiler
.display_stats
93 self.toolcontext
.info
("*** END GENERATING C: {time1-time0} ***", 2)
94 write_and_make
(compiler
)
98 # Compiler that use global compilation and perform hard optimisations like:
103 super AbstractCompiler
105 redef type VISITOR: GlobalCompilerVisitor
107 # The result of the RTA (used to know live types and methods)
108 var runtime_type_analysis
: RapidTypeAnalysis
110 init(mainmodule
: MModule, modelbuilder
: ModelBuilder, runtime_type_analysis
: RapidTypeAnalysis)
112 super(mainmodule
, modelbuilder
)
113 var file
= new_file
("{mainmodule.name}.nitgg")
114 self.header
= new CodeWriter(file
)
115 self.runtime_type_analysis
= runtime_type_analysis
116 self.live_primitive_types
= new Array[MClassType]
117 for t
in runtime_type_analysis
.live_types
do
118 if t
.ctype
!= "val*" then
119 self.live_primitive_types
.add
(t
)
124 # Compile class names (for the class_name and output_class_name methods)
125 protected fun compile_class_names
do
127 self.header
.add_decl
("extern const char const * class_names[];")
128 v
.add
("const char const * class_names[] = \{")
129 for t
in self.runtime_type_analysis
.live_types
do
130 v
.add
("\"{t}\
", /* {self.classid(t)} */")
135 # Return the C symbol associated to a live type runtime
136 # REQUIRE: self.runtime_type_analysis.live_types.has(mtype)
137 fun classid
(mtype
: MClassType): String
139 if self.classids
.has_key
(mtype
) then
140 return self.classids
[mtype
]
142 print
"No classid for {mtype}"
147 protected var classids
: HashMap[MClassType, String] = new HashMap[MClassType, String]
149 # Declaration of structures the live Nit types
150 # Each live type is generated as an independent C `struct` type.
151 # They only share a common first field `classid` used to implement the polymorphism.
152 # Usualy, all C variables that refers to a Nit object are typed on the abstract struct `val` that contains only the `classid` field.
153 redef fun compile_header_structs
do
154 self.header
.add_decl
("typedef struct \{int classid;\} val; /* general C type representing a Nit instance. */")
157 # Subset of runtime_type_analysis.live_types that contains only primitive types
158 # Used to implement the equal test
159 var live_primitive_types
: Array[MClassType]
161 # Add a new todo task
162 fun todo
(m
: AbstractRuntimeFunction)
164 if seen
.has
(m
) then return
169 # runtime_functions that need to be compiled
170 private var todos
: List[AbstractRuntimeFunction] = new List[AbstractRuntimeFunction]
172 # runtime_functions already seen (todo or done)
173 private var seen
: HashSet[AbstractRuntimeFunction] = new HashSet[AbstractRuntimeFunction]
175 # Declare C structures and identifiers for a runtime class
176 fun declare_runtimeclass
(mtype
: MClassType)
179 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
180 v
.add_decl
("/* runtime class {mtype} */")
181 var idnum
= classids
.length
182 var idname
= "ID_" + mtype
.c_name
183 self.classids
[mtype
] = idname
184 v
.add_decl
("#define {idname} {idnum} /* {mtype} */")
186 v
.add_decl
("struct {mtype.c_name} \{")
187 v
.add_decl
("int classid; /* must be {idname} */")
189 if mtype
.mclass
.name
== "NativeArray" then
190 # NativeArrays are just a instance header followed by an array of values
191 v
.add_decl
("int length;")
192 v
.add_decl
("{mtype.arguments.first.ctype} values[1];")
195 if mtype
.ctype
!= "val*" then
196 # Is the Nit type is native then the struct is a box with two fields:
197 # * the `classid` to be polymorph
198 # * the `value` that contains the native value.
199 v
.add_decl
("{mtype.ctype} value;")
202 # Collect all attributes and associate them a field in the structure.
203 # Note: we do not try to optimize the order and helps CC to optimize the client code.
204 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
205 for p
in cd
.intro_mproperties
do
206 if not p
isa MAttribute then continue
207 var t
= p
.intro
.static_mtype
.as(not null)
208 t
= t
.anchor_to
(self.mainmodule
, mtype
)
209 v
.add_decl
("{t.ctype} {p.intro.c_name}; /* {p}: {t} */")
215 # Generate the init-instance of a live type (allocate + init-instance)
216 fun generate_init_instance
(mtype
: MClassType)
218 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
219 assert mtype
.ctype
== "val*"
220 var v
= self.new_visitor
222 var is_native_array
= mtype
.mclass
.name
== "NativeArray"
225 if is_native_array
then
231 self.header
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig});")
232 v
.add_decl
("/* allocate {mtype} */")
233 v
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig}) \{")
234 var res
= v
.new_var
(mtype
)
236 if is_native_array
then
237 var mtype_elt
= mtype
.arguments
.first
238 v
.add
("{res} = nit_alloc(sizeof(struct {mtype.c_name}) + length*sizeof({mtype_elt.ctype}));")
239 v
.add
("((struct {mtype.c_name}*){res})->length = length;")
241 v
.add
("{res} = nit_alloc(sizeof(struct {mtype.c_name}));")
243 v
.add
("{res}->classid = {self.classid(mtype)};")
245 self.generate_init_attr
(v
, res
, mtype
)
246 v
.add
("return {res};")
250 fun generate_box_instance
(mtype
: MClassType)
252 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
253 assert mtype
.ctype
!= "val*"
254 var v
= self.new_visitor
256 self.header
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype});")
257 v
.add_decl
("/* allocate {mtype} */")
258 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
259 v
.add
("struct {mtype.c_name}*res = nit_alloc(sizeof(struct {mtype.c_name}));")
260 v
.add
("res->classid = {self.classid(mtype)};")
261 v
.add
("res->value = value;")
262 v
.add
("return (val*)res;")
266 redef fun new_visitor
do return new GlobalCompilerVisitor(self)
268 private var collect_types_cache
: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
270 redef fun compile_nitni_structs
272 self.header
.add_decl
("struct nitni_instance \{ val *value; \};")
276 # A visitor on the AST of property definition that generate the C code.
277 # Because of inlining, a visitor can visit more than one property.
278 class GlobalCompilerVisitor
279 super AbstractCompilerVisitor
281 redef type COMPILER: GlobalCompiler
283 redef fun autobox
(value
, mtype
)
285 if value
.mtype
== mtype
then
287 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
289 else if value
.mtype
.ctype
== "val*" then
290 return self.new_expr
("((struct {mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
291 else if mtype
.ctype
== "val*" then
292 var valtype
= value
.mtype
.as(MClassType)
293 var res
= self.new_var
(mtype
)
294 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
295 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
296 self.add
("PRINT_ERROR(\"Dead code executed
!\\n\
"); show_backtrace(1);")
299 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
301 else if value
.mtype
.ctype
== "void*" and mtype
.ctype
== "void*" then
304 # Bad things will appen!
305 var res
= self.new_var
(mtype
)
306 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
307 self.add
("PRINT_ERROR(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); show_backtrace(1);")
312 # The runtime types that are acceptable for a given receiver.
313 fun collect_types
(recv
: RuntimeVariable): Array[MClassType]
315 var mtype
= recv
.mcasttype
316 if recv
.is_exact
then
317 assert mtype
isa MClassType
318 assert self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
)
322 var cache
= self.compiler
.collect_types_cache
323 if cache
.has_key
(mtype
) then
326 var types
= new Array[MClassType]
327 var mainmodule
= self.compiler
.mainmodule
328 for t
in self.compiler
.runtime_type_analysis
.live_types
do
329 if not t
.is_subtype
(mainmodule
, null, mtype
) then continue
336 redef fun native_array_def
(pname
, ret_type
, arguments
)
338 var elttype
= arguments
.first
.mtype
339 var recv
= "((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->values"
340 if pname
== "[]" then
341 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
343 else if pname
== "[]=" then
344 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
346 else if pname
== "length" then
347 self.ret
(self.new_expr
("((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->length", ret_type
.as(not null)))
349 else if pname
== "copy_to" then
350 var recv1
= "((struct {arguments[1].mcasttype.c_name}*){arguments[1]})->values"
351 self.add
("memcpy({recv1},{recv},{arguments[2]}*sizeof({elttype.ctype}));")
356 redef fun calloc_array
(ret_type
, arguments
)
358 self.ret
(self.new_expr
("NEW_{ret_type.c_name}({arguments[1]})", ret_type
))
361 redef fun send
(m
, args
)
363 var types
= self.collect_types
(args
.first
)
365 var res
: nullable RuntimeVariable
366 var ret
= m
.intro
.msignature
.return_mtype
368 ret
= args
.first
.mtype
369 res
= self.new_var
(ret
)
370 else if ret
== null then
373 ret
= self.resolve_for
(ret
, args
.first
)
374 res
= self.new_var
(ret
)
377 self.add
("/* send {m} on {args.first.inspect} */")
378 if args
.first
.mtype
.ctype
!= "val*" then
379 var mclasstype
= args
.first
.mtype
.as(MClassType)
380 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
381 self.add
("/* skip, no method {m} */")
384 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, mclasstype
)
385 var res2
= self.call
(propdef
, mclasstype
, args
)
386 if res
!= null then self.assign
(res
, res2
.as(not null))
389 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
or m
.name
== "==" or m
.name
== "!="
390 if args
.first
.mcasttype
isa MNullableType or args
.first
.mcasttype
isa MNullType and consider_null
then
391 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
392 self.add
("if ({args.first} == NULL) \{ /* Special null case */")
393 if m
.name
== "==" then
395 if args
[1].mcasttype
isa MNullableType then
396 self.add
("{res} = ({args[1]} == NULL);")
397 else if args
[1].mcasttype
isa MNullType then
398 self.add
("{res} = 1; /* is null */")
400 self.add
("{res} = 0; /* {args[1].inspect} cannot be null */")
402 else if m
.name
== "!=" then
404 if args
[1].mcasttype
isa MNullableType then
405 self.add
("{res} = ({args[1]} != NULL);")
406 else if args
[1].mcasttype
isa MNullType then
407 self.add
("{res} = 0; /* is null */")
409 self.add
("{res} = 1; /* {args[1].inspect} cannot be null */")
412 self.add_abort
("Receiver is null")
416 if types
.is_empty
then
418 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
419 self.bugtype
(args
.first
)
424 self.add
("switch({args.first}->classid) \{")
425 var last
= types
.last
426 var defaultpropdef
: nullable MMethodDef = null
428 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, t
)
429 if propdef
.mclassdef
.mclass
.name
== "Object" and t
.ctype
== "val*" then
430 defaultpropdef
= propdef
433 if not self.compiler
.hardening
and t
== last
and defaultpropdef
== null then
434 self.add
("default: /* test {t} */")
436 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
438 var res2
= self.call
(propdef
, t
, args
)
439 if res
!= null then self.assign
(res
, res2
.as(not null))
442 if defaultpropdef
!= null then
443 self.add
("default: /* default is Object */")
444 var res2
= self.call
(defaultpropdef
, defaultpropdef
.mclassdef
.bound_mtype
, args
)
445 if res
!= null then self.assign
(res
, res2
.as(not null))
446 else if self.compiler
.hardening
then
447 self.add
("default: /* bug */")
448 self.bugtype
(args
.first
)
454 fun check_valid_reciever
(recvtype
: MClassType)
456 if self.compiler
.runtime_type_analysis
.live_types
.has
(recvtype
) or recvtype
.mclass
.name
== "Object" then return
457 print
"{recvtype} is not a live type"
461 # Subpart of old call function
463 # Checks if the type of the receiver is valid and corrects it if necessary
464 private fun get_recvtype
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): MClassType
466 check_valid_reciever
(recvtype
)
467 #debug("call {m} on {recvtype} on {args.first}:{args.first.mtype}")
468 if m
.mclassdef
.mclass
.name
== "Object" and recvtype
.ctype
== "val*" then
469 recvtype
= m
.mclassdef
.bound_mtype
474 # Subpart of old call function
475 # Gets the receiver boxed and casted if necessary
476 private fun get_recv
(recvtype
: MClassType, args
: Array[RuntimeVariable]): RuntimeVariable
478 return self.autoadapt
(self.autobox
(args
.first
, recvtype
), recvtype
)
481 # Finalizes a call to a method ´m´ on type ´recvtype´ with arguments ´args´
482 private fun finalize_call
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
484 assert args
.length
== m
.msignature
.arity
+ 1 else debug
("Invalid arity for {m}. {args.length} arguments given.")
486 var rm
= new CustomizedRuntimeFunction(m
, recvtype
)
487 return rm
.call
(self, args
)
490 redef fun call
(m
, recvtype
, args
)
492 var recv_type
= get_recvtype
(m
, recvtype
, args
)
493 var recv
= get_recv
(recv_type
, args
)
494 var new_args
= args
.to_a
495 self.varargize
(m
, m
.msignature
.as(not null), new_args
)
496 new_args
.first
= recv
497 return finalize_call
(m
, recv_type
, new_args
)
500 # Does a call without encapsulating varargs into an array
501 # Avoids multiple encapsulation when calling a super in a variadic function
502 fun call_without_varargize
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
504 var recv_type
= get_recvtype
(m
, recvtype
, args
)
505 var recv
= get_recv
(recv_type
, args
)
506 var new_args
= args
.to_a
507 new_args
.first
= recv
508 return finalize_call
(m
, recv_type
, new_args
)
511 redef fun supercall
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
513 var types
= self.collect_types
(args
.first
)
515 var res
: nullable RuntimeVariable
516 var ret
= m
.mproperty
.intro
.msignature
.return_mtype
520 ret
= self.resolve_for
(ret
, args
.first
)
521 res
= self.new_var
(ret
)
524 self.add
("/* super {m} on {args.first.inspect} */")
525 if args
.first
.mtype
.ctype
!= "val*" then
526 var mclasstype
= args
.first
.mtype
.as(MClassType)
527 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
528 self.add
("/* skip, no method {m} */")
531 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, mclasstype
)
532 var res2
= self.call_without_varargize
(propdef
, mclasstype
, args
)
533 if res
!= null then self.assign
(res
, res2
.as(not null))
537 if types
.is_empty
then
539 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
540 self.bugtype
(args
.first
)
545 self.add
("switch({args.first}->classid) \{")
546 var last
= types
.last
548 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, t
)
549 if not self.compiler
.hardening
and t
== last
then
550 self.add
("default: /* test {t} */")
552 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
554 var res2
= self.call_without_varargize
(propdef
, t
, args
)
555 if res
!= null then self.assign
(res
, res2
.as(not null))
558 if self.compiler
.hardening
then
559 self.add
("default: /* bug */")
560 self.bugtype
(args
.first
)
566 redef fun adapt_signature
(m
, args
)
568 var recv
= args
.first
569 for i
in [0..m
.msignature
.arity
[ do
570 var t
= m
.msignature
.mparameters
[i
].mtype
571 if i
== m
.msignature
.vararg_rank
then
574 t
= self.resolve_for
(t
, recv
)
575 args
[i
+1] = self.autobox
(args
[i
+1], t
)
579 # FIXME: this is currently buggy since recv is not exact
580 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
582 elttype
= self.resolve_for
(elttype
, recv
)
583 return self.array_instance
(varargs
, elttype
)
586 fun bugtype
(recv
: RuntimeVariable)
588 if recv
.mtype
.ctype
!= "val*" then return
589 self.add
("PRINT_ERROR(\"BTD BUG: Dynamic type is %s
, static
type is %s\\n\
", class_names[{recv}->classid], \"{recv.mcasttype}\
");")
590 self.add
("show_backtrace(1);")
593 redef fun isset_attribute
(a
, recv
)
595 check_recv_notnull
(recv
)
597 var types
= self.collect_types
(recv
)
598 var res
= self.new_var
(bool_type
)
600 if types
.is_empty
then
601 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
605 self.add
("/* isset {a} on {recv.inspect} */")
606 self.add
("switch({recv}->classid) \{")
607 var last
= types
.last
609 if not self.compiler
.hardening
and t
== last
then
610 self.add
("default: /*{self.compiler.classid(t)}*/")
612 self.add
("case {self.compiler.classid(t)}:")
614 var recv2
= self.autoadapt
(recv
, t
)
615 var ta
= a
.intro
.static_mtype
.as(not null)
616 ta
= self.resolve_for
(ta
, recv2
)
617 var attr
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
618 if not ta
isa MNullableType then
619 if ta
.ctype
== "val*" then
620 self.add
("{res} = ({attr} != NULL);")
622 self.add
("{res} = 1; /*NOTYET isset on primitive attributes*/")
627 if self.compiler
.hardening
then
628 self.add
("default: /* Bug */")
636 redef fun read_attribute
(a
, recv
)
638 check_recv_notnull
(recv
)
640 var types
= self.collect_types
(recv
)
642 var ret
= a
.intro
.static_mtype
.as(not null)
643 ret
= self.resolve_for
(ret
, recv
)
644 var res
= self.new_var
(ret
)
646 if types
.is_empty
then
647 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
651 self.add
("/* read {a} on {recv.inspect} */")
652 self.add
("switch({recv}->classid) \{")
653 var last
= types
.last
655 if not self.compiler
.hardening
and t
== last
then
656 self.add
("default: /*{self.compiler.classid(t)}*/")
658 self.add
("case {self.compiler.classid(t)}:")
660 var recv2
= self.autoadapt
(recv
, t
)
661 var ta
= a
.intro
.static_mtype
.as(not null)
662 ta
= self.resolve_for
(ta
, recv2
)
663 var res2
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
664 if not ta
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
then
665 if ta
.ctype
== "val*" then
666 self.add
("if ({res2} == NULL) \{")
667 self.add_abort
("Uninitialized attribute {a.name}")
670 self.add
("/*NOTYET isset on primitive attributes*/")
673 self.assign
(res
, res2
)
676 if self.compiler
.hardening
then
677 self.add
("default: /* Bug */")
685 redef fun write_attribute
(a
, recv
, value
)
687 check_recv_notnull
(recv
)
689 var types
= self.collect_types
(recv
)
691 if types
.is_empty
then
692 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
696 self.add
("/* write {a} on {recv.inspect} */")
697 self.add
("switch({recv}->classid) \{")
698 var last
= types
.last
700 if not self.compiler
.hardening
and t
== last
then
701 self.add
("default: /*{self.compiler.classid(t)}*/")
703 self.add
("case {self.compiler.classid(t)}:")
705 var recv2
= self.autoadapt
(recv
, t
)
706 var ta
= a
.intro
.static_mtype
.as(not null)
707 ta
= self.resolve_for
(ta
, recv2
)
708 self.add
("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
711 if self.compiler
.hardening
then
712 self.add
("default: /* Bug*/")
718 redef fun init_instance
(mtype
)
720 mtype
= self.anchor
(mtype
).as(MClassType)
721 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
722 debug
"problem: {mtype} was detected dead"
724 var res
= self.new_expr
("NEW_{mtype.c_name}()", mtype
)
729 redef fun type_test
(value
, mtype
, tag
)
731 mtype
= self.anchor
(mtype
)
732 if not self.compiler
.runtime_type_analysis
.live_cast_types
.has
(mtype
) then
733 debug
"problem: {mtype} was detected cast-dead"
737 var types
= self.collect_types
(value
)
738 var res
= self.new_var
(bool_type
)
740 self.add
("/* isa {mtype} on {value.inspect} */")
741 if value
.mtype
.ctype
!= "val*" then
742 if value
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
743 self.add
("{res} = 1;")
745 self.add
("{res} = 0;")
749 if value
.mcasttype
isa MNullableType or value
.mcasttype
isa MNullType then
750 self.add
("if ({value} == NULL) \{")
751 if mtype
isa MNullableType then
752 self.add
("{res} = 1; /* isa {mtype} */")
754 self.add
("{res} = 0; /* not isa {mtype} */")
758 self.add
("switch({value}->classid) \{")
760 if t
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
761 self.add
("case {self.compiler.classid(t)}: /* {t} */")
764 self.add
("{res} = 1;")
767 self.add
("{res} = 0;")
773 redef fun is_same_type_test
(value1
, value2
)
775 var res
= self.new_var
(bool_type
)
776 if value2
.mtype
.ctype
== "val*" then
777 if value1
.mtype
.ctype
== "val*" then
778 self.add
"{res} = {value1}->classid == {value2}->classid;"
780 self.add
"{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
783 if value1
.mtype
.ctype
== "val*" then
784 self.add
"{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
785 else if value1
.mcasttype
== value2
.mcasttype
then
786 self.add
"{res} = 1;"
788 self.add
"{res} = 0;"
794 redef fun class_name_string
(value
)
796 var res
= self.get_name
("var_class_name")
797 self.add_decl
("const char* {res};")
798 if value
.mtype
.ctype
== "val*" then
799 self.add
"{res} = class_names[{value}->classid];"
801 self.add
"{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
806 redef fun equal_test
(value1
, value2
)
808 var res
= self.new_var
(bool_type
)
809 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
814 if value1
.mtype
.ctype
!= "val*" then
815 if value2
.mtype
== value1
.mtype
then
816 self.add
("{res} = {value1} == {value2};")
817 else if value2
.mtype
.ctype
!= "val*" then
818 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
820 var mtype1
= value1
.mtype
.as(MClassType)
821 self.add
("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
822 self.add
("if ({res}) \{")
823 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
827 var s
= new Array[String]
828 for t
in self.compiler
.live_primitive_types
do
829 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value1
.mcasttype
) then continue
830 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value2
.mcasttype
) then continue
831 s
.add
"({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
834 self.add
("{res} = {value1} == {value2};")
836 self.add
("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
842 redef fun array_instance
(array
, elttype
)
844 elttype
= self.anchor
(elttype
)
845 var arraytype
= self.get_class
("Array").get_mtype
([elttype
])
846 var res
= self.init_instance
(arraytype
)
847 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
848 var nat
= self.new_var
(self.get_class
("NativeArray").get_mtype
([elttype
]))
850 self.add
("{nat} = NEW_{nat.mtype.c_name}({array.length});")
851 for i
in [0..array
.length
[ do
852 var r
= self.autobox
(array
[i
], elttype
)
853 self.add
("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
855 var length
= self.int_instance
(array
.length
)
856 self.send
(self.get_property
("with_native", arraytype
), [res
, nat
, length
])
862 # A runtime function customized on a specific monomrph receiver type
863 private class CustomizedRuntimeFunction
864 super AbstractRuntimeFunction
866 redef type COMPILER: GlobalCompiler
867 redef type VISITOR: GlobalCompilerVisitor
869 # The considered reciever
870 # (usually is a live type but no strong guarantee)
873 init(mmethoddef
: MMethodDef, recv
: MClassType)
879 redef fun build_c_name
881 var res
= self.c_name_cache
882 if res
!= null then return res
883 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
884 res
= self.mmethoddef
.c_name
886 res
= "{mmethoddef.c_name}__{recv.c_name}"
888 self.c_name_cache
= res
892 # used in the compiler worklist
895 if not o
isa CustomizedRuntimeFunction then return false
896 if self.mmethoddef
!= o
.mmethoddef
then return false
897 if self.recv
!= o
.recv
then return false
901 # used in the compiler work-list
902 redef fun hash
do return self.mmethoddef
.hash
+ self.recv
.hash
906 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
907 return self.mmethoddef
.to_s
909 return "{self.mmethoddef}@{self.recv}"
913 # compile the code customized for the reciever
914 redef fun compile_to_c
(compiler
)
917 var mmethoddef
= self.mmethoddef
918 if not recv
.is_subtype
(compiler
.mainmodule
, null, mmethoddef
.mclassdef
.bound_mtype
) then
919 print
("problem: why do we compile {self} for {recv}?")
923 var v
= compiler
.new_visitor
924 var selfvar
= new RuntimeVariable("self", recv
, recv
)
925 if compiler
.runtime_type_analysis
.live_types
.has
(recv
) then
926 selfvar
.is_exact
= true
928 var arguments
= new Array[RuntimeVariable]
929 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
932 var sig
= new FlatBuffer
933 var comment
= new FlatBuffer
934 var ret
= mmethoddef
.msignature
.return_mtype
936 ret
= v
.resolve_for
(ret
, selfvar
)
937 sig
.append
("{ret.ctype} ")
938 else if mmethoddef
.mproperty
.is_new
then
940 sig
.append
("{ret.ctype} ")
944 sig
.append
(self.c_name
)
945 sig
.append
("({recv.ctype} {selfvar}")
946 comment
.append
("(self: {recv}")
947 arguments
.add
(selfvar
)
948 for i
in [0..mmethoddef
.msignature
.arity
[ do
949 var mtype
= mmethoddef
.msignature
.mparameters
[i
].mtype
950 if i
== mmethoddef
.msignature
.vararg_rank
then
951 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
953 mtype
= v
.resolve_for
(mtype
, selfvar
)
954 comment
.append
(", {mtype}")
955 sig
.append
(", {mtype.ctype} p{i}")
956 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
957 arguments
.add
(argvar
)
962 comment
.append
(": {ret}")
964 compiler
.header
.add_decl
("{sig};")
966 v
.add_decl
("/* method {self} for {comment} */")
967 v
.add_decl
("{sig} \{")
968 #v.add("printf(\"method {self} for {comment}\\n\");")
970 frame
.returnvar
= v
.new_var
(ret
)
972 frame
.returnlabel
= v
.get_name
("RET_LABEL")
974 mmethoddef
.compile_inside_to_c
(v
, arguments
)
976 v
.add
("{frame.returnlabel.as(not null)}:;")
978 v
.add
("return {frame.returnvar.as(not null)};")
981 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})"
984 redef fun call
(v
: VISITOR, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
986 var ret
= self.mmethoddef
.msignature
.return_mtype
987 if self.mmethoddef
.mproperty
.is_new
then
991 ret
= v
.resolve_for
(ret
, arguments
.first
)
993 if self.mmethoddef
.can_inline
(v
) then
994 var frame
= new Frame(v
, self.mmethoddef
, self.recv
, arguments
)
995 frame
.returnlabel
= v
.get_name
("RET_LABEL")
997 frame
.returnvar
= v
.new_var
(ret
)
999 var old_frame
= v
.frame
1001 v
.add
("\{ /* Inline {self} ({arguments.join(",")}) */")
1002 self.mmethoddef
.compile_inside_to_c
(v
, arguments
)
1003 v
.add
("{frame.returnlabel.as(not null)}:(void)0;")
1006 return frame
.returnvar
1008 v
.adapt_signature
(self.mmethoddef
, arguments
)
1009 v
.compiler
.todo
(self)
1011 v
.add
("{self.c_name}({arguments.join(",")});")
1014 var res
= v
.new_var
(ret
)
1015 v
.add
("{res} = {self.c_name}({arguments.join(",")});")