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
.ctype
!= "val*" 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 t
.ctype
== "val*" 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
"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 mtype
.ctype_extern
!= "val*" then
208 # Is the Nit type is native then the struct is a box with two fields:
209 # * the `classid` to be polymorph
210 # * the `value` that contains the native value.
211 v
.add_decl
("{mtype.ctype_extern} value;")
214 # Collect all attributes and associate them a field in the structure.
215 # Note: we do not try to optimize the order and helps CC to optimize the client code.
216 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
217 for p
in cd
.intro_mproperties
do
218 if not p
isa MAttribute then continue
219 var t
= p
.intro
.static_mtype
.as(not null)
220 t
= t
.anchor_to
(self.mainmodule
, mtype
)
221 v
.add_decl
("{t.ctype} {p.intro.c_name}; /* {p}: {t} */")
227 # Generate the init-instance of a live type (allocate + init-instance)
228 fun generate_init_instance
(mtype
: MClassType)
230 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
231 assert mtype
.ctype
== "val*"
232 var v
= self.new_visitor
234 var is_native_array
= mtype
.mclass
.name
== "NativeArray"
237 if is_native_array
then
243 self.header
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig});")
244 v
.add_decl
("/* allocate {mtype} */")
245 v
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig}) \{")
246 var res
= v
.new_var
(mtype
)
248 if is_native_array
then
249 var mtype_elt
= mtype
.arguments
.first
250 v
.add
("{res} = nit_alloc(sizeof(struct {mtype.c_name}) + length*sizeof({mtype_elt.ctype}));")
251 v
.add
("((struct {mtype.c_name}*){res})->length = length;")
253 v
.add
("{res} = nit_alloc(sizeof(struct {mtype.c_name}));")
255 v
.add
("{res}->classid = {self.classid(mtype)};")
257 self.generate_init_attr
(v
, res
, mtype
)
259 v
.add
("return {res};")
263 fun generate_box_instance
(mtype
: MClassType)
265 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
266 var v
= self.new_visitor
268 self.header
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype});")
269 v
.add_decl
("/* allocate {mtype} */")
270 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
271 v
.add
("struct {mtype.c_name}*res = nit_alloc(sizeof(struct {mtype.c_name}));")
272 v
.add
("res->classid = {self.classid(mtype)};")
273 v
.add
("res->value = value;")
274 v
.add
("return (val*)res;")
278 redef fun new_visitor
do return new GlobalCompilerVisitor(self)
280 private var collect_types_cache
: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
282 redef fun compile_nitni_structs
284 self.header
.add_decl
"""
285 struct nitni_instance \{
286 struct nitni_instance *next,
287 *prev; /* adjacent global references in global list */
288 int count; /* number of time this global reference has been marked */
295 # A visitor on the AST of property definition that generate the C code.
296 # Because of inlining, a visitor can visit more than one property.
297 class GlobalCompilerVisitor
298 super AbstractCompilerVisitor
300 redef type COMPILER: GlobalCompiler
302 redef fun autobox
(value
, mtype
)
304 if value
.mtype
== mtype
then
306 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
308 else if value
.mtype
.ctype
== "val*" then
309 return self.new_expr
("((struct {mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
310 else if mtype
.ctype
== "val*" then
311 var valtype
= value
.mtype
.as(MClassType)
312 var res
= self.new_var
(mtype
)
313 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
314 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
315 self.add
("PRINT_ERROR(\"Dead code executed
!\\n\
"); show_backtrace(1);")
318 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
320 else if value
.mtype
.ctype
== "void*" and mtype
.ctype
== "void*" then
323 # Bad things will appen!
324 var res
= self.new_var
(mtype
)
325 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
326 self.add
("PRINT_ERROR(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); show_backtrace(1);")
331 redef fun unbox_extern
(value
, mtype
)
333 if mtype
isa MClassType and mtype
.mclass
.kind
== extern_kind
and
334 mtype
.mclass
.name
!= "NativeString" then
335 var res
= self.new_var_extern
(mtype
)
336 self.add
"{res} = ((struct {mtype.c_name}*){value})->value; /* unboxing {value.mtype} */"
343 redef fun box_extern
(value
, mtype
)
345 if not mtype
isa MClassType or mtype
.mclass
.kind
!= extern_kind
or
346 mtype
.mclass
.name
== "NativeString" then return value
348 var valtype
= value
.mtype
.as(MClassType)
349 var res
= self.new_var
(mtype
)
350 if not compiler
.runtime_type_analysis
.live_types
.has
(value
.mtype
.as(MClassType)) then
351 self.add
("/*no boxing of {value.mtype}: {value.mtype} is not live! */")
352 self.add
("PRINT_ERROR(\"Dead code executed
!\\n\
"); show_backtrace(1);")
355 self.add
("{res} = BOX_{valtype.c_name}({value}); /* boxing {value.mtype} */")
359 # The runtime types that are acceptable for a given receiver.
360 fun collect_types
(recv
: RuntimeVariable): Array[MClassType]
362 var mtype
= recv
.mcasttype
363 if recv
.is_exact
then
364 assert mtype
isa MClassType
365 assert self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
)
369 var cache
= self.compiler
.collect_types_cache
370 if cache
.has_key
(mtype
) then
373 var types
= new Array[MClassType]
374 var mainmodule
= self.compiler
.mainmodule
375 for t
in self.compiler
.runtime_type_analysis
.live_types
do
376 if not t
.is_subtype
(mainmodule
, null, mtype
) then continue
383 redef fun native_array_def
(pname
, ret_type
, arguments
)
385 var elttype
= arguments
.first
.mtype
386 var recv
= "((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->values"
387 if pname
== "[]" then
388 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
390 else if pname
== "[]=" then
391 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
393 else if pname
== "length" then
394 self.ret
(self.new_expr
("((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->length", ret_type
.as(not null)))
396 else if pname
== "copy_to" then
397 var recv1
= "((struct {arguments[1].mcasttype.c_name}*){arguments[1]})->values"
398 self.add
("memmove({recv1},{recv},{arguments[2]}*sizeof({elttype.ctype}));")
403 redef fun native_array_instance
(elttype
: MType, length
: RuntimeVariable): RuntimeVariable
405 var ret_type
= self.get_class
("NativeArray").get_mtype
([elttype
])
406 ret_type
= anchor
(ret_type
).as(MClassType)
407 return self.new_expr
("NEW_{ret_type.c_name}({length})", ret_type
)
410 redef fun calloc_array
(ret_type
, arguments
)
412 self.ret
(self.new_expr
("NEW_{ret_type.c_name}({arguments[1]})", ret_type
))
415 redef fun send
(m
, args
)
417 var types
= self.collect_types
(args
.first
)
419 var res
: nullable RuntimeVariable
420 var ret
= m
.intro
.msignature
.return_mtype
424 ret
= self.resolve_for
(ret
, args
.first
)
425 res
= self.new_var
(ret
)
428 self.add
("/* send {m} on {args.first.inspect} */")
429 if args
.first
.mtype
.ctype
!= "val*" then
430 var mclasstype
= args
.first
.mtype
.as(MClassType)
431 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
432 self.add
("/* skip, no method {m} */")
435 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, mclasstype
)
436 var res2
= self.call
(propdef
, mclasstype
, args
)
437 if res
!= null then self.assign
(res
, res2
.as(not null))
440 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_null
.value
or m
.name
== "==" or m
.name
== "!="
441 if args
.first
.mcasttype
isa MNullableType or args
.first
.mcasttype
isa MNullType and consider_null
then
442 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
443 self.add
("if ({args.first} == NULL) \{ /* Special null case */")
444 if m
.name
== "==" or m
.name
== "is_same_instance" then
446 if args
[1].mcasttype
isa MNullableType then
447 self.add
("{res} = ({args[1]} == NULL);")
448 else if args
[1].mcasttype
isa MNullType then
449 self.add
("{res} = 1; /* is null */")
451 self.add
("{res} = 0; /* {args[1].inspect} cannot be null */")
453 else if m
.name
== "!=" then
455 if args
[1].mcasttype
isa MNullableType then
456 self.add
("{res} = ({args[1]} != NULL);")
457 else if args
[1].mcasttype
isa MNullType then
458 self.add
("{res} = 0; /* is null */")
460 self.add
("{res} = 1; /* {args[1].inspect} cannot be null */")
463 self.add_abort
("Receiver is null")
467 if types
.is_empty
then
469 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
470 self.bugtype
(args
.first
)
475 self.add
("switch({args.first}->classid) \{")
476 var last
= types
.last
477 var defaultpropdef
: nullable MMethodDef = null
479 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, t
)
480 if propdef
.mclassdef
.mclass
.name
== "Object" and t
.ctype
== "val*" then
481 defaultpropdef
= propdef
484 if not self.compiler
.hardening
and t
== last
and defaultpropdef
== null then
485 self.add
("default: /* test {t} */")
487 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
489 var res2
= self.call
(propdef
, t
, args
)
490 if res
!= null then self.assign
(res
, res2
.as(not null))
493 if defaultpropdef
!= null then
494 self.add
("default: /* default is Object */")
495 var res2
= self.call
(defaultpropdef
, defaultpropdef
.mclassdef
.bound_mtype
, args
)
496 if res
!= null then self.assign
(res
, res2
.as(not null))
497 else if self.compiler
.hardening
then
498 self.add
("default: /* bug */")
499 self.bugtype
(args
.first
)
505 fun check_valid_reciever
(recvtype
: MClassType)
507 if self.compiler
.runtime_type_analysis
.live_types
.has
(recvtype
) or recvtype
.mclass
.name
== "Object" then return
508 print
"{recvtype} is not a live type"
512 # Subpart of old call function
514 # Checks if the type of the receiver is valid and corrects it if necessary
515 private fun get_recvtype
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): MClassType
517 check_valid_reciever
(recvtype
)
518 #debug("call {m} on {recvtype} on {args.first}:{args.first.mtype}")
519 if m
.mproperty
.is_toplevel
then
520 # Do not customize top-level methods
521 recvtype
= m
.mclassdef
.bound_mtype
526 redef fun call
(m
, recvtype
, args
)
528 var recv_type
= get_recvtype
(m
, recvtype
, args
)
529 var recv
= self.autoadapt
(self.autobox
(args
.first
, recvtype
), recvtype
)
530 if m
.is_extern
then recv
= unbox_extern
(recv
, recv_type
)
535 assert args
.length
== m
.msignature
.arity
+ 1 else debug
("Invalid arity for {m}. {args.length} arguments given.")
537 var rm
= new CustomizedRuntimeFunction(m
, recvtype
)
538 return rm
.call
(self, args
)
541 redef fun supercall
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
543 var types
= self.collect_types
(args
.first
)
545 var res
: nullable RuntimeVariable
546 var ret
= m
.mproperty
.intro
.msignature
.return_mtype
550 ret
= self.resolve_for
(ret
, args
.first
)
551 res
= self.new_var
(ret
)
554 self.add
("/* super {m} on {args.first.inspect} */")
555 if args
.first
.mtype
.ctype
!= "val*" then
556 var mclasstype
= args
.first
.mtype
.as(MClassType)
557 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
558 self.add
("/* skip, no method {m} */")
561 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, mclasstype
)
562 var res2
= self.call
(propdef
, mclasstype
, args
)
563 if res
!= null then self.assign
(res
, res2
.as(not null))
567 if types
.is_empty
then
569 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
570 self.bugtype
(args
.first
)
575 self.add
("switch({args.first}->classid) \{")
576 var last
= types
.last
578 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, t
)
579 if not self.compiler
.hardening
and t
== last
then
580 self.add
("default: /* test {t} */")
582 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
584 var res2
= self.call
(propdef
, t
, args
)
585 if res
!= null then self.assign
(res
, res2
.as(not null))
588 if self.compiler
.hardening
then
589 self.add
("default: /* bug */")
590 self.bugtype
(args
.first
)
596 redef fun adapt_signature
(m
, args
)
598 var recv
= args
.first
599 for i
in [0..m
.msignature
.arity
[ do
600 var t
= m
.msignature
.mparameters
[i
].mtype
601 if i
== m
.msignature
.vararg_rank
then
604 t
= self.resolve_for
(t
, recv
)
605 args
[i
+1] = self.autobox
(args
[i
+1], t
)
609 redef fun unbox_signature_extern
(m
, args
)
611 var recv
= args
.first
612 for i
in [0..m
.msignature
.arity
[ do
613 var t
= m
.msignature
.mparameters
[i
].mtype
614 if i
== m
.msignature
.vararg_rank
then
617 t
= self.resolve_for
(t
, recv
)
618 if m
.is_extern
then args
[i
+1] = self.unbox_extern
(args
[i
+1], t
)
622 # FIXME: this is currently buggy since recv is not exact
623 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
625 elttype
= self.resolve_for
(elttype
, recv
)
626 return self.array_instance
(varargs
, elttype
)
629 fun bugtype
(recv
: RuntimeVariable)
631 if recv
.mtype
.ctype
!= "val*" then return
632 self.add
("PRINT_ERROR(\"BTD BUG: Dynamic type is %s
, static
type is %s\\n\
", class_names[{recv}->classid], \"{recv.mcasttype}\
");")
633 self.add
("show_backtrace(1);")
636 redef fun isset_attribute
(a
, recv
)
638 check_recv_notnull
(recv
)
640 var types
= self.collect_types
(recv
)
641 var res
= self.new_var
(bool_type
)
643 if types
.is_empty
then
644 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
648 self.add
("/* isset {a} on {recv.inspect} */")
649 self.add
("switch({recv}->classid) \{")
650 var last
= types
.last
652 if not self.compiler
.hardening
and t
== last
then
653 self.add
("default: /*{self.compiler.classid(t)}*/")
655 self.add
("case {self.compiler.classid(t)}:")
657 var recv2
= self.autoadapt
(recv
, t
)
658 var ta
= a
.intro
.static_mtype
.as(not null)
659 ta
= self.resolve_for
(ta
, recv2
)
660 var attr
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
661 if not ta
isa MNullableType then
662 if ta
.ctype
== "val*" then
663 self.add
("{res} = ({attr} != NULL);")
665 self.add
("{res} = 1; /*NOTYET isset on primitive attributes*/")
670 if self.compiler
.hardening
then
671 self.add
("default: /* Bug */")
679 redef fun read_attribute
(a
, recv
)
681 check_recv_notnull
(recv
)
683 var types
= self.collect_types
(recv
)
685 var ret
= a
.intro
.static_mtype
.as(not null)
686 ret
= self.resolve_for
(ret
, recv
)
687 var res
= self.new_var
(ret
)
689 if types
.is_empty
then
690 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
694 self.add
("/* read {a} on {recv.inspect} */")
695 self.add
("switch({recv}->classid) \{")
696 var last
= types
.last
698 if not self.compiler
.hardening
and t
== last
then
699 self.add
("default: /*{self.compiler.classid(t)}*/")
701 self.add
("case {self.compiler.classid(t)}:")
703 var recv2
= self.autoadapt
(recv
, t
)
704 var ta
= a
.intro
.static_mtype
.as(not null)
705 ta
= self.resolve_for
(ta
, recv2
)
706 var res2
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
707 if not ta
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_attr_isset
.value
then
708 if ta
.ctype
== "val*" then
709 self.add
("if ({res2} == NULL) \{")
710 self.add_abort
("Uninitialized attribute {a.name}")
713 self.add
("/*NOTYET isset on primitive attributes*/")
716 self.assign
(res
, res2
)
719 if self.compiler
.hardening
then
720 self.add
("default: /* Bug */")
728 redef fun write_attribute
(a
, recv
, value
)
730 check_recv_notnull
(recv
)
732 var types
= self.collect_types
(recv
)
734 if types
.is_empty
then
735 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
739 self.add
("/* write {a} on {recv.inspect} */")
740 self.add
("switch({recv}->classid) \{")
741 var last
= types
.last
743 if not self.compiler
.hardening
and t
== last
then
744 self.add
("default: /*{self.compiler.classid(t)}*/")
746 self.add
("case {self.compiler.classid(t)}:")
748 var recv2
= self.autoadapt
(recv
, t
)
749 var ta
= a
.intro
.static_mtype
.as(not null)
750 ta
= self.resolve_for
(ta
, recv2
)
751 self.add
("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
754 if self.compiler
.hardening
then
755 self.add
("default: /* Bug*/")
761 redef fun init_instance
(mtype
)
763 mtype
= self.anchor
(mtype
).as(MClassType)
764 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
765 debug
"problem: {mtype} was detected dead"
767 var res
= self.new_expr
("NEW_{mtype.c_name}()", mtype
)
772 redef fun type_test
(value
, mtype
, tag
)
774 mtype
= self.anchor
(mtype
)
775 if not self.compiler
.runtime_type_analysis
.live_cast_types
.has
(mtype
) then
776 debug
"problem: {mtype} was detected cast-dead"
780 var types
= self.collect_types
(value
)
781 var res
= self.new_var
(bool_type
)
783 self.add
("/* isa {mtype} on {value.inspect} */")
784 if value
.mtype
.ctype
!= "val*" then
785 if value
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
786 self.add
("{res} = 1;")
788 self.add
("{res} = 0;")
792 if value
.mcasttype
isa MNullableType or value
.mcasttype
isa MNullType then
793 self.add
("if ({value} == NULL) \{")
794 if mtype
isa MNullableType then
795 self.add
("{res} = 1; /* isa {mtype} */")
797 self.add
("{res} = 0; /* not isa {mtype} */")
801 self.add
("switch({value}->classid) \{")
803 if t
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
804 self.add
("case {self.compiler.classid(t)}: /* {t} */")
807 self.add
("{res} = 1;")
810 self.add
("{res} = 0;")
816 redef fun is_same_type_test
(value1
, value2
)
818 var res
= self.new_var
(bool_type
)
819 if value2
.mtype
.ctype
== "val*" then
820 if value1
.mtype
.ctype
== "val*" then
821 self.add
"{res} = {value1}->classid == {value2}->classid;"
823 self.add
"{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
826 if value1
.mtype
.ctype
== "val*" then
827 self.add
"{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
828 else if value1
.mcasttype
== value2
.mcasttype
then
829 self.add
"{res} = 1;"
831 self.add
"{res} = 0;"
837 redef fun class_name_string
(value
)
839 var res
= self.get_name
("var_class_name")
840 self.add_decl
("const char* {res};")
841 if value
.mtype
.ctype
== "val*" then
842 self.add
"{res} = class_names[{value}->classid];"
844 self.add
"{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
849 redef fun equal_test
(value1
, value2
)
851 var res
= self.new_var
(bool_type
)
852 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
857 if value1
.mtype
.ctype
!= "val*" then
858 if value2
.mtype
== value1
.mtype
then
859 self.add
("{res} = {value1} == {value2};")
860 else if value2
.mtype
.ctype
!= "val*" then
861 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
863 var mtype1
= value1
.mtype
.as(MClassType)
864 self.add
("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
865 self.add
("if ({res}) \{")
866 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
870 var s
= new Array[String]
871 for t
in self.compiler
.live_primitive_types
do
872 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value1
.mcasttype
) then continue
873 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value2
.mcasttype
) then continue
874 s
.add
"({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
877 if self.compiler
.mainmodule
.model
.get_mclasses_by_name
("Pointer") != null then
878 var pointer_type
= self.compiler
.mainmodule
.pointer_type
879 if value1
.mcasttype
.is_subtype
(self.compiler
.mainmodule
, null, pointer_type
) or
880 value2
.mcasttype
.is_subtype
(self.compiler
.mainmodule
, null, pointer_type
) then
881 s
.add
"(((struct {pointer_type.c_name}*){value1})->value == ((struct {pointer_type.c_name}*){value2})->value)"
886 self.add
("{res} = {value1} == {value2};")
888 self.add
("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
894 redef fun array_instance
(array
, elttype
)
896 elttype
= self.anchor
(elttype
)
897 var arraytype
= self.get_class
("Array").get_mtype
([elttype
])
898 var res
= self.init_instance
(arraytype
)
899 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
900 var nat
= self.new_var
(self.get_class
("NativeArray").get_mtype
([elttype
]))
902 self.add
("{nat} = NEW_{nat.mtype.c_name}({array.length});")
903 for i
in [0..array
.length
[ do
904 var r
= self.autobox
(array
[i
], elttype
)
905 self.add
("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
907 var length
= self.int_instance
(array
.length
)
908 self.send
(self.get_property
("with_native", arraytype
), [res
, nat
, length
])
914 # A runtime function customized on a specific monomrph receiver type
915 private class CustomizedRuntimeFunction
916 super AbstractRuntimeFunction
918 redef type COMPILER: GlobalCompiler
919 redef type VISITOR: GlobalCompilerVisitor
921 # The considered reciever
922 # (usually is a live type but no strong guarantee)
925 redef fun build_c_name
927 var res
= self.c_name_cache
928 if res
!= null then return res
929 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
930 res
= self.mmethoddef
.c_name
932 res
= "{mmethoddef.c_name}__{recv.c_name}"
934 self.c_name_cache
= res
938 # used in the compiler worklist
941 if not o
isa CustomizedRuntimeFunction then return false
942 if self.mmethoddef
!= o
.mmethoddef
then return false
943 if self.recv
!= o
.recv
then return false
947 # used in the compiler work-list
948 redef fun hash
do return self.mmethoddef
.hash
+ self.recv
.hash
952 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
953 return self.mmethoddef
.to_s
955 return "{self.mmethoddef}@{self.recv}"
959 # compile the code customized for the reciever
960 redef fun compile_to_c
(compiler
)
963 var mmethoddef
= self.mmethoddef
964 if not recv
.is_subtype
(compiler
.mainmodule
, null, mmethoddef
.mclassdef
.bound_mtype
) then
965 print
("problem: why do we compile {self} for {recv}?")
969 var v
= compiler
.new_visitor
970 var selfvar
= new RuntimeVariable("self", recv
, recv
)
971 if compiler
.runtime_type_analysis
.live_types
.has
(recv
) then
972 selfvar
.is_exact
= true
974 var arguments
= new Array[RuntimeVariable]
975 var frame
= new StaticFrame(v
, mmethoddef
, recv
, arguments
)
978 var sig
= new FlatBuffer
979 var comment
= new FlatBuffer
980 var ret
= mmethoddef
.msignature
.return_mtype
982 ret
= v
.resolve_for
(ret
, selfvar
)
983 sig
.append
("{ret.ctype} ")
987 sig
.append
(self.c_name
)
988 sig
.append
("({recv.ctype} {selfvar}")
989 comment
.append
("(self: {recv}")
990 arguments
.add
(selfvar
)
991 for i
in [0..mmethoddef
.msignature
.arity
[ do
992 var mtype
= mmethoddef
.msignature
.mparameters
[i
].mtype
993 if i
== mmethoddef
.msignature
.vararg_rank
then
994 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
996 mtype
= v
.resolve_for
(mtype
, selfvar
)
997 comment
.append
(", {mtype}")
998 sig
.append
(", {mtype.ctype} p{i}")
999 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
1000 arguments
.add
(argvar
)
1005 comment
.append
(": {ret}")
1007 compiler
.header
.add_decl
("{sig};")
1009 v
.add_decl
("/* method {self} for {comment} */")
1010 v
.add_decl
("{sig} \{")
1011 #v.add("printf(\"method {self} for {comment}\\n\");")
1013 frame
.returnvar
= v
.new_var
(ret
)
1015 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1017 mmethoddef
.compile_inside_to_c
(v
, arguments
)
1019 v
.add
("{frame.returnlabel.as(not null)}:;")
1021 v
.add
("return {frame.returnvar.as(not null)};")
1024 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})"
1027 redef fun call
(v
: VISITOR, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
1029 var ret
= self.mmethoddef
.msignature
.return_mtype
1031 ret
= v
.resolve_for
(ret
, arguments
.first
)
1033 if self.mmethoddef
.can_inline
(v
) then
1034 var frame
= new StaticFrame(v
, self.mmethoddef
, self.recv
, arguments
)
1035 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1037 frame
.returnvar
= v
.new_var
(ret
)
1039 var old_frame
= v
.frame
1041 v
.add
("\{ /* Inline {self} ({arguments.join(",")}) */")
1042 self.mmethoddef
.compile_inside_to_c
(v
, arguments
)
1043 v
.add
("{frame.returnlabel.as(not null)}:(void)0;")
1046 return frame
.returnvar
1048 v
.adapt_signature
(self.mmethoddef
, arguments
)
1049 v
.compiler
.todo
(self)
1051 v
.add
("{self.c_name}({arguments.join(",")});")
1054 var res
= v
.new_var
(ret
)
1055 v
.add
("{res} = {self.c_name}({arguments.join(",")});")