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, [contracts_phase
])
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
, callsite
)
468 var mmethoddef
= callsite
.mpropdef
469 var method
= new CustomizedRuntimeFunction(mmethoddef
, recv
.mcasttype
.as(MClassType))
471 if recv
.mtype
.is_c_primitive
then
472 var object_type
= mmodule
.object_type
473 my_recv
= autobox
(recv
, object_type
)
475 var thunk
= new CustomizedThunkFunction(mmethoddef
, my_recv
.mtype
.as(MClassType))
476 thunk
.polymorph_call_flag
= not my_recv
.is_exact
477 compiler
.todo
(method
)
479 var ret_type
= self.anchor
(routine_mclass_type
).as(MClassType)
480 var res
= self.new_expr
("NEW_{ret_type.c_name}({my_recv}, &{thunk.c_name})", ret_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 ret_mtype
= resolve_for
(ret_mtype
, routine
)
504 var callsite
= "{underlying_method}({ss})"
505 if ret_mtype
!= null then
506 var subres
= new_expr
("{callsite}", ret_mtype
)
513 redef fun send
(m
, args
)
515 var types
= self.collect_types
(args
.first
)
517 var res
: nullable RuntimeVariable
518 var ret
= m
.intro
.msignature
.return_mtype
522 ret
= self.resolve_for
(ret
, args
.first
)
523 res
= self.new_var
(ret
)
526 self.add
("/* send {m} on {args.first.inspect} */")
527 if args
.first
.mtype
.is_c_primitive
then
528 var mclasstype
= args
.first
.mtype
.as(MClassType)
529 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
530 self.add
("/* skip, dead class {mclasstype} */")
533 if not mclasstype
.has_mproperty
(self.compiler
.mainmodule
, m
) then
534 self.add
("/* skip, no method {m} */")
537 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, mclasstype
)
538 var res2
= self.call
(propdef
, mclasstype
, args
)
539 if res
!= null then self.assign
(res
, res2
.as(not null))
542 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_null
.value
or m
.name
== "==" or m
.name
== "!="
543 if args
.first
.mcasttype
isa MNullableType or args
.first
.mcasttype
isa MNullType and consider_null
then
544 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
545 self.add
("if ({args.first} == NULL) \{ /* Special null case */")
546 if m
.name
== "==" or m
.name
== "is_same_instance" then
548 if args
[1].mcasttype
isa MNullableType then
549 self.add
("{res} = ({args[1]} == NULL);")
550 else if args
[1].mcasttype
isa MNullType then
551 self.add
("{res} = 1; /* is null */")
553 self.add
("{res} = 0; /* {args[1].inspect} cannot be null */")
555 else if m
.name
== "!=" then
557 if args
[1].mcasttype
isa MNullableType then
558 self.add
("{res} = ({args[1]} != NULL);")
559 else if args
[1].mcasttype
isa MNullType then
560 self.add
("{res} = 0; /* is null */")
562 self.add
("{res} = 1; /* {args[1].inspect} cannot be null */")
565 self.add_abort
("Receiver is null")
569 if types
.is_empty
then
571 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
572 self.bugtype
(args
.first
)
577 self.add
("switch({args.first}->classid) \{")
578 var last
= types
.last
579 var defaultpropdef
: nullable MMethodDef = null
581 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, t
)
582 if propdef
.mclassdef
.mclass
.name
== "Object" and not t
.is_c_primitive
then
583 defaultpropdef
= propdef
586 if not self.compiler
.hardening
and t
== last
and defaultpropdef
== null then
587 self.add
("default: /* test {t} */")
589 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
591 var res2
= self.call
(propdef
, t
, args
)
592 if res
!= null then self.assign
(res
, res2
.as(not null))
595 if defaultpropdef
!= null then
596 self.add
("default: /* default is Object */")
597 var res2
= self.call
(defaultpropdef
, defaultpropdef
.mclassdef
.bound_mtype
, args
)
598 if res
!= null then self.assign
(res
, res2
.as(not null))
599 else if self.compiler
.hardening
then
600 self.add
("default: /* bug */")
601 self.bugtype
(args
.first
)
607 fun check_valid_reciever
(recvtype
: MClassType)
609 if self.compiler
.runtime_type_analysis
.live_types
.has
(recvtype
) or recvtype
.mclass
.name
== "Object" then return
610 print_error
"{recvtype} is not a live type"
614 # Subpart of old call function
616 # Checks if the type of the receiver is valid and corrects it if necessary
617 private fun get_recvtype
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): MClassType
619 check_valid_reciever
(recvtype
)
623 redef fun call
(m
, recvtype
, args
)
625 var recv_type
= get_recvtype
(m
, recvtype
, args
)
626 var recv
= self.autoadapt
(self.autobox
(args
.first
, recvtype
), recvtype
)
627 if m
.is_extern
then recv
= unbox_extern
(recv
, recv_type
)
632 assert args
.length
== m
.msignature
.arity
+ 1 else debug
("Invalid arity for {m}. {args.length} arguments given.")
634 var rm
= new CustomizedRuntimeFunction(m
, recvtype
)
635 return rm
.call
(self, args
)
638 redef fun supercall
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
640 var types
= self.collect_types
(args
.first
)
642 var res
: nullable RuntimeVariable
643 var ret
= m
.mproperty
.intro
.msignature
.return_mtype
647 ret
= self.resolve_for
(ret
, args
.first
)
648 res
= self.new_var
(ret
)
651 self.add
("/* super {m} on {args.first.inspect} */")
652 if args
.first
.mtype
.is_c_primitive
then
653 var mclasstype
= args
.first
.mtype
.as(MClassType)
654 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
655 self.add
("/* skip, no method {m} */")
658 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, mclasstype
)
659 var res2
= self.call
(propdef
, mclasstype
, args
)
660 if res
!= null then self.assign
(res
, res2
.as(not null))
664 if types
.is_empty
then
666 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
667 self.bugtype
(args
.first
)
672 self.add
("switch({args.first}->classid) \{")
673 var last
= types
.last
675 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, t
)
676 if not self.compiler
.hardening
and t
== last
then
677 self.add
("default: /* test {t} */")
679 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
681 var res2
= self.call
(propdef
, t
, args
)
682 if res
!= null then self.assign
(res
, res2
.as(not null))
685 if self.compiler
.hardening
then
686 self.add
("default: /* bug */")
687 self.bugtype
(args
.first
)
693 redef fun adapt_signature
(m
, args
)
695 var recv
= args
.first
696 for i
in [0..m
.msignature
.arity
[ do
697 var mp
= m
.msignature
.mparameters
[i
]
702 t
= self.resolve_for
(t
, recv
)
703 args
[i
+1] = self.autobox
(args
[i
+1], t
)
707 redef fun unbox_signature_extern
(m
, args
)
709 var recv
= args
.first
710 for i
in [0..m
.msignature
.arity
[ do
711 var mp
= m
.msignature
.mparameters
[i
]
716 t
= self.resolve_for
(t
, recv
)
717 if m
.is_extern
then args
[i
+1] = self.unbox_extern
(args
[i
+1], t
)
721 # FIXME: this is currently buggy since recv is not exact
722 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
724 elttype
= self.resolve_for
(elttype
, recv
)
725 return self.array_instance
(varargs
, elttype
)
728 fun bugtype
(recv
: RuntimeVariable)
730 if recv
.mtype
.is_c_primitive
then return
731 self.add
("PRINT_ERROR(\"BTD BUG: Dynamic type is %s
, static
type is %s\\n\
", class_names[{recv}->classid], \"{recv.mcasttype}\
");")
732 self.add
("fatal_exit(1);")
735 redef fun isset_attribute
(a
, recv
)
737 check_recv_notnull
(recv
)
739 var types
= self.collect_types
(recv
)
740 var res
= self.new_var
(bool_type
)
742 if types
.is_empty
then
743 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
747 self.add
("/* isset {a} on {recv.inspect} */")
748 self.add
("switch({recv}->classid) \{")
749 var last
= types
.last
751 if not self.compiler
.hardening
and t
== last
then
752 self.add
("default: /*{self.compiler.classid(t)}*/")
754 self.add
("case {self.compiler.classid(t)}:")
756 var recv2
= self.autoadapt
(recv
, t
)
757 var ta
= a
.intro
.static_mtype
.as(not null)
758 ta
= self.resolve_for
(ta
, recv2
)
759 var attr
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
760 if not ta
isa MNullableType then
761 if not ta
.is_c_primitive
then
762 self.add
("{res} = ({attr} != NULL);")
764 self.add
("{res} = 1; /*NOTYET isset on primitive attributes*/")
769 if self.compiler
.hardening
then
770 self.add
("default: /* Bug */")
778 redef fun read_attribute
(a
, recv
)
780 check_recv_notnull
(recv
)
782 var types
= self.collect_types
(recv
)
784 var ret
= a
.intro
.static_mtype
.as(not null)
785 ret
= self.resolve_for
(ret
, recv
)
786 var res
= self.new_var
(ret
)
788 if types
.is_empty
then
789 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
793 self.add
("/* read {a} on {recv.inspect} */")
794 self.add
("switch({recv}->classid) \{")
795 var last
= types
.last
797 if not self.compiler
.hardening
and t
== last
then
798 self.add
("default: /*{self.compiler.classid(t)}*/")
800 self.add
("case {self.compiler.classid(t)}:")
802 var recv2
= self.autoadapt
(recv
, t
)
803 var ta
= a
.intro
.static_mtype
.as(not null)
804 ta
= self.resolve_for
(ta
, recv2
)
805 var res2
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
806 if not ta
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_attr_isset
.value
then
807 if not ta
.is_c_primitive
then
808 self.add
("if ({res2} == NULL) \{")
809 self.add_abort
("Uninitialized attribute {a.name}")
812 self.add
("/*NOTYET isset on primitive attributes*/")
815 self.assign
(res
, res2
)
818 if self.compiler
.hardening
then
819 self.add
("default: /* Bug */")
827 redef fun write_attribute
(a
, recv
, value
)
829 check_recv_notnull
(recv
)
831 var types
= self.collect_types
(recv
)
833 if types
.is_empty
then
834 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
838 self.add
("/* write {a} on {recv.inspect} */")
839 self.add
("switch({recv}->classid) \{")
840 var last
= types
.last
842 if not self.compiler
.hardening
and t
== last
then
843 self.add
("default: /*{self.compiler.classid(t)}*/")
845 self.add
("case {self.compiler.classid(t)}:")
847 var recv2
= self.autoadapt
(recv
, t
)
848 var ta
= a
.intro
.static_mtype
.as(not null)
849 ta
= self.resolve_for
(ta
, recv2
)
850 self.add
("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
853 if self.compiler
.hardening
then
854 self.add
("default: /* Bug*/")
860 redef fun init_instance
(mtype
)
862 mtype
= self.anchor
(mtype
).as(MClassType)
863 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
864 debug
"problem: {mtype} was detected dead"
866 var res
= self.new_expr
("NEW_{mtype.c_name}()", mtype
)
871 redef fun type_test
(value
, mtype
, tag
)
873 mtype
= self.anchor
(mtype
)
874 if not self.compiler
.runtime_type_analysis
.live_cast_types
.has
(mtype
) then
875 debug
"problem: {mtype} was detected cast-dead"
879 var types
= self.collect_types
(value
)
880 var res
= self.new_var
(bool_type
)
882 self.add
("/* isa {mtype} on {value.inspect} */")
883 if value
.mtype
.is_c_primitive
then
884 if value
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
885 self.add
("{res} = 1;")
887 self.add
("{res} = 0;")
891 if value
.mcasttype
isa MNullableType or value
.mcasttype
isa MNullType then
892 self.add
("if ({value} == NULL) \{")
893 if mtype
isa MNullableType then
894 self.add
("{res} = 1; /* isa {mtype} */")
896 self.add
("{res} = 0; /* not isa {mtype} */")
900 self.add
("switch({value}->classid) \{")
902 if t
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
903 self.add
("case {self.compiler.classid(t)}: /* {t} */")
906 self.add
("{res} = 1;")
909 self.add
("{res} = 0;")
915 redef fun is_same_type_test
(value1
, value2
)
917 var res
= self.new_var
(bool_type
)
918 if not value2
.mtype
.is_c_primitive
then
919 if not value1
.mtype
.is_c_primitive
then
920 self.add
"{res} = {value1}->classid == {value2}->classid;"
922 self.add
"{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
925 if not value1
.mtype
.is_c_primitive
then
926 self.add
"{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
927 else if value1
.mcasttype
== value2
.mcasttype
then
928 self.add
"{res} = 1;"
930 self.add
"{res} = 0;"
936 redef fun class_name_string
(value
)
938 var res
= self.get_name
("var_class_name")
939 self.add_decl
("const char* {res};")
940 if not value
.mtype
.is_c_primitive
then
941 self.add
"{res} = class_names[{value}->classid];"
943 self.add
"{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
948 redef fun equal_test
(value1
, value2
)
950 var res
= self.new_var
(bool_type
)
951 if value2
.mtype
.is_c_primitive
and not value1
.mtype
.is_c_primitive
then
956 if value1
.mtype
.is_c_primitive
then
957 if value2
.mtype
== value1
.mtype
then
958 self.add
("{res} = {value1} == {value2};")
959 else if value2
.mtype
.is_c_primitive
then
960 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
962 var mtype1
= value1
.mtype
.as(MClassType)
963 self.add
("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
964 self.add
("if ({res}) \{")
965 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
969 var s
= new Array[String]
970 for t
in self.compiler
.live_primitive_types
do
971 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value1
.mcasttype
) then continue
972 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value2
.mcasttype
) then continue
973 s
.add
"({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
976 if self.compiler
.mainmodule
.model
.get_mclasses_by_name
("Pointer") != null then
977 var pointer_type
= self.compiler
.mainmodule
.pointer_type
978 if value1
.mcasttype
.is_subtype
(self.compiler
.mainmodule
, null, pointer_type
) or
979 value2
.mcasttype
.is_subtype
(self.compiler
.mainmodule
, null, pointer_type
) then
980 s
.add
"(((struct {pointer_type.c_name}*){value1})->value == ((struct {pointer_type.c_name}*){value2})->value)"
985 self.add
("{res} = {value1} == {value2};")
987 self.add
("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
993 redef fun array_instance
(array
, elttype
)
995 elttype
= self.anchor
(elttype
)
996 var arraytype
= mmodule
.array_type
(elttype
)
997 var res
= self.init_instance
(arraytype
)
998 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
999 var nat
= self.new_var
(mmodule
.native_array_type
(elttype
))
1001 self.add
("{nat} = NEW_{nat.mtype.c_name}({array.length});")
1002 for i
in [0..array
.length
[ do
1003 var r
= self.autobox
(array
[i
], elttype
)
1004 self.add
("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
1006 var length
= self.int_instance
(array
.length
)
1007 self.send
(self.get_property
("with_native", arraytype
), [res
, nat
, length
])
1013 # A runtime function customized on a specific monomorph receiver type
1014 private class CustomizedRuntimeFunction
1015 super AbstractRuntimeFunction
1017 redef type COMPILER: GlobalCompiler
1018 redef type VISITOR: GlobalCompilerVisitor
1020 # The considered reciever
1021 # (usually is a live type but no strong guarantee)
1022 var recv
: MClassType
1024 redef fun build_c_name
1026 var res
= self.c_name_cache
1027 if res
!= null then return res
1028 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
1029 res
= self.mmethoddef
.c_name
1031 res
= "{mmethoddef.c_name}__{recv.c_name}"
1033 self.c_name_cache
= res
1037 # used in the compiler worklist
1040 if not o
isa CustomizedRuntimeFunction then return false
1041 if self.mmethoddef
!= o
.mmethoddef
then return false
1042 if self.recv
!= o
.recv
then return false
1046 # used in the compiler work-list
1047 redef fun hash
do return self.mmethoddef
.hash
+ self.recv
.hash
1051 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
1052 return self.mmethoddef
.to_s
1054 return "{self.mmethoddef}@{self.recv}"
1058 redef fun recv_mtype
1063 redef var return_mtype
1065 redef fun resolve_receiver
(v
)
1067 var selfvar
= new RuntimeVariable("self", recv
, recv
)
1068 if v
.compiler
.runtime_type_analysis
.live_types
.has
(recv
) then
1069 selfvar
.is_exact
= true
1074 redef fun resolve_return_mtype
(v
)
1076 var selfvar
= v
.frame
.selfvar
1078 var ret
= msignature
.return_mtype
.as(not null)
1079 return_mtype
= v
.resolve_for
(ret
, selfvar
)
1082 redef fun resolve_ith_parameter
(v
, i
)
1084 var selfvar
= v
.frame
.selfvar
1085 var mp
= msignature
.mparameters
[i
]
1086 var mtype
= mp
.mtype
1087 if mp
.is_vararg
then
1088 mtype
= v
.mmodule
.array_type
(mtype
)
1090 mtype
= v
.resolve_for
(mtype
, selfvar
)
1091 return new RuntimeVariable("p{i}", mtype
, mtype
)
1094 redef fun declare_signature
(v
, sig
)
1096 v
.compiler
.header
.add_decl
("{sig};")
1099 redef fun end_compile_to_c
(v
)
1101 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})"
1104 redef fun call
(v
: VISITOR, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
1106 var ret
= self.mmethoddef
.msignature
.return_mtype
1108 ret
= v
.resolve_for
(ret
, arguments
.first
)
1111 # TODO: remove this guard when gcc warning issue (#2781) is resolved
1112 # WARNING: the next two lines of code is used to prevent inlining.
1113 # Inlining of a callref seems to work all the time. However,
1114 # it will produce some deadcode in certain scenarios (when using nullable type).
1120 # # ...do something with x...
1124 # var a = new A[nullable Int]
1126 # f.call(null) # Will produce a proper C callsite, but it will
1127 # # produce unreachable (dead code) for type checking
1128 # # and covariance. Thus, creating warnings when
1129 # # compiling in global. However, if you ignore
1130 # # those warnings, the binary works perfectly fine.
1132 var intromclassdef
= self.mmethoddef
.mproperty
.intro_mclassdef
1133 var is_callref
= v
.compiler
.all_routine_types_name
.has
(intromclassdef
.name
)
1135 if self.mmethoddef
.can_inline
(v
) and not is_callref
then
1136 var frame
= new StaticFrame(v
, self.mmethoddef
, self.recv
, arguments
)
1137 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1139 frame
.returnvar
= v
.new_var
(ret
)
1141 var old_frame
= v
.frame
1143 v
.add
("\{ /* Inline {self} ({arguments.join(",")}) */")
1144 self.mmethoddef
.compile_inside_to_c
(v
, arguments
)
1145 v
.add
("{frame.returnlabel.as(not null)}:(void)0;")
1148 return frame
.returnvar
1150 v
.adapt_signature
(self.mmethoddef
, arguments
)
1151 v
.compiler
.todo
(self)
1153 v
.add
("{self.c_name}({arguments.join(",")});")
1156 var res
= v
.new_var
(ret
)
1157 v
.add
("{res} = {self.c_name}({arguments.join(",")});")
1163 # Thunk implementation for global compiler.
1164 # For more detail see `abstract_compiler::ThunkFunction` documentation.
1165 class CustomizedThunkFunction
1167 super CustomizedRuntimeFunction
1171 return "THUNK_" + super
1176 return super + c_name
.hash
1179 redef fun resolve_receiver
(v
)
1182 if res
.is_exact
then res
.is_exact
= not polymorph_call_flag
1186 redef fun target_recv
1188 # If the targeted method was introduced by a primitive type,
1189 # then target_recv must be set to it. Otherwise, there will
1190 # be a missing cast. Here's an example:
1194 # fun mult_by(x:Int):Int do return x * self
1197 # var f = &10.mult_by
1199 # Here the thunk `f` must box the receiver `10` into an object.
1200 # This is due to the memory representation of a call ref which
1201 # has a pointer to an opaque type `val*`:
1204 # struct Mult_by_callref_struct {
1206 # // The receiver `10` would be here
1208 # // the targeted receiver is a `long`
1209 # long (*pointer_to_mult_by)(long, long);
1213 # Thus, every primitive type must be boxed into an `Object` when
1214 # instantiating a callref.
1216 # However, if the underlying method was introduced by a primitive
1217 # type then a cast must be invoked to convert our boxed receiver
1218 # to its original primitive type.
1219 var intro_recv
= mmethoddef
.mproperty
.intro_mclassdef
.bound_mtype
1220 if intro_recv
.is_c_primitive
then