1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2012 Jean Privat <jean@pryen.org>
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 # Global compilation of a Nit program
19 # Techniques used are:
20 # * heterogeneous generics
24 module global_compiler
26 import abstract_compiler
27 import rapid_type_analysis
29 redef class ToolContext
31 var opt_global
= new OptionBool("Use global compilation", "--global")
33 var global_compiler_phase
= new GlobalCompilerPhase(self, null)
37 option_context
.add_option
(opt_global
)
41 class GlobalCompilerPhase
43 redef fun process_mainmodule
(mainmodule
, given_mmodules
) do
44 if not toolcontext
.opt_global
.value
then return
46 var modelbuilder
= toolcontext
.modelbuilder
47 var analysis
= modelbuilder
.do_rapid_type_analysis
(mainmodule
)
48 modelbuilder
.run_global_compiler
(mainmodule
, analysis
)
52 redef class ModelBuilder
53 # Entry point to performs a global compilation on the AST of a complete program.
54 # `mainmodule` is the main module of the program
55 # `runtime_type_analysis` is a already computer type analysis.
56 fun run_global_compiler
(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis)
59 self.toolcontext
.info
("*** GENERATING C ***", 1)
61 var compiler
= new GlobalCompiler(mainmodule
, self, runtime_type_analysis
)
62 compiler
.compile_header
64 if mainmodule
.model
.get_mclasses_by_name
("Pointer") != null then
65 runtime_type_analysis
.live_types
.add
(mainmodule
.pointer_type
)
67 for t
in runtime_type_analysis
.live_types
do
68 compiler
.declare_runtimeclass
(t
)
71 compiler
.compile_class_names
73 # Init instance code (allocate and init-arguments)
74 for t
in runtime_type_analysis
.live_types
do
75 if t
.ctype
== "val*" then
76 compiler
.generate_init_instance
(t
)
77 if t
.mclass
.kind
== extern_kind
then
78 compiler
.generate_box_instance
(t
)
81 compiler
.generate_box_instance
(t
)
85 # The main function of the C
86 compiler
.compile_nitni_global_ref_functions
87 compiler
.compile_main_function
89 # Compile until all runtime_functions are visited
90 while not compiler
.todos
.is_empty
do
91 var m
= compiler
.todos
.shift
92 self.toolcontext
.info
("Compile {m} ({compiler.seen.length-compiler.todos.length}/{compiler.seen.length})", 3)
93 m
.compile_to_c
(compiler
)
95 self.toolcontext
.info
("Total methods to compile to C: {compiler.seen.length}", 2)
97 compiler
.display_stats
100 self.toolcontext
.info
("*** END GENERATING C: {time1-time0} ***", 2)
101 write_and_make
(compiler
)
105 # Compiler that use global compilation and perform hard optimisations like:
110 super AbstractCompiler
112 redef type VISITOR: GlobalCompilerVisitor
114 # The result of the RTA (used to know live types and methods)
115 var runtime_type_analysis
: RapidTypeAnalysis
119 var file
= new_file
("{mainmodule.name}.nitgg")
120 self.header
= new CodeWriter(file
)
121 self.live_primitive_types
= new Array[MClassType]
122 for t
in runtime_type_analysis
.live_types
do
123 if t
.ctype
!= "val*" or t
.mclass
.name
== "Pointer" then
124 self.live_primitive_types
.add
(t
)
129 # Compile class names (for the class_name and output_class_name methods)
130 protected fun compile_class_names
do
132 self.header
.add_decl
("extern const char *class_names[];")
133 v
.add
("const char *class_names[] = \{")
134 for t
in self.runtime_type_analysis
.live_types
do
135 v
.add
("\"{t}\
", /* {self.classid(t)} */")
140 # Return the C symbol associated to a live type runtime
141 # REQUIRE: self.runtime_type_analysis.live_types.has(mtype)
142 fun classid
(mtype
: MClassType): String
144 if self.classids
.has_key
(mtype
) then
145 return self.classids
[mtype
]
147 print
"No classid for {mtype}"
152 protected var classids
: HashMap[MClassType, String] = new HashMap[MClassType, String]
154 # Declaration of structures the live Nit types
155 # Each live type is generated as an independent C `struct` type.
156 # They only share a common first field `classid` used to implement the polymorphism.
157 # Usualy, all C variables that refers to a Nit object are typed on the abstract struct `val` that contains only the `classid` field.
158 redef fun compile_header_structs
do
159 self.header
.add_decl
("typedef struct \{int classid;\} val; /* general C type representing a Nit instance. */")
162 # Subset of runtime_type_analysis.live_types that contains only primitive types
163 # Used to implement the equal test
164 var live_primitive_types
: Array[MClassType] is noinit
166 # Add a new todo task
167 fun todo
(m
: AbstractRuntimeFunction)
169 if seen
.has
(m
) then return
174 # runtime_functions that need to be compiled
175 private var todos
: List[AbstractRuntimeFunction] = new List[AbstractRuntimeFunction]
177 # runtime_functions already seen (todo or done)
178 private var seen
: HashSet[AbstractRuntimeFunction] = new HashSet[AbstractRuntimeFunction]
180 # Declare C structures and identifiers for a runtime class
181 fun declare_runtimeclass
(mtype
: MClassType)
184 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
185 v
.add_decl
("/* runtime class {mtype} */")
186 var idnum
= classids
.length
187 var idname
= "ID_" + mtype
.c_name
188 self.classids
[mtype
] = idname
189 v
.add_decl
("#define {idname} {idnum} /* {mtype} */")
191 v
.add_decl
("struct {mtype.c_name} \{")
192 v
.add_decl
("int classid; /* must be {idname} */")
194 if mtype
.mclass
.name
== "NativeArray" then
195 # NativeArrays are just a instance header followed by an array of values
196 v
.add_decl
("int length;")
197 v
.add_decl
("{mtype.arguments.first.ctype} values[1];")
200 if mtype
.ctype_extern
!= "val*" then
201 # Is the Nit type is native then the struct is a box with two fields:
202 # * the `classid` to be polymorph
203 # * the `value` that contains the native value.
204 v
.add_decl
("{mtype.ctype_extern} value;")
207 # Collect all attributes and associate them a field in the structure.
208 # Note: we do not try to optimize the order and helps CC to optimize the client code.
209 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
210 for p
in cd
.intro_mproperties
do
211 if not p
isa MAttribute then continue
212 var t
= p
.intro
.static_mtype
.as(not null)
213 t
= t
.anchor_to
(self.mainmodule
, mtype
)
214 v
.add_decl
("{t.ctype} {p.intro.c_name}; /* {p}: {t} */")
220 # Generate the init-instance of a live type (allocate + init-instance)
221 fun generate_init_instance
(mtype
: MClassType)
223 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
224 assert mtype
.ctype
== "val*"
225 var v
= self.new_visitor
227 var is_native_array
= mtype
.mclass
.name
== "NativeArray"
230 if is_native_array
then
236 self.header
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig});")
237 v
.add_decl
("/* allocate {mtype} */")
238 v
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig}) \{")
239 var res
= v
.new_var
(mtype
)
241 if is_native_array
then
242 var mtype_elt
= mtype
.arguments
.first
243 v
.add
("{res} = nit_alloc(sizeof(struct {mtype.c_name}) + length*sizeof({mtype_elt.ctype}));")
244 v
.add
("((struct {mtype.c_name}*){res})->length = length;")
246 v
.add
("{res} = nit_alloc(sizeof(struct {mtype.c_name}));")
248 v
.add
("{res}->classid = {self.classid(mtype)};")
250 self.generate_init_attr
(v
, res
, mtype
)
252 v
.add
("return {res};")
256 fun generate_box_instance
(mtype
: MClassType)
258 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
259 var v
= self.new_visitor
261 self.header
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype});")
262 v
.add_decl
("/* allocate {mtype} */")
263 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
264 v
.add
("struct {mtype.c_name}*res = nit_alloc(sizeof(struct {mtype.c_name}));")
265 v
.add
("res->classid = {self.classid(mtype)};")
266 v
.add
("res->value = value;")
267 v
.add
("return (val*)res;")
271 redef fun new_visitor
do return new GlobalCompilerVisitor(self)
273 private var collect_types_cache
: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
275 redef fun compile_nitni_structs
277 self.header
.add_decl
"""
278 struct nitni_instance \{
279 struct nitni_instance *next,
280 *prev; /* adjacent global references in global list */
281 int count; /* number of time this global reference has been marked */
288 # A visitor on the AST of property definition that generate the C code.
289 # Because of inlining, a visitor can visit more than one property.
290 class GlobalCompilerVisitor
291 super AbstractCompilerVisitor
293 redef type COMPILER: GlobalCompiler
295 redef fun autobox
(value
, mtype
)
297 if value
.mtype
== mtype
then
299 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
301 else if value
.mtype
.ctype
== "val*" then
302 return self.new_expr
("((struct {mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
303 else if mtype
.ctype
== "val*" then
304 var valtype
= value
.mtype
.as(MClassType)
305 var res
= self.new_var
(mtype
)
306 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
307 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
308 self.add
("PRINT_ERROR(\"Dead code executed
!\\n\
"); show_backtrace(1);")
311 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
313 else if value
.mtype
.ctype
== "void*" and mtype
.ctype
== "void*" then
316 # Bad things will appen!
317 var res
= self.new_var
(mtype
)
318 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
319 self.add
("PRINT_ERROR(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); show_backtrace(1);")
324 redef fun unbox_extern
(value
, mtype
)
326 if mtype
isa MClassType and mtype
.mclass
.kind
== extern_kind
and
327 mtype
.mclass
.name
!= "NativeString" then
328 var res
= self.new_var_extern
(mtype
)
329 self.add
"{res} = ((struct {mtype.c_name}*){value})->value; /* unboxing {value.mtype} */"
336 redef fun box_extern
(value
, mtype
)
338 if not mtype
isa MClassType or mtype
.mclass
.kind
!= extern_kind
or
339 mtype
.mclass
.name
== "NativeString" then return value
341 var valtype
= value
.mtype
.as(MClassType)
342 var res
= self.new_var
(mtype
)
343 if not compiler
.runtime_type_analysis
.live_types
.has
(value
.mtype
.as(MClassType)) then
344 self.add
("/*no boxing of {value.mtype}: {value.mtype} is not live! */")
345 self.add
("PRINT_ERROR(\"Dead code executed
!\\n\
"); show_backtrace(1);")
348 self.add
("{res} = BOX_{valtype.c_name}({value}); /* boxing {value.mtype} */")
352 # The runtime types that are acceptable for a given receiver.
353 fun collect_types
(recv
: RuntimeVariable): Array[MClassType]
355 var mtype
= recv
.mcasttype
356 if recv
.is_exact
then
357 assert mtype
isa MClassType
358 assert self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
)
362 var cache
= self.compiler
.collect_types_cache
363 if cache
.has_key
(mtype
) then
366 var types
= new Array[MClassType]
367 var mainmodule
= self.compiler
.mainmodule
368 for t
in self.compiler
.runtime_type_analysis
.live_types
do
369 if not t
.is_subtype
(mainmodule
, null, mtype
) then continue
376 redef fun native_array_def
(pname
, ret_type
, arguments
)
378 var elttype
= arguments
.first
.mtype
379 var recv
= "((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->values"
380 if pname
== "[]" then
381 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
383 else if pname
== "[]=" then
384 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
386 else if pname
== "length" then
387 self.ret
(self.new_expr
("((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->length", ret_type
.as(not null)))
389 else if pname
== "copy_to" then
390 var recv1
= "((struct {arguments[1].mcasttype.c_name}*){arguments[1]})->values"
391 self.add
("memmove({recv1},{recv},{arguments[2]}*sizeof({elttype.ctype}));")
396 redef fun native_array_instance
(elttype
: MType, length
: RuntimeVariable): RuntimeVariable
398 var ret_type
= self.get_class
("NativeArray").get_mtype
([elttype
])
399 return self.new_expr
("NEW_{ret_type.c_name}({length})", ret_type
)
402 redef fun calloc_array
(ret_type
, arguments
)
404 self.ret
(self.new_expr
("NEW_{ret_type.c_name}({arguments[1]})", ret_type
))
407 redef fun send
(m
, args
)
409 var types
= self.collect_types
(args
.first
)
411 var res
: nullable RuntimeVariable
412 var ret
= m
.intro
.msignature
.return_mtype
416 ret
= self.resolve_for
(ret
, args
.first
)
417 res
= self.new_var
(ret
)
420 self.add
("/* send {m} on {args.first.inspect} */")
421 if args
.first
.mtype
.ctype
!= "val*" then
422 var mclasstype
= args
.first
.mtype
.as(MClassType)
423 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
424 self.add
("/* skip, no method {m} */")
427 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, mclasstype
)
428 var res2
= self.call
(propdef
, mclasstype
, args
)
429 if res
!= null then self.assign
(res
, res2
.as(not null))
432 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_null
.value
or m
.name
== "==" or m
.name
== "!="
433 if args
.first
.mcasttype
isa MNullableType or args
.first
.mcasttype
isa MNullType and consider_null
then
434 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
435 self.add
("if ({args.first} == NULL) \{ /* Special null case */")
436 if m
.name
== "==" then
438 if args
[1].mcasttype
isa MNullableType then
439 self.add
("{res} = ({args[1]} == NULL);")
440 else if args
[1].mcasttype
isa MNullType then
441 self.add
("{res} = 1; /* is null */")
443 self.add
("{res} = 0; /* {args[1].inspect} cannot be null */")
445 else if m
.name
== "!=" then
447 if args
[1].mcasttype
isa MNullableType then
448 self.add
("{res} = ({args[1]} != NULL);")
449 else if args
[1].mcasttype
isa MNullType then
450 self.add
("{res} = 0; /* is null */")
452 self.add
("{res} = 1; /* {args[1].inspect} cannot be null */")
455 self.add_abort
("Receiver is null")
459 if types
.is_empty
then
461 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
462 self.bugtype
(args
.first
)
467 self.add
("switch({args.first}->classid) \{")
468 var last
= types
.last
469 var defaultpropdef
: nullable MMethodDef = null
471 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, t
)
472 if propdef
.mclassdef
.mclass
.name
== "Object" and t
.ctype
== "val*" then
473 defaultpropdef
= propdef
476 if not self.compiler
.hardening
and t
== last
and defaultpropdef
== null then
477 self.add
("default: /* test {t} */")
479 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
481 var res2
= self.call
(propdef
, t
, args
)
482 if res
!= null then self.assign
(res
, res2
.as(not null))
485 if defaultpropdef
!= null then
486 self.add
("default: /* default is Object */")
487 var res2
= self.call
(defaultpropdef
, defaultpropdef
.mclassdef
.bound_mtype
, args
)
488 if res
!= null then self.assign
(res
, res2
.as(not null))
489 else if self.compiler
.hardening
then
490 self.add
("default: /* bug */")
491 self.bugtype
(args
.first
)
497 fun check_valid_reciever
(recvtype
: MClassType)
499 if self.compiler
.runtime_type_analysis
.live_types
.has
(recvtype
) or recvtype
.mclass
.name
== "Object" then return
500 print
"{recvtype} is not a live type"
504 # Subpart of old call function
506 # Checks if the type of the receiver is valid and corrects it if necessary
507 private fun get_recvtype
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): MClassType
509 check_valid_reciever
(recvtype
)
510 #debug("call {m} on {recvtype} on {args.first}:{args.first.mtype}")
511 if m
.mproperty
.is_toplevel
then
512 # Do not customize top-level methods
513 recvtype
= m
.mclassdef
.bound_mtype
518 redef fun call
(m
, recvtype
, args
)
520 var recv_type
= get_recvtype
(m
, recvtype
, args
)
521 var recv
= self.autoadapt
(self.autobox
(args
.first
, recvtype
), recvtype
)
522 if m
.is_extern
then recv
= unbox_extern
(recv
, recv_type
)
527 assert args
.length
== m
.msignature
.arity
+ 1 else debug
("Invalid arity for {m}. {args.length} arguments given.")
529 var rm
= new CustomizedRuntimeFunction(m
, recvtype
)
530 return rm
.call
(self, args
)
533 redef fun supercall
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
535 var types
= self.collect_types
(args
.first
)
537 var res
: nullable RuntimeVariable
538 var ret
= m
.mproperty
.intro
.msignature
.return_mtype
542 ret
= self.resolve_for
(ret
, args
.first
)
543 res
= self.new_var
(ret
)
546 self.add
("/* super {m} on {args.first.inspect} */")
547 if args
.first
.mtype
.ctype
!= "val*" then
548 var mclasstype
= args
.first
.mtype
.as(MClassType)
549 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
550 self.add
("/* skip, no method {m} */")
553 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, mclasstype
)
554 var res2
= self.call
(propdef
, mclasstype
, args
)
555 if res
!= null then self.assign
(res
, res2
.as(not null))
559 if types
.is_empty
then
561 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
562 self.bugtype
(args
.first
)
567 self.add
("switch({args.first}->classid) \{")
568 var last
= types
.last
570 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, t
)
571 if not self.compiler
.hardening
and t
== last
then
572 self.add
("default: /* test {t} */")
574 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
576 var res2
= self.call
(propdef
, t
, args
)
577 if res
!= null then self.assign
(res
, res2
.as(not null))
580 if self.compiler
.hardening
then
581 self.add
("default: /* bug */")
582 self.bugtype
(args
.first
)
588 redef fun adapt_signature
(m
, args
)
590 var recv
= args
.first
591 for i
in [0..m
.msignature
.arity
[ do
592 var t
= m
.msignature
.mparameters
[i
].mtype
593 if i
== m
.msignature
.vararg_rank
then
596 t
= self.resolve_for
(t
, recv
)
597 args
[i
+1] = self.autobox
(args
[i
+1], t
)
601 redef fun unbox_signature_extern
(m
, args
)
603 var recv
= args
.first
604 for i
in [0..m
.msignature
.arity
[ do
605 var t
= m
.msignature
.mparameters
[i
].mtype
606 if i
== m
.msignature
.vararg_rank
then
609 t
= self.resolve_for
(t
, recv
)
610 if m
.is_extern
then args
[i
+1] = self.unbox_extern
(args
[i
+1], t
)
614 # FIXME: this is currently buggy since recv is not exact
615 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
617 elttype
= self.resolve_for
(elttype
, recv
)
618 return self.array_instance
(varargs
, elttype
)
621 fun bugtype
(recv
: RuntimeVariable)
623 if recv
.mtype
.ctype
!= "val*" then return
624 self.add
("PRINT_ERROR(\"BTD BUG: Dynamic type is %s
, static
type is %s\\n\
", class_names[{recv}->classid], \"{recv.mcasttype}\
");")
625 self.add
("show_backtrace(1);")
628 redef fun isset_attribute
(a
, recv
)
630 check_recv_notnull
(recv
)
632 var types
= self.collect_types
(recv
)
633 var res
= self.new_var
(bool_type
)
635 if types
.is_empty
then
636 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
640 self.add
("/* isset {a} on {recv.inspect} */")
641 self.add
("switch({recv}->classid) \{")
642 var last
= types
.last
644 if not self.compiler
.hardening
and t
== last
then
645 self.add
("default: /*{self.compiler.classid(t)}*/")
647 self.add
("case {self.compiler.classid(t)}:")
649 var recv2
= self.autoadapt
(recv
, t
)
650 var ta
= a
.intro
.static_mtype
.as(not null)
651 ta
= self.resolve_for
(ta
, recv2
)
652 var attr
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
653 if not ta
isa MNullableType then
654 if ta
.ctype
== "val*" then
655 self.add
("{res} = ({attr} != NULL);")
657 self.add
("{res} = 1; /*NOTYET isset on primitive attributes*/")
662 if self.compiler
.hardening
then
663 self.add
("default: /* Bug */")
671 redef fun read_attribute
(a
, recv
)
673 check_recv_notnull
(recv
)
675 var types
= self.collect_types
(recv
)
677 var ret
= a
.intro
.static_mtype
.as(not null)
678 ret
= self.resolve_for
(ret
, recv
)
679 var res
= self.new_var
(ret
)
681 if types
.is_empty
then
682 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
686 self.add
("/* read {a} on {recv.inspect} */")
687 self.add
("switch({recv}->classid) \{")
688 var last
= types
.last
690 if not self.compiler
.hardening
and t
== last
then
691 self.add
("default: /*{self.compiler.classid(t)}*/")
693 self.add
("case {self.compiler.classid(t)}:")
695 var recv2
= self.autoadapt
(recv
, t
)
696 var ta
= a
.intro
.static_mtype
.as(not null)
697 ta
= self.resolve_for
(ta
, recv2
)
698 var res2
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
699 if not ta
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_attr_isset
.value
then
700 if ta
.ctype
== "val*" then
701 self.add
("if ({res2} == NULL) \{")
702 self.add_abort
("Uninitialized attribute {a.name}")
705 self.add
("/*NOTYET isset on primitive attributes*/")
708 self.assign
(res
, res2
)
711 if self.compiler
.hardening
then
712 self.add
("default: /* Bug */")
720 redef fun write_attribute
(a
, recv
, value
)
722 check_recv_notnull
(recv
)
724 var types
= self.collect_types
(recv
)
726 if types
.is_empty
then
727 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
731 self.add
("/* write {a} on {recv.inspect} */")
732 self.add
("switch({recv}->classid) \{")
733 var last
= types
.last
735 if not self.compiler
.hardening
and t
== last
then
736 self.add
("default: /*{self.compiler.classid(t)}*/")
738 self.add
("case {self.compiler.classid(t)}:")
740 var recv2
= self.autoadapt
(recv
, t
)
741 var ta
= a
.intro
.static_mtype
.as(not null)
742 ta
= self.resolve_for
(ta
, recv2
)
743 self.add
("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
746 if self.compiler
.hardening
then
747 self.add
("default: /* Bug*/")
753 redef fun init_instance
(mtype
)
755 mtype
= self.anchor
(mtype
).as(MClassType)
756 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
757 debug
"problem: {mtype} was detected dead"
759 var res
= self.new_expr
("NEW_{mtype.c_name}()", mtype
)
764 redef fun type_test
(value
, mtype
, tag
)
766 mtype
= self.anchor
(mtype
)
767 if not self.compiler
.runtime_type_analysis
.live_cast_types
.has
(mtype
) then
768 debug
"problem: {mtype} was detected cast-dead"
772 var types
= self.collect_types
(value
)
773 var res
= self.new_var
(bool_type
)
775 self.add
("/* isa {mtype} on {value.inspect} */")
776 if value
.mtype
.ctype
!= "val*" then
777 if value
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
778 self.add
("{res} = 1;")
780 self.add
("{res} = 0;")
784 if value
.mcasttype
isa MNullableType or value
.mcasttype
isa MNullType then
785 self.add
("if ({value} == NULL) \{")
786 if mtype
isa MNullableType then
787 self.add
("{res} = 1; /* isa {mtype} */")
789 self.add
("{res} = 0; /* not isa {mtype} */")
793 self.add
("switch({value}->classid) \{")
795 if t
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
796 self.add
("case {self.compiler.classid(t)}: /* {t} */")
799 self.add
("{res} = 1;")
802 self.add
("{res} = 0;")
808 redef fun is_same_type_test
(value1
, value2
)
810 var res
= self.new_var
(bool_type
)
811 if value2
.mtype
.ctype
== "val*" then
812 if value1
.mtype
.ctype
== "val*" then
813 self.add
"{res} = {value1}->classid == {value2}->classid;"
815 self.add
"{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
818 if value1
.mtype
.ctype
== "val*" then
819 self.add
"{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
820 else if value1
.mcasttype
== value2
.mcasttype
then
821 self.add
"{res} = 1;"
823 self.add
"{res} = 0;"
829 redef fun class_name_string
(value
)
831 var res
= self.get_name
("var_class_name")
832 self.add_decl
("const char* {res};")
833 if value
.mtype
.ctype
== "val*" then
834 self.add
"{res} = class_names[{value}->classid];"
836 self.add
"{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
841 redef fun equal_test
(value1
, value2
)
843 var res
= self.new_var
(bool_type
)
844 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
849 if value1
.mtype
.ctype
!= "val*" then
850 if value2
.mtype
== value1
.mtype
then
851 self.add
("{res} = {value1} == {value2};")
852 else if value2
.mtype
.ctype
!= "val*" then
853 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
855 var mtype1
= value1
.mtype
.as(MClassType)
856 self.add
("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
857 self.add
("if ({res}) \{")
858 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
862 var s
= new Array[String]
863 for t
in self.compiler
.live_primitive_types
do
864 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value1
.mcasttype
) then continue
865 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value2
.mcasttype
) then continue
866 s
.add
"({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
869 if self.compiler
.mainmodule
.model
.get_mclasses_by_name
("Pointer") != null then
870 var pointer_type
= self.compiler
.mainmodule
.pointer_type
871 if value1
.mcasttype
.is_subtype
(self.compiler
.mainmodule
, null, pointer_type
) or
872 value2
.mcasttype
.is_subtype
(self.compiler
.mainmodule
, null, pointer_type
) then
873 s
.add
"(((struct {pointer_type.c_name}*){value1})->value == ((struct {pointer_type.c_name}*){value2})->value)"
878 self.add
("{res} = {value1} == {value2};")
880 self.add
("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
886 redef fun array_instance
(array
, elttype
)
888 elttype
= self.anchor
(elttype
)
889 var arraytype
= self.get_class
("Array").get_mtype
([elttype
])
890 var res
= self.init_instance
(arraytype
)
891 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
892 var nat
= self.new_var
(self.get_class
("NativeArray").get_mtype
([elttype
]))
894 self.add
("{nat} = NEW_{nat.mtype.c_name}({array.length});")
895 for i
in [0..array
.length
[ do
896 var r
= self.autobox
(array
[i
], elttype
)
897 self.add
("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
899 var length
= self.int_instance
(array
.length
)
900 self.send
(self.get_property
("with_native", arraytype
), [res
, nat
, length
])
906 # A runtime function customized on a specific monomrph receiver type
907 private class CustomizedRuntimeFunction
908 super AbstractRuntimeFunction
910 redef type COMPILER: GlobalCompiler
911 redef type VISITOR: GlobalCompilerVisitor
913 # The considered reciever
914 # (usually is a live type but no strong guarantee)
917 redef fun build_c_name
919 var res
= self.c_name_cache
920 if res
!= null then return res
921 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
922 res
= self.mmethoddef
.c_name
924 res
= "{mmethoddef.c_name}__{recv.c_name}"
926 self.c_name_cache
= res
930 # used in the compiler worklist
933 if not o
isa CustomizedRuntimeFunction then return false
934 if self.mmethoddef
!= o
.mmethoddef
then return false
935 if self.recv
!= o
.recv
then return false
939 # used in the compiler work-list
940 redef fun hash
do return self.mmethoddef
.hash
+ self.recv
.hash
944 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
945 return self.mmethoddef
.to_s
947 return "{self.mmethoddef}@{self.recv}"
951 # compile the code customized for the reciever
952 redef fun compile_to_c
(compiler
)
955 var mmethoddef
= self.mmethoddef
956 if not recv
.is_subtype
(compiler
.mainmodule
, null, mmethoddef
.mclassdef
.bound_mtype
) then
957 print
("problem: why do we compile {self} for {recv}?")
961 var v
= compiler
.new_visitor
962 var selfvar
= new RuntimeVariable("self", recv
, recv
)
963 if compiler
.runtime_type_analysis
.live_types
.has
(recv
) then
964 selfvar
.is_exact
= true
966 var arguments
= new Array[RuntimeVariable]
967 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
970 var sig
= new FlatBuffer
971 var comment
= new FlatBuffer
972 var ret
= mmethoddef
.msignature
.return_mtype
974 ret
= v
.resolve_for
(ret
, selfvar
)
975 sig
.append
("{ret.ctype} ")
979 sig
.append
(self.c_name
)
980 sig
.append
("({recv.ctype} {selfvar}")
981 comment
.append
("(self: {recv}")
982 arguments
.add
(selfvar
)
983 for i
in [0..mmethoddef
.msignature
.arity
[ do
984 var mtype
= mmethoddef
.msignature
.mparameters
[i
].mtype
985 if i
== mmethoddef
.msignature
.vararg_rank
then
986 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
988 mtype
= v
.resolve_for
(mtype
, selfvar
)
989 comment
.append
(", {mtype}")
990 sig
.append
(", {mtype.ctype} p{i}")
991 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
992 arguments
.add
(argvar
)
997 comment
.append
(": {ret}")
999 compiler
.header
.add_decl
("{sig};")
1001 v
.add_decl
("/* method {self} for {comment} */")
1002 v
.add_decl
("{sig} \{")
1003 #v.add("printf(\"method {self} for {comment}\\n\");")
1005 frame
.returnvar
= v
.new_var
(ret
)
1007 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1009 mmethoddef
.compile_inside_to_c
(v
, arguments
)
1011 v
.add
("{frame.returnlabel.as(not null)}:;")
1013 v
.add
("return {frame.returnvar.as(not null)};")
1016 if not self.c_name
.has_substring
("VIRTUAL", 0) then compiler
.names
[self.c_name
] = "{mmethoddef.mclassdef.mmodule.name}::{mmethoddef.mclassdef.mclass.name}::{mmethoddef.mproperty.name} ({mmethoddef.location.file.filename}:{mmethoddef.location.line_start})"
1019 redef fun call
(v
: VISITOR, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
1021 var ret
= self.mmethoddef
.msignature
.return_mtype
1023 ret
= v
.resolve_for
(ret
, arguments
.first
)
1025 if self.mmethoddef
.can_inline
(v
) then
1026 var frame
= new Frame(v
, self.mmethoddef
, self.recv
, arguments
)
1027 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1029 frame
.returnvar
= v
.new_var
(ret
)
1031 var old_frame
= v
.frame
1033 v
.add
("\{ /* Inline {self} ({arguments.join(",")}) */")
1034 self.mmethoddef
.compile_inside_to_c
(v
, arguments
)
1035 v
.add
("{frame.returnlabel.as(not null)}:(void)0;")
1038 return frame
.returnvar
1040 v
.adapt_signature
(self.mmethoddef
, arguments
)
1041 v
.compiler
.todo
(self)
1043 v
.add
("{self.c_name}({arguments.join(",")});")
1046 var res
= v
.new_var
(ret
)
1047 v
.add
("{res} = {self.c_name}({arguments.join(",")});")