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
476 compiler
.todo
(method
)
479 var res
= self.new_expr
("NEW_{routine_mclass_type.c_name}({my_recv}, &{thunk.c_name})", routine_mclass_type
)
483 redef fun routine_ref_call
(mmethoddef
, arguments
)
485 var routine
= arguments
.first
486 var routine_type
= routine
.mtype
.as(MClassType)
487 var routine_class
= routine_type
.mclass
488 var underlying_recv
= "((struct {routine.mcasttype.c_name}*){routine})->recv"
489 var underlying_method
= "((struct {routine.mcasttype.c_name}*){routine})->method"
490 adapt_signature
(mmethoddef
, arguments
)
492 var ss
= "{underlying_recv}"
493 if arguments
.length
> 0 then
494 ss
= "{ss}, {arguments.join(", ")}"
496 arguments
.unshift routine
498 var ret_mtype
= mmethoddef
.msignature
.return_mtype
500 if ret_mtype
!= null then
501 ret_mtype
= resolve_for
(ret_mtype
, routine
)
503 var callsite
= "{underlying_method}({ss})"
504 if ret_mtype
!= null then
505 var subres
= new_expr
("{callsite}", ret_mtype
)
512 redef fun send
(m
, args
)
514 var types
= self.collect_types
(args
.first
)
516 var res
: nullable RuntimeVariable
517 var ret
= m
.intro
.msignature
.return_mtype
521 ret
= self.resolve_for
(ret
, args
.first
)
522 res
= self.new_var
(ret
)
525 self.add
("/* send {m} on {args.first.inspect} */")
526 if args
.first
.mtype
.is_c_primitive
then
527 var mclasstype
= args
.first
.mtype
.as(MClassType)
528 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
529 self.add
("/* skip, dead class {mclasstype} */")
532 if not mclasstype
.has_mproperty
(self.compiler
.mainmodule
, m
) then
533 self.add
("/* skip, no method {m} */")
536 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, mclasstype
)
537 var res2
= self.call
(propdef
, mclasstype
, args
)
538 if res
!= null then self.assign
(res
, res2
.as(not null))
541 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_null
.value
or m
.name
== "==" or m
.name
== "!="
542 if args
.first
.mcasttype
isa MNullableType or args
.first
.mcasttype
isa MNullType and consider_null
then
543 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
544 self.add
("if ({args.first} == NULL) \{ /* Special null case */")
545 if m
.name
== "==" or m
.name
== "is_same_instance" then
547 if args
[1].mcasttype
isa MNullableType then
548 self.add
("{res} = ({args[1]} == NULL);")
549 else if args
[1].mcasttype
isa MNullType then
550 self.add
("{res} = 1; /* is null */")
552 self.add
("{res} = 0; /* {args[1].inspect} cannot be null */")
554 else if m
.name
== "!=" then
556 if args
[1].mcasttype
isa MNullableType then
557 self.add
("{res} = ({args[1]} != NULL);")
558 else if args
[1].mcasttype
isa MNullType then
559 self.add
("{res} = 0; /* is null */")
561 self.add
("{res} = 1; /* {args[1].inspect} cannot be null */")
564 self.add_abort
("Receiver is null")
568 if types
.is_empty
then
570 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
571 self.bugtype
(args
.first
)
576 self.add
("switch({args.first}->classid) \{")
577 var last
= types
.last
578 var defaultpropdef
: nullable MMethodDef = null
580 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, t
)
581 if propdef
.mclassdef
.mclass
.name
== "Object" and not t
.is_c_primitive
then
582 defaultpropdef
= propdef
585 if not self.compiler
.hardening
and t
== last
and defaultpropdef
== null then
586 self.add
("default: /* test {t} */")
588 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
590 var res2
= self.call
(propdef
, t
, args
)
591 if res
!= null then self.assign
(res
, res2
.as(not null))
594 if defaultpropdef
!= null then
595 self.add
("default: /* default is Object */")
596 var res2
= self.call
(defaultpropdef
, defaultpropdef
.mclassdef
.bound_mtype
, args
)
597 if res
!= null then self.assign
(res
, res2
.as(not null))
598 else if self.compiler
.hardening
then
599 self.add
("default: /* bug */")
600 self.bugtype
(args
.first
)
606 fun check_valid_reciever
(recvtype
: MClassType)
608 if self.compiler
.runtime_type_analysis
.live_types
.has
(recvtype
) or recvtype
.mclass
.name
== "Object" then return
609 print_error
"{recvtype} is not a live type"
613 # Subpart of old call function
615 # Checks if the type of the receiver is valid and corrects it if necessary
616 private fun get_recvtype
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): MClassType
618 check_valid_reciever
(recvtype
)
622 redef fun call
(m
, recvtype
, args
)
624 var recv_type
= get_recvtype
(m
, recvtype
, args
)
625 var recv
= self.autoadapt
(self.autobox
(args
.first
, recvtype
), recvtype
)
626 if m
.is_extern
then recv
= unbox_extern
(recv
, recv_type
)
631 assert args
.length
== m
.msignature
.arity
+ 1 else debug
("Invalid arity for {m}. {args.length} arguments given.")
633 var rm
= new CustomizedRuntimeFunction(m
, recvtype
)
634 return rm
.call
(self, args
)
637 redef fun supercall
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
639 var types
= self.collect_types
(args
.first
)
641 var res
: nullable RuntimeVariable
642 var ret
= m
.mproperty
.intro
.msignature
.return_mtype
646 ret
= self.resolve_for
(ret
, args
.first
)
647 res
= self.new_var
(ret
)
650 self.add
("/* super {m} on {args.first.inspect} */")
651 if args
.first
.mtype
.is_c_primitive
then
652 var mclasstype
= args
.first
.mtype
.as(MClassType)
653 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
654 self.add
("/* skip, no method {m} */")
657 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, mclasstype
)
658 var res2
= self.call
(propdef
, mclasstype
, args
)
659 if res
!= null then self.assign
(res
, res2
.as(not null))
663 if types
.is_empty
then
665 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
666 self.bugtype
(args
.first
)
671 self.add
("switch({args.first}->classid) \{")
672 var last
= types
.last
674 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, t
)
675 if not self.compiler
.hardening
and t
== last
then
676 self.add
("default: /* test {t} */")
678 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
680 var res2
= self.call
(propdef
, t
, args
)
681 if res
!= null then self.assign
(res
, res2
.as(not null))
684 if self.compiler
.hardening
then
685 self.add
("default: /* bug */")
686 self.bugtype
(args
.first
)
692 redef fun adapt_signature
(m
, args
)
694 var recv
= args
.first
695 for i
in [0..m
.msignature
.arity
[ do
696 var mp
= m
.msignature
.mparameters
[i
]
701 t
= self.resolve_for
(t
, recv
)
702 args
[i
+1] = self.autobox
(args
[i
+1], t
)
706 redef fun unbox_signature_extern
(m
, args
)
708 var recv
= args
.first
709 for i
in [0..m
.msignature
.arity
[ do
710 var mp
= m
.msignature
.mparameters
[i
]
715 t
= self.resolve_for
(t
, recv
)
716 if m
.is_extern
then args
[i
+1] = self.unbox_extern
(args
[i
+1], t
)
720 # FIXME: this is currently buggy since recv is not exact
721 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
723 elttype
= self.resolve_for
(elttype
, recv
)
724 return self.array_instance
(varargs
, elttype
)
727 fun bugtype
(recv
: RuntimeVariable)
729 if recv
.mtype
.is_c_primitive
then return
730 self.add
("PRINT_ERROR(\"BTD BUG: Dynamic type is %s
, static
type is %s\\n\
", class_names[{recv}->classid], \"{recv.mcasttype}\
");")
731 self.add
("fatal_exit(1);")
734 redef fun isset_attribute
(a
, recv
)
736 check_recv_notnull
(recv
)
738 var types
= self.collect_types
(recv
)
739 var res
= self.new_var
(bool_type
)
741 if types
.is_empty
then
742 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
746 self.add
("/* isset {a} on {recv.inspect} */")
747 self.add
("switch({recv}->classid) \{")
748 var last
= types
.last
750 if not self.compiler
.hardening
and t
== last
then
751 self.add
("default: /*{self.compiler.classid(t)}*/")
753 self.add
("case {self.compiler.classid(t)}:")
755 var recv2
= self.autoadapt
(recv
, t
)
756 var ta
= a
.intro
.static_mtype
.as(not null)
757 ta
= self.resolve_for
(ta
, recv2
)
758 var attr
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
759 if not ta
isa MNullableType then
760 if not ta
.is_c_primitive
then
761 self.add
("{res} = ({attr} != NULL);")
763 self.add
("{res} = 1; /*NOTYET isset on primitive attributes*/")
768 if self.compiler
.hardening
then
769 self.add
("default: /* Bug */")
777 redef fun read_attribute
(a
, recv
)
779 check_recv_notnull
(recv
)
781 var types
= self.collect_types
(recv
)
783 var ret
= a
.intro
.static_mtype
.as(not null)
784 ret
= self.resolve_for
(ret
, recv
)
785 var res
= self.new_var
(ret
)
787 if types
.is_empty
then
788 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
792 self.add
("/* read {a} on {recv.inspect} */")
793 self.add
("switch({recv}->classid) \{")
794 var last
= types
.last
796 if not self.compiler
.hardening
and t
== last
then
797 self.add
("default: /*{self.compiler.classid(t)}*/")
799 self.add
("case {self.compiler.classid(t)}:")
801 var recv2
= self.autoadapt
(recv
, t
)
802 var ta
= a
.intro
.static_mtype
.as(not null)
803 ta
= self.resolve_for
(ta
, recv2
)
804 var res2
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
805 if not ta
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_attr_isset
.value
then
806 if not ta
.is_c_primitive
then
807 self.add
("if ({res2} == NULL) \{")
808 self.add_abort
("Uninitialized attribute {a.name}")
811 self.add
("/*NOTYET isset on primitive attributes*/")
814 self.assign
(res
, res2
)
817 if self.compiler
.hardening
then
818 self.add
("default: /* Bug */")
826 redef fun write_attribute
(a
, recv
, value
)
828 check_recv_notnull
(recv
)
830 var types
= self.collect_types
(recv
)
832 if types
.is_empty
then
833 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
837 self.add
("/* write {a} on {recv.inspect} */")
838 self.add
("switch({recv}->classid) \{")
839 var last
= types
.last
841 if not self.compiler
.hardening
and t
== last
then
842 self.add
("default: /*{self.compiler.classid(t)}*/")
844 self.add
("case {self.compiler.classid(t)}:")
846 var recv2
= self.autoadapt
(recv
, t
)
847 var ta
= a
.intro
.static_mtype
.as(not null)
848 ta
= self.resolve_for
(ta
, recv2
)
849 self.add
("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
852 if self.compiler
.hardening
then
853 self.add
("default: /* Bug*/")
859 redef fun init_instance
(mtype
)
861 mtype
= self.anchor
(mtype
).as(MClassType)
862 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
863 debug
"problem: {mtype} was detected dead"
865 var res
= self.new_expr
("NEW_{mtype.c_name}()", mtype
)
870 redef fun type_test
(value
, mtype
, tag
)
872 mtype
= self.anchor
(mtype
)
873 if not self.compiler
.runtime_type_analysis
.live_cast_types
.has
(mtype
) then
874 debug
"problem: {mtype} was detected cast-dead"
878 var types
= self.collect_types
(value
)
879 var res
= self.new_var
(bool_type
)
881 self.add
("/* isa {mtype} on {value.inspect} */")
882 if value
.mtype
.is_c_primitive
then
883 if value
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
884 self.add
("{res} = 1;")
886 self.add
("{res} = 0;")
890 if value
.mcasttype
isa MNullableType or value
.mcasttype
isa MNullType then
891 self.add
("if ({value} == NULL) \{")
892 if mtype
isa MNullableType then
893 self.add
("{res} = 1; /* isa {mtype} */")
895 self.add
("{res} = 0; /* not isa {mtype} */")
899 self.add
("switch({value}->classid) \{")
901 if t
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
902 self.add
("case {self.compiler.classid(t)}: /* {t} */")
905 self.add
("{res} = 1;")
908 self.add
("{res} = 0;")
914 redef fun is_same_type_test
(value1
, value2
)
916 var res
= self.new_var
(bool_type
)
917 if not value2
.mtype
.is_c_primitive
then
918 if not value1
.mtype
.is_c_primitive
then
919 self.add
"{res} = {value1}->classid == {value2}->classid;"
921 self.add
"{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
924 if not value1
.mtype
.is_c_primitive
then
925 self.add
"{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
926 else if value1
.mcasttype
== value2
.mcasttype
then
927 self.add
"{res} = 1;"
929 self.add
"{res} = 0;"
935 redef fun class_name_string
(value
)
937 var res
= self.get_name
("var_class_name")
938 self.add_decl
("const char* {res};")
939 if not value
.mtype
.is_c_primitive
then
940 self.add
"{res} = class_names[{value}->classid];"
942 self.add
"{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
947 redef fun equal_test
(value1
, value2
)
949 var res
= self.new_var
(bool_type
)
950 if value2
.mtype
.is_c_primitive
and not value1
.mtype
.is_c_primitive
then
955 if value1
.mtype
.is_c_primitive
then
956 if value2
.mtype
== value1
.mtype
then
957 self.add
("{res} = {value1} == {value2};")
958 else if value2
.mtype
.is_c_primitive
then
959 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
961 var mtype1
= value1
.mtype
.as(MClassType)
962 self.add
("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
963 self.add
("if ({res}) \{")
964 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
968 var s
= new Array[String]
969 for t
in self.compiler
.live_primitive_types
do
970 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value1
.mcasttype
) then continue
971 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value2
.mcasttype
) then continue
972 s
.add
"({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
975 if self.compiler
.mainmodule
.model
.get_mclasses_by_name
("Pointer") != null then
976 var pointer_type
= self.compiler
.mainmodule
.pointer_type
977 if value1
.mcasttype
.is_subtype
(self.compiler
.mainmodule
, null, pointer_type
) or
978 value2
.mcasttype
.is_subtype
(self.compiler
.mainmodule
, null, pointer_type
) then
979 s
.add
"(((struct {pointer_type.c_name}*){value1})->value == ((struct {pointer_type.c_name}*){value2})->value)"
984 self.add
("{res} = {value1} == {value2};")
986 self.add
("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
992 redef fun array_instance
(array
, elttype
)
994 elttype
= self.anchor
(elttype
)
995 var arraytype
= mmodule
.array_type
(elttype
)
996 var res
= self.init_instance
(arraytype
)
997 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
998 var nat
= self.new_var
(mmodule
.native_array_type
(elttype
))
1000 self.add
("{nat} = NEW_{nat.mtype.c_name}({array.length});")
1001 for i
in [0..array
.length
[ do
1002 var r
= self.autobox
(array
[i
], elttype
)
1003 self.add
("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
1005 var length
= self.int_instance
(array
.length
)
1006 self.send
(self.get_property
("with_native", arraytype
), [res
, nat
, length
])
1012 # A runtime function customized on a specific monomorph receiver type
1013 private class CustomizedRuntimeFunction
1014 super AbstractRuntimeFunction
1016 redef type COMPILER: GlobalCompiler
1017 redef type VISITOR: GlobalCompilerVisitor
1019 # The considered reciever
1020 # (usually is a live type but no strong guarantee)
1021 var recv
: MClassType
1023 redef fun build_c_name
1025 var res
= self.c_name_cache
1026 if res
!= null then return res
1027 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
1028 res
= self.mmethoddef
.c_name
1030 res
= "{mmethoddef.c_name}__{recv.c_name}"
1032 self.c_name_cache
= res
1036 # used in the compiler worklist
1039 if not o
isa CustomizedRuntimeFunction then return false
1040 if self.mmethoddef
!= o
.mmethoddef
then return false
1041 if self.recv
!= o
.recv
then return false
1045 # used in the compiler work-list
1046 redef fun hash
do return self.mmethoddef
.hash
+ self.recv
.hash
1050 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
1051 return self.mmethoddef
.to_s
1053 return "{self.mmethoddef}@{self.recv}"
1057 redef fun recv_mtype
1062 redef var return_mtype
1064 redef fun resolve_receiver
(v
)
1066 var selfvar
= new RuntimeVariable("self", recv
, recv
)
1067 if v
.compiler
.runtime_type_analysis
.live_types
.has
(recv
) then
1068 selfvar
.is_exact
= true
1073 redef fun resolve_return_mtype
(v
)
1075 var selfvar
= v
.frame
.selfvar
1077 var ret
= msignature
.return_mtype
.as(not null)
1078 return_mtype
= v
.resolve_for
(ret
, selfvar
)
1081 redef fun resolve_ith_parameter
(v
, i
)
1083 var selfvar
= v
.frame
.selfvar
1084 var mp
= msignature
.mparameters
[i
]
1085 var mtype
= mp
.mtype
1086 if mp
.is_vararg
then
1087 mtype
= v
.mmodule
.array_type
(mtype
)
1089 mtype
= v
.resolve_for
(mtype
, selfvar
)
1090 return new RuntimeVariable("p{i}", mtype
, mtype
)
1093 redef fun declare_signature
(v
, sig
)
1095 v
.compiler
.header
.add_decl
("{sig};")
1098 redef fun end_compile_to_c
(v
)
1100 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})"
1103 redef fun call
(v
: VISITOR, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
1105 var ret
= self.mmethoddef
.msignature
.return_mtype
1107 ret
= v
.resolve_for
(ret
, arguments
.first
)
1110 # TODO: remove this guard when gcc warning issue (#2781) is resolved
1111 # WARNING: the next two lines of code is used to prevent inlining.
1112 # Inlining of a callref seems to work all the time. However,
1113 # it will produce some deadcode in certain scenarios (when using nullable type).
1119 # # ...do something with x...
1123 # var a = new A[nullable Int]
1125 # f.call(null) # Will produce a proper C callsite, but it will
1126 # # produce unreachable (dead code) for type checking
1127 # # and covariance. Thus, creating warnings when
1128 # # compiling in global. However, if you ignore
1129 # # those warnings, the binary works perfectly fine.
1131 var intromclassdef
= self.mmethoddef
.mproperty
.intro_mclassdef
1132 var is_callref
= v
.compiler
.all_routine_types_name
.has
(intromclassdef
.name
)
1134 if self.mmethoddef
.can_inline
(v
) and not is_callref
then
1135 var frame
= new StaticFrame(v
, self.mmethoddef
, self.recv
, arguments
)
1136 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1138 frame
.returnvar
= v
.new_var
(ret
)
1140 var old_frame
= v
.frame
1142 v
.add
("\{ /* Inline {self} ({arguments.join(",")}) */")
1143 self.mmethoddef
.compile_inside_to_c
(v
, arguments
)
1144 v
.add
("{frame.returnlabel.as(not null)}:(void)0;")
1147 return frame
.returnvar
1149 v
.adapt_signature
(self.mmethoddef
, arguments
)
1150 v
.compiler
.todo
(self)
1152 v
.add
("{self.c_name}({arguments.join(",")});")
1155 var res
= v
.new_var
(ret
)
1156 v
.add
("{res} = {self.c_name}({arguments.join(",")});")
1162 # Thunk implementation for global compiler.
1163 # For more detail see `abstract_compiler::ThunkFunction` documentation.
1164 class CustomizedThunkFunction
1166 super CustomizedRuntimeFunction
1170 return "THUNK_" + super
1175 return super + c_name
.hash
1178 redef fun resolve_receiver
(v
)
1181 if res
.is_exact
then res
.is_exact
= not polymorph_call_flag
1185 redef fun target_recv
1187 # If the targeted method was introduced by a primitive type,
1188 # then target_recv must be set to it. Otherwise, there will
1189 # be a missing cast. Here's an example:
1193 # fun mult_by(x:Int):Int do return x * self
1196 # var f = &10.mult_by
1198 # Here the thunk `f` must box the receiver `10` into an object.
1199 # This is due to the memory representation of a call ref which
1200 # has a pointer to an opaque type `val*`:
1203 # struct Mult_by_callref_struct {
1205 # // The receiver `10` would be here
1207 # // the targeted receiver is a `long`
1208 # long (*pointer_to_mult_by)(long, long);
1212 # Thus, every primitive type must be boxed into an `Object` when
1213 # instantiating a callref.
1215 # However, if the underlying method was introduced by a primitive
1216 # type then a cast must be invoked to convert our boxed receiver
1217 # to its original primitive type.
1218 var intro_recv
= mmethoddef
.mproperty
.intro_mclassdef
.bound_mtype
1219 if intro_recv
.is_c_primitive
then