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
.do_compilation
63 compiler
.display_stats
66 self.toolcontext
.info
("*** END GENERATING C: {time1-time0} ***", 2)
67 write_and_make
(compiler
)
71 # Compiler that use global compilation and perform hard optimisations like:
76 super AbstractCompiler
78 redef type VISITOR: GlobalCompilerVisitor
80 # The result of the RTA (used to know live types and methods)
81 var runtime_type_analysis
: RapidTypeAnalysis
85 var file
= new_file
("{mainmodule.c_name}.nitgg")
86 self.header
= new CodeWriter(file
)
87 self.live_primitive_types
= new Array[MClassType]
88 for t
in runtime_type_analysis
.live_types
do
89 if t
.is_c_primitive
or t
.mclass
.name
== "Pointer" then
90 self.live_primitive_types
.add
(t
)
95 redef fun do_compilation
99 compiler
.compile_header
101 if mainmodule
.model
.get_mclasses_by_name
("Pointer") != null then
102 runtime_type_analysis
.live_types
.add
(mainmodule
.pointer_type
)
104 for t
in runtime_type_analysis
.live_types
do
105 compiler
.declare_runtimeclass
(t
)
108 compiler
.compile_class_names
110 # Init instance code (allocate and init-arguments)
111 for t
in runtime_type_analysis
.live_types
do
112 if not t
.is_c_primitive
then
113 compiler
.generate_init_instance
(t
)
114 if t
.mclass
.kind
== extern_kind
then
115 compiler
.generate_box_instance
(t
)
118 compiler
.generate_box_instance
(t
)
122 # The main function of the C
123 compiler
.compile_nitni_global_ref_functions
124 compiler
.compile_main_function
126 # Compile until all runtime_functions are visited
127 while not compiler
.todos
.is_empty
do
128 var m
= compiler
.todos
.shift
129 modelbuilder
.toolcontext
.info
("Compile {m} ({compiler.seen.length-compiler.todos.length}/{compiler.seen.length})", 3)
130 m
.compile_to_c
(compiler
)
132 modelbuilder
.toolcontext
.info
("Total methods to compile to C: {compiler.seen.length}", 2)
136 # Compile class names (for the class_name and output_class_name methods)
137 protected fun compile_class_names
do
139 self.header
.add_decl
("extern const char *class_names[];")
140 v
.add
("const char *class_names[] = \{")
141 for t
in self.runtime_type_analysis
.live_types
do
142 v
.add
("\"{t}\
", /* {self.classid(t)} */")
147 # Return the C symbol associated to a live type runtime
148 # REQUIRE: self.runtime_type_analysis.live_types.has(mtype)
149 fun classid
(mtype
: MClassType): String
151 if self.classids
.has_key
(mtype
) then
152 return self.classids
[mtype
]
154 print_error
"No classid for {mtype}"
159 protected var classids
: HashMap[MClassType, String] = new HashMap[MClassType, String]
161 # Declaration of structures the live Nit types
162 # Each live type is generated as an independent C `struct` type.
163 # They only share a common first field `classid` used to implement the polymorphism.
164 # Usualy, all C variables that refers to a Nit object are typed on the abstract struct `val` that contains only the `classid` field.
165 redef fun compile_header_structs
do
166 self.header
.add_decl
("typedef struct \{int classid;\} val; /* general C type representing a Nit instance. */")
169 # Subset of runtime_type_analysis.live_types that contains only primitive types
170 # Used to implement the equal test
171 var live_primitive_types
: Array[MClassType] is noinit
173 # Add a new todo task
174 fun todo
(m
: AbstractRuntimeFunction)
176 if seen
.has
(m
) then return
181 # runtime_functions that need to be compiled
182 private var todos
: List[AbstractRuntimeFunction] = new List[AbstractRuntimeFunction]
184 # runtime_functions already seen (todo or done)
185 private var seen
: HashSet[AbstractRuntimeFunction] = new HashSet[AbstractRuntimeFunction]
187 # Declare C structures and identifiers for a runtime class
188 fun declare_runtimeclass
(mtype
: MClassType)
191 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
192 v
.add_decl
("/* runtime class {mtype} */")
193 var idnum
= classids
.length
194 var idname
= "ID_" + mtype
.c_name
195 self.classids
[mtype
] = idname
196 v
.add_decl
("#define {idname} {idnum} /* {mtype} */")
198 v
.add_decl
("struct {mtype.c_name} \{")
199 v
.add_decl
("int classid; /* must be {idname} */")
201 if mtype
.mclass
.name
== "NativeArray" then
202 # NativeArrays are just a instance header followed by an array of values
203 v
.add_decl
("int length;")
204 v
.add_decl
("{mtype.arguments.first.ctype} values[1];")
207 if all_routine_types_name
.has
(mtype
.mclass
.name
) then
208 v
.add_decl
("val* recv;")
209 var c_args
= ["val* self"]
211 var k
= mtype
.arguments
.length
212 if mtype
.mclass
.name
.has
("Fun") then
213 c_ret
= mtype
.arguments
.last
.ctype
217 var t
= mtype
.arguments
[i
]
218 c_args
.push
("{t.ctype} p{i}")
220 var c_sig
= c_args
.join
(", ")
221 v
.add_decl
("{c_ret} (*method)({c_sig});")
224 if mtype
.ctype_extern
!= "val*" then
225 # Is the Nit type is native then the struct is a box with two fields:
226 # * the `classid` to be polymorph
227 # * the `value` that contains the native value.
228 v
.add_decl
("{mtype.ctype_extern} value;")
231 # Collect all attributes and associate them a field in the structure.
232 # Note: we do not try to optimize the order and helps CC to optimize the client code.
233 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
234 for p
in cd
.intro_mproperties
do
235 if not p
isa MAttribute then continue
236 var t
= p
.intro
.static_mtype
.as(not null)
237 t
= t
.anchor_to
(self.mainmodule
, mtype
)
238 v
.add_decl
("{t.ctype} {p.intro.c_name}; /* {p}: {t} */")
244 # Generate the init-instance of a live type (allocate + init-instance)
245 fun generate_init_instance
(mtype
: MClassType)
247 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
248 assert not mtype
.is_c_primitive
249 var v
= self.new_visitor
251 var is_native_array
= mtype
.mclass
.name
== "NativeArray"
252 var is_routine_ref
= all_routine_types_name
.has
(mtype
.mclass
.name
)
254 if is_native_array
then
259 if is_routine_ref
then
260 var c_args
= ["val* self"]
262 var k
= mtype
.arguments
.length
263 if mtype
.mclass
.name
.has
("Fun") then
264 c_ret
= mtype
.arguments
.last
.ctype
268 var t
= mtype
.arguments
[i
]
269 c_args
.push
("{t.ctype} p{i}")
271 # The underlying method signature
272 var method_sig
= "{c_ret} (*method)({c_args.join(", ")})"
273 sig
= "val* recv, {method_sig}"
276 self.header
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig});")
277 v
.add_decl
("/* allocate {mtype} */")
278 v
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig}) \{")
279 var res
= v
.new_var
(mtype
)
281 if is_native_array
then
282 v
.add
("{res} = nit_alloc(sizeof(struct {mtype.c_name}) + length*sizeof(val*));")
283 v
.add
("((struct {mtype.c_name}*){res})->length = length;")
285 v
.add
("{res} = nit_alloc(sizeof(struct {mtype.c_name}));")
287 if is_routine_ref
then
288 v
.add
("((struct {mtype.c_name}*){res})->recv = recv;")
289 v
.add
("((struct {mtype.c_name}*){res})->method = method;")
291 v
.add
("{res}->classid = {self.classid(mtype)};")
293 self.generate_init_attr
(v
, res
, mtype
)
295 v
.add
("return {res};")
299 fun generate_box_instance
(mtype
: MClassType)
301 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
302 var v
= self.new_visitor
304 self.header
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype});")
305 v
.add_decl
("/* allocate {mtype} */")
306 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
307 v
.add
("struct {mtype.c_name}*res = nit_alloc(sizeof(struct {mtype.c_name}));")
308 v
.add
("res->classid = {self.classid(mtype)};")
309 v
.add
("res->value = value;")
310 v
.add
("return (val*)res;")
314 redef fun new_visitor
do return new GlobalCompilerVisitor(self)
316 private var collect_types_cache
: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
318 redef fun compile_nitni_structs
320 self.header
.add_decl
"""
321 struct nitni_instance \{
322 struct nitni_instance *next,
323 *prev; /* adjacent global references in global list */
324 int count; /* number of time this global reference has been marked */
331 # A visitor on the AST of property definition that generate the C code.
332 # Because of inlining, a visitor can visit more than one property.
333 class GlobalCompilerVisitor
334 super AbstractCompilerVisitor
336 redef type COMPILER: GlobalCompiler
338 redef fun autobox
(value
, mtype
)
340 if value
.mtype
== mtype
then
342 else if not value
.mtype
.is_c_primitive
and not mtype
.is_c_primitive
then
344 else if not value
.mtype
.is_c_primitive
then
345 return self.new_expr
("((struct {mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
346 else if not mtype
.is_c_primitive
then
347 var valtype
= value
.mtype
.as(MClassType)
348 var res
= self.new_var
(mtype
)
349 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
350 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
351 self.add
("PRINT_ERROR(\"Dead code executed
!\\n\
"); fatal_exit(1);")
354 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
356 else if value
.mtype
.ctype
== "void*" and mtype
.ctype
== "void*" then
359 # Bad things will appen!
360 var res
= self.new_var
(mtype
)
361 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
362 self.add
("PRINT_ERROR(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); fatal_exit(1);")
367 redef fun unbox_extern
(value
, mtype
)
369 if mtype
isa MClassType and mtype
.mclass
.kind
== extern_kind
and
370 mtype
.mclass
.name
!= "CString" then
371 var res
= self.new_var_extern
(mtype
)
372 self.add
"{res} = ((struct {mtype.c_name}*){value})->value; /* unboxing {value.mtype} */"
379 redef fun box_extern
(value
, mtype
)
381 if not mtype
isa MClassType or mtype
.mclass
.kind
!= extern_kind
or
382 mtype
.mclass
.name
== "CString" then return value
384 var valtype
= value
.mtype
.as(MClassType)
385 var res
= self.new_var
(mtype
)
386 if not compiler
.runtime_type_analysis
.live_types
.has
(value
.mtype
.as(MClassType)) then
387 self.add
("/*no boxing of {value.mtype}: {value.mtype} is not live! */")
388 self.add
("PRINT_ERROR(\"Dead code executed
!\\n\
"); fatal_exit(1);")
391 self.add
("{res} = BOX_{valtype.c_name}({value}); /* boxing {value.mtype} */")
395 # The runtime types that are acceptable for a given receiver.
396 fun collect_types
(recv
: RuntimeVariable): Array[MClassType]
398 var mtype
= recv
.mcasttype
399 if recv
.is_exact
then
400 assert mtype
isa MClassType
401 assert self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
)
405 var cache
= self.compiler
.collect_types_cache
406 if cache
.has_key
(mtype
) then
409 var types
= new Array[MClassType]
410 var mainmodule
= self.compiler
.mainmodule
411 for t
in self.compiler
.runtime_type_analysis
.live_types
do
412 if not t
.is_subtype
(mainmodule
, null, mtype
) then continue
419 redef fun native_array_def
(pname
, ret_type
, arguments
)
421 var elttype
= arguments
.first
.mtype
422 var recv
= "((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->values"
423 if pname
== "[]" then
424 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
426 else if pname
== "[]=" then
427 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
429 else if pname
== "length" then
430 self.ret
(self.new_expr
("((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->length", ret_type
.as(not null)))
432 else if pname
== "copy_to" then
433 var recv1
= "((struct {arguments[1].mcasttype.c_name}*){arguments[1]})->values"
434 self.add
("memmove({recv1},{recv},{arguments[2]}*sizeof({elttype.ctype}));")
436 else if pname
== "memmove" then
437 # fun memmove(start: Int, length: Int, dest: NativeArray[E], dest_start: Int) is intern do
438 var recv1
= "((struct {arguments[3].mcasttype.c_name}*){arguments[3]})->values"
439 self.add
("memmove({recv1}+{arguments[4]}, {recv}+{arguments[1]}, {arguments[2]}*sizeof({elttype.ctype}));")
445 redef fun native_array_instance
(elttype
, length
)
447 var ret_type
= mmodule
.native_array_type
(elttype
)
448 ret_type
= anchor
(ret_type
).as(MClassType)
449 length
= autobox
(length
, compiler
.mainmodule
.int_type
)
450 return self.new_expr
("NEW_{ret_type.c_name}((int){length})", ret_type
)
453 redef fun native_array_get
(nat
, i
)
455 var recv
= "((struct {nat.mcasttype.c_name}*){nat})->values"
456 var ret_type
= nat
.mcasttype
.as(MClassType).arguments
.first
457 return self.new_expr
("{recv}[{i}]", ret_type
)
460 redef fun native_array_set
(nat
, i
, val
)
462 var recv
= "((struct {nat.mcasttype.c_name}*){nat})->values"
463 self.add
("{recv}[{i}]={val};")
466 redef fun routine_ref_instance
(routine_mclass_type
, recv
, mmethoddef
)
468 var method
= new CustomizedRuntimeFunction(mmethoddef
, recv
.mcasttype
.as(MClassType))
470 if recv
.mtype
.is_c_primitive
then
471 var object_type
= mmodule
.object_type
472 my_recv
= autobox
(recv
, object_type
)
474 var thunk
= new CustomizedThunkFunction(mmethoddef
, my_recv
.mtype
.as(MClassType))
475 thunk
.polymorph_call_flag
= not my_recv
.is_exact
#true
476 #thunk.force_polymorphism = not my_recv.is_exact
477 compiler
.todo
(method
)
480 var res
= self.new_expr
("NEW_{routine_mclass_type.c_name}({my_recv}, &{thunk.c_name})", routine_mclass_type
)
484 redef fun routine_ref_call
(mmethoddef
, arguments
)
486 var routine
= arguments
.first
487 var routine_type
= routine
.mtype
.as(MClassType)
488 var routine_class
= routine_type
.mclass
489 var underlying_recv
= "((struct {routine.mcasttype.c_name}*){routine})->recv"
490 var underlying_method
= "((struct {routine.mcasttype.c_name}*){routine})->method"
491 adapt_signature
(mmethoddef
, arguments
)
493 var ss
= "{underlying_recv}"
494 if arguments
.length
> 0 then
495 ss
= "{ss}, {arguments.join(", ")}"
497 arguments
.unshift routine
499 var ret_mtype
= mmethoddef
.msignature
.return_mtype
501 if ret_mtype
!= null then
502 # TODO check for separate compiler
503 ret_mtype
= resolve_for
(ret_mtype
, routine
)
504 # var temp = ret_mtype
505 # If mmethoddef has a return type, use the type defined
506 # in the routine instance instead.
507 #ret_mtype = routine_type.arguments.last
509 var callsite
= "{underlying_method}({ss})"
510 if ret_mtype
!= null then
511 var subres
= new_expr
("{callsite}", ret_mtype
)
518 redef fun send
(m
, args
)
520 var types
= self.collect_types
(args
.first
)
522 var res
: nullable RuntimeVariable
523 var ret
= m
.intro
.msignature
.return_mtype
527 ret
= self.resolve_for
(ret
, args
.first
)
528 res
= self.new_var
(ret
)
531 self.add
("/* send {m} on {args.first.inspect} */")
532 if args
.first
.mtype
.is_c_primitive
then
533 var mclasstype
= args
.first
.mtype
.as(MClassType)
534 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
535 self.add
("/* skip, dead class {mclasstype} */")
538 if not mclasstype
.has_mproperty
(self.compiler
.mainmodule
, m
) then
539 self.add
("/* skip, no method {m} */")
542 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, mclasstype
)
543 var res2
= self.call
(propdef
, mclasstype
, args
)
544 if res
!= null then self.assign
(res
, res2
.as(not null))
547 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_null
.value
or m
.name
== "==" or m
.name
== "!="
548 if args
.first
.mcasttype
isa MNullableType or args
.first
.mcasttype
isa MNullType and consider_null
then
549 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
550 self.add
("if ({args.first} == NULL) \{ /* Special null case */")
551 if m
.name
== "==" or m
.name
== "is_same_instance" then
553 if args
[1].mcasttype
isa MNullableType then
554 self.add
("{res} = ({args[1]} == NULL);")
555 else if args
[1].mcasttype
isa MNullType then
556 self.add
("{res} = 1; /* is null */")
558 self.add
("{res} = 0; /* {args[1].inspect} cannot be null */")
560 else if m
.name
== "!=" then
562 if args
[1].mcasttype
isa MNullableType then
563 self.add
("{res} = ({args[1]} != NULL);")
564 else if args
[1].mcasttype
isa MNullType then
565 self.add
("{res} = 0; /* is null */")
567 self.add
("{res} = 1; /* {args[1].inspect} cannot be null */")
570 self.add_abort
("Receiver is null")
574 if types
.is_empty
then
576 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
577 self.bugtype
(args
.first
)
582 self.add
("switch({args.first}->classid) \{")
583 var last
= types
.last
584 var defaultpropdef
: nullable MMethodDef = null
586 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, t
)
587 if propdef
.mclassdef
.mclass
.name
== "Object" and not t
.is_c_primitive
then
588 defaultpropdef
= propdef
591 if not self.compiler
.hardening
and t
== last
and defaultpropdef
== null then
592 self.add
("default: /* test {t} */")
594 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
596 var res2
= self.call
(propdef
, t
, args
)
597 if res
!= null then self.assign
(res
, res2
.as(not null))
600 if defaultpropdef
!= null then
601 self.add
("default: /* default is Object */")
602 var res2
= self.call
(defaultpropdef
, defaultpropdef
.mclassdef
.bound_mtype
, args
)
603 if res
!= null then self.assign
(res
, res2
.as(not null))
604 else if self.compiler
.hardening
then
605 self.add
("default: /* bug */")
606 self.bugtype
(args
.first
)
612 fun check_valid_reciever
(recvtype
: MClassType)
614 if self.compiler
.runtime_type_analysis
.live_types
.has
(recvtype
) or recvtype
.mclass
.name
== "Object" then return
615 print_error
"{recvtype} is not a live type"
619 # Subpart of old call function
621 # Checks if the type of the receiver is valid and corrects it if necessary
622 private fun get_recvtype
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): MClassType
624 check_valid_reciever
(recvtype
)
628 redef fun call
(m
, recvtype
, args
)
630 var recv_type
= get_recvtype
(m
, recvtype
, args
)
631 var recv
= self.autoadapt
(self.autobox
(args
.first
, recvtype
), recvtype
)
632 if m
.is_extern
then recv
= unbox_extern
(recv
, recv_type
)
637 assert args
.length
== m
.msignature
.arity
+ 1 else debug
("Invalid arity for {m}. {args.length} arguments given.")
639 var rm
= new CustomizedRuntimeFunction(m
, recvtype
)
640 return rm
.call
(self, args
)
643 redef fun supercall
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
645 var types
= self.collect_types
(args
.first
)
647 var res
: nullable RuntimeVariable
648 var ret
= m
.mproperty
.intro
.msignature
.return_mtype
652 ret
= self.resolve_for
(ret
, args
.first
)
653 res
= self.new_var
(ret
)
656 self.add
("/* super {m} on {args.first.inspect} */")
657 if args
.first
.mtype
.is_c_primitive
then
658 var mclasstype
= args
.first
.mtype
.as(MClassType)
659 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
660 self.add
("/* skip, no method {m} */")
663 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, mclasstype
)
664 var res2
= self.call
(propdef
, mclasstype
, args
)
665 if res
!= null then self.assign
(res
, res2
.as(not null))
669 if types
.is_empty
then
671 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
672 self.bugtype
(args
.first
)
677 self.add
("switch({args.first}->classid) \{")
678 var last
= types
.last
680 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, t
)
681 if not self.compiler
.hardening
and t
== last
then
682 self.add
("default: /* test {t} */")
684 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
686 var res2
= self.call
(propdef
, t
, args
)
687 if res
!= null then self.assign
(res
, res2
.as(not null))
690 if self.compiler
.hardening
then
691 self.add
("default: /* bug */")
692 self.bugtype
(args
.first
)
698 redef fun adapt_signature
(m
, args
)
700 var recv
= args
.first
701 for i
in [0..m
.msignature
.arity
[ do
702 var mp
= m
.msignature
.mparameters
[i
]
707 t
= self.resolve_for
(t
, recv
)
708 args
[i
+1] = self.autobox
(args
[i
+1], t
)
712 redef fun unbox_signature_extern
(m
, args
)
714 var recv
= args
.first
715 for i
in [0..m
.msignature
.arity
[ do
716 var mp
= m
.msignature
.mparameters
[i
]
721 t
= self.resolve_for
(t
, recv
)
722 if m
.is_extern
then args
[i
+1] = self.unbox_extern
(args
[i
+1], t
)
726 # FIXME: this is currently buggy since recv is not exact
727 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
729 elttype
= self.resolve_for
(elttype
, recv
)
730 return self.array_instance
(varargs
, elttype
)
733 fun bugtype
(recv
: RuntimeVariable)
735 if recv
.mtype
.is_c_primitive
then return
736 self.add
("PRINT_ERROR(\"BTD BUG: Dynamic type is %s
, static
type is %s\\n\
", class_names[{recv}->classid], \"{recv.mcasttype}\
");")
737 self.add
("fatal_exit(1);")
740 redef fun isset_attribute
(a
, recv
)
742 check_recv_notnull
(recv
)
744 var types
= self.collect_types
(recv
)
745 var res
= self.new_var
(bool_type
)
747 if types
.is_empty
then
748 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
752 self.add
("/* isset {a} on {recv.inspect} */")
753 self.add
("switch({recv}->classid) \{")
754 var last
= types
.last
756 if not self.compiler
.hardening
and t
== last
then
757 self.add
("default: /*{self.compiler.classid(t)}*/")
759 self.add
("case {self.compiler.classid(t)}:")
761 var recv2
= self.autoadapt
(recv
, t
)
762 var ta
= a
.intro
.static_mtype
.as(not null)
763 ta
= self.resolve_for
(ta
, recv2
)
764 var attr
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
765 if not ta
isa MNullableType then
766 if not ta
.is_c_primitive
then
767 self.add
("{res} = ({attr} != NULL);")
769 self.add
("{res} = 1; /*NOTYET isset on primitive attributes*/")
774 if self.compiler
.hardening
then
775 self.add
("default: /* Bug */")
783 redef fun read_attribute
(a
, recv
)
785 check_recv_notnull
(recv
)
787 var types
= self.collect_types
(recv
)
789 var ret
= a
.intro
.static_mtype
.as(not null)
790 ret
= self.resolve_for
(ret
, recv
)
791 var res
= self.new_var
(ret
)
793 if types
.is_empty
then
794 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
798 self.add
("/* read {a} on {recv.inspect} */")
799 self.add
("switch({recv}->classid) \{")
800 var last
= types
.last
802 if not self.compiler
.hardening
and t
== last
then
803 self.add
("default: /*{self.compiler.classid(t)}*/")
805 self.add
("case {self.compiler.classid(t)}:")
807 var recv2
= self.autoadapt
(recv
, t
)
808 var ta
= a
.intro
.static_mtype
.as(not null)
809 ta
= self.resolve_for
(ta
, recv2
)
810 var res2
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
811 if not ta
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_attr_isset
.value
then
812 if not ta
.is_c_primitive
then
813 self.add
("if ({res2} == NULL) \{")
814 self.add_abort
("Uninitialized attribute {a.name}")
817 self.add
("/*NOTYET isset on primitive attributes*/")
820 self.assign
(res
, res2
)
823 if self.compiler
.hardening
then
824 self.add
("default: /* Bug */")
832 redef fun write_attribute
(a
, recv
, value
)
834 check_recv_notnull
(recv
)
836 var types
= self.collect_types
(recv
)
838 if types
.is_empty
then
839 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
843 self.add
("/* write {a} on {recv.inspect} */")
844 self.add
("switch({recv}->classid) \{")
845 var last
= types
.last
847 if not self.compiler
.hardening
and t
== last
then
848 self.add
("default: /*{self.compiler.classid(t)}*/")
850 self.add
("case {self.compiler.classid(t)}:")
852 var recv2
= self.autoadapt
(recv
, t
)
853 var ta
= a
.intro
.static_mtype
.as(not null)
854 ta
= self.resolve_for
(ta
, recv2
)
855 self.add
("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
858 if self.compiler
.hardening
then
859 self.add
("default: /* Bug*/")
865 redef fun init_instance
(mtype
)
867 mtype
= self.anchor
(mtype
).as(MClassType)
868 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
869 debug
"problem: {mtype} was detected dead"
871 var res
= self.new_expr
("NEW_{mtype.c_name}()", mtype
)
876 redef fun type_test
(value
, mtype
, tag
)
878 mtype
= self.anchor
(mtype
)
879 if not self.compiler
.runtime_type_analysis
.live_cast_types
.has
(mtype
) then
880 debug
"problem: {mtype} was detected cast-dead"
884 var types
= self.collect_types
(value
)
885 var res
= self.new_var
(bool_type
)
887 self.add
("/* isa {mtype} on {value.inspect} */")
888 if value
.mtype
.is_c_primitive
then
889 if value
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
890 self.add
("{res} = 1;")
892 self.add
("{res} = 0;")
896 if value
.mcasttype
isa MNullableType or value
.mcasttype
isa MNullType then
897 self.add
("if ({value} == NULL) \{")
898 if mtype
isa MNullableType then
899 self.add
("{res} = 1; /* isa {mtype} */")
901 self.add
("{res} = 0; /* not isa {mtype} */")
905 self.add
("switch({value}->classid) \{")
907 if t
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
908 self.add
("case {self.compiler.classid(t)}: /* {t} */")
911 self.add
("{res} = 1;")
914 self.add
("{res} = 0;")
920 redef fun is_same_type_test
(value1
, value2
)
922 var res
= self.new_var
(bool_type
)
923 if not value2
.mtype
.is_c_primitive
then
924 if not value1
.mtype
.is_c_primitive
then
925 self.add
"{res} = {value1}->classid == {value2}->classid;"
927 self.add
"{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
930 if not value1
.mtype
.is_c_primitive
then
931 self.add
"{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
932 else if value1
.mcasttype
== value2
.mcasttype
then
933 self.add
"{res} = 1;"
935 self.add
"{res} = 0;"
941 redef fun class_name_string
(value
)
943 var res
= self.get_name
("var_class_name")
944 self.add_decl
("const char* {res};")
945 if not value
.mtype
.is_c_primitive
then
946 self.add
"{res} = class_names[{value}->classid];"
948 self.add
"{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
953 redef fun equal_test
(value1
, value2
)
955 var res
= self.new_var
(bool_type
)
956 if value2
.mtype
.is_c_primitive
and not value1
.mtype
.is_c_primitive
then
961 if value1
.mtype
.is_c_primitive
then
962 if value2
.mtype
== value1
.mtype
then
963 self.add
("{res} = {value1} == {value2};")
964 else if value2
.mtype
.is_c_primitive
then
965 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
967 var mtype1
= value1
.mtype
.as(MClassType)
968 self.add
("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
969 self.add
("if ({res}) \{")
970 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
974 var s
= new Array[String]
975 for t
in self.compiler
.live_primitive_types
do
976 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value1
.mcasttype
) then continue
977 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value2
.mcasttype
) then continue
978 s
.add
"({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
981 if self.compiler
.mainmodule
.model
.get_mclasses_by_name
("Pointer") != null then
982 var pointer_type
= self.compiler
.mainmodule
.pointer_type
983 if value1
.mcasttype
.is_subtype
(self.compiler
.mainmodule
, null, pointer_type
) or
984 value2
.mcasttype
.is_subtype
(self.compiler
.mainmodule
, null, pointer_type
) then
985 s
.add
"(((struct {pointer_type.c_name}*){value1})->value == ((struct {pointer_type.c_name}*){value2})->value)"
990 self.add
("{res} = {value1} == {value2};")
992 self.add
("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
998 redef fun array_instance
(array
, elttype
)
1000 elttype
= self.anchor
(elttype
)
1001 var arraytype
= mmodule
.array_type
(elttype
)
1002 var res
= self.init_instance
(arraytype
)
1003 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
1004 var nat
= self.new_var
(mmodule
.native_array_type
(elttype
))
1006 self.add
("{nat} = NEW_{nat.mtype.c_name}({array.length});")
1007 for i
in [0..array
.length
[ do
1008 var r
= self.autobox
(array
[i
], elttype
)
1009 self.add
("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
1011 var length
= self.int_instance
(array
.length
)
1012 self.send
(self.get_property
("with_native", arraytype
), [res
, nat
, length
])
1018 # A runtime function customized on a specific monomorph receiver type
1019 private class CustomizedRuntimeFunction
1020 super AbstractRuntimeFunction
1022 redef type COMPILER: GlobalCompiler
1023 redef type VISITOR: GlobalCompilerVisitor
1025 # The considered reciever
1026 # (usually is a live type but no strong guarantee)
1027 var recv
: MClassType
1029 redef fun build_c_name
1031 var res
= self.c_name_cache
1032 if res
!= null then return res
1033 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
1034 res
= self.mmethoddef
.c_name
1036 res
= "{mmethoddef.c_name}__{recv.c_name}"
1038 self.c_name_cache
= res
1042 # used in the compiler worklist
1045 if not o
isa CustomizedRuntimeFunction then return false
1046 if self.mmethoddef
!= o
.mmethoddef
then return false
1047 if self.recv
!= o
.recv
then return false
1051 # used in the compiler work-list
1052 redef fun hash
do return self.mmethoddef
.hash
+ self.recv
.hash
1056 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
1057 return self.mmethoddef
.to_s
1059 return "{self.mmethoddef}@{self.recv}"
1063 redef fun recv_mtype
1068 redef var return_mtype
1070 redef fun resolve_receiver
(v
)
1072 var selfvar
= new RuntimeVariable("self", recv
, recv
)
1073 if v
.compiler
.runtime_type_analysis
.live_types
.has
(recv
) then
1074 selfvar
.is_exact
= true
1079 redef fun resolve_return_mtype
(v
)
1081 var selfvar
= v
.frame
.selfvar
1083 var ret
= msignature
.return_mtype
.as(not null)
1084 return_mtype
= v
.resolve_for
(ret
, selfvar
)
1087 redef fun resolve_ith_parameter
(v
, i
)
1089 var selfvar
= v
.frame
.selfvar
1090 var mp
= msignature
.mparameters
[i
]
1091 var mtype
= mp
.mtype
1092 if mp
.is_vararg
then
1093 mtype
= v
.mmodule
.array_type
(mtype
)
1095 mtype
= v
.resolve_for
(mtype
, selfvar
)
1096 return new RuntimeVariable("p{i}", mtype
, mtype
)
1099 redef fun declare_signature
(v
, sig
)
1101 v
.compiler
.header
.add_decl
("{sig};")
1104 redef fun end_compile_to_c
(v
)
1106 if not self.c_name
.has_substring
("VIRTUAL", 0) then v
.compiler
.names
[self.c_name
] = "{mmethoddef.mclassdef.mmodule.name}::{mmethoddef.mclassdef.mclass.name}::{mmethoddef.mproperty.name} ({mmethoddef.location.file.filename}:{mmethoddef.location.line_start})"
1109 redef fun call
(v
: VISITOR, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
1111 var ret
= self.mmethoddef
.msignature
.return_mtype
1113 ret
= v
.resolve_for
(ret
, arguments
.first
)
1116 # TODO: remove this guard when gcc warning issue (#2781) is resolved
1117 # WARNING: the next two lines of code is used to prevent inlining.
1118 # Inlining of a callref seems to work all the time. However,
1119 # it will produce some deadcode in certain scenarios (when using nullable type).
1125 # ...do something with x...
1129 # var a = new A[nullable Int]
1131 # f.call(null) <-- Will produce a proper C callsite, but it will
1132 # -- produce unreachable (dead code) for type checking
1133 # -- and covariance. Thus, creating warnings when
1134 # -- compiling in global. However, if you ignore
1135 # -- those warnings, the binary works perfectly fine.
1137 var intromclassdef
= self.mmethoddef
.mproperty
.intro_mclassdef
1138 var is_callref
= v
.compiler
.all_routine_types_name
.has
(intromclassdef
.name
)
1140 if self.mmethoddef
.can_inline
(v
) and not is_callref
then
1141 var frame
= new StaticFrame(v
, self.mmethoddef
, self.recv
, arguments
)
1142 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1144 frame
.returnvar
= v
.new_var
(ret
)
1146 var old_frame
= v
.frame
1148 v
.add
("\{ /* Inline {self} ({arguments.join(",")}) */")
1149 self.mmethoddef
.compile_inside_to_c
(v
, arguments
)
1150 v
.add
("{frame.returnlabel.as(not null)}:(void)0;")
1153 return frame
.returnvar
1155 v
.adapt_signature
(self.mmethoddef
, arguments
)
1156 v
.compiler
.todo
(self)
1158 v
.add
("{self.c_name}({arguments.join(",")});")
1161 var res
= v
.new_var
(ret
)
1162 v
.add
("{res} = {self.c_name}({arguments.join(",")});")
1168 class CustomizedThunkFunction
1170 super CustomizedRuntimeFunction
1172 #var force_polymorphism = false
1176 return "THUNK_" + super
1181 return super + c_name
.hash
1184 redef fun resolve_receiver
(v
)
1187 if res
.is_exact
then res
.is_exact
= not polymorph_call_flag
1191 redef fun target_recv
1193 # If the targeted method was introduced by a primitive type,
1194 # then target_recv must be set to it. Otherwise, there will
1195 # be a missing cast. Here's an example:
1199 # fun mult_by(x:Int):Int do return x * self
1202 # var f = &10.mult_by
1204 # Here the thunk `f` must box the receiver `10` into an object.
1205 # This is due to the memory representation of a call ref which
1206 # has a pointer to an opaque type `val*`:
1209 # struct Mult_by_callref_struct {
1211 # // The receiver `10` would be here
1213 # // the targeted receiver is a `long`
1214 # long (*pointer_to_mult_by)(long, long);
1218 # Thus, every primitive type must be boxed into an `Object` when
1219 # instantiating a callref.
1221 # However, if the underlying method was introduced by a primitive
1222 # type then a cast must be invoked to convert our boxed receiver
1223 # to its original primitive type.
1224 var intro_recv
= mmethoddef
.mproperty
.intro_mclassdef
.bound_mtype
1225 if intro_recv
.is_c_primitive
then