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
117 init(mainmodule
: MModule, modelbuilder
: ModelBuilder, runtime_type_analysis
: RapidTypeAnalysis)
119 super(mainmodule
, modelbuilder
)
120 var file
= new_file
("{mainmodule.name}.nitgg")
121 self.header
= new CodeWriter(file
)
122 self.runtime_type_analysis
= runtime_type_analysis
123 self.live_primitive_types
= new Array[MClassType]
124 for t
in runtime_type_analysis
.live_types
do
125 if t
.ctype
!= "val*" or t
.mclass
.name
== "Pointer" then
126 self.live_primitive_types
.add
(t
)
131 # Compile class names (for the class_name and output_class_name methods)
132 protected fun compile_class_names
do
134 self.header
.add_decl
("extern const char *class_names[];")
135 v
.add
("const char *class_names[] = \{")
136 for t
in self.runtime_type_analysis
.live_types
do
137 v
.add
("\"{t}\
", /* {self.classid(t)} */")
142 # Return the C symbol associated to a live type runtime
143 # REQUIRE: self.runtime_type_analysis.live_types.has(mtype)
144 fun classid
(mtype
: MClassType): String
146 if self.classids
.has_key
(mtype
) then
147 return self.classids
[mtype
]
149 print
"No classid for {mtype}"
154 protected var classids
: HashMap[MClassType, String] = new HashMap[MClassType, String]
156 # Declaration of structures the live Nit types
157 # Each live type is generated as an independent C `struct` type.
158 # They only share a common first field `classid` used to implement the polymorphism.
159 # Usualy, all C variables that refers to a Nit object are typed on the abstract struct `val` that contains only the `classid` field.
160 redef fun compile_header_structs
do
161 self.header
.add_decl
("typedef struct \{int classid;\} val; /* general C type representing a Nit instance. */")
164 # Subset of runtime_type_analysis.live_types that contains only primitive types
165 # Used to implement the equal test
166 var live_primitive_types
: Array[MClassType]
168 # Add a new todo task
169 fun todo
(m
: AbstractRuntimeFunction)
171 if seen
.has
(m
) then return
176 # runtime_functions that need to be compiled
177 private var todos
: List[AbstractRuntimeFunction] = new List[AbstractRuntimeFunction]
179 # runtime_functions already seen (todo or done)
180 private var seen
: HashSet[AbstractRuntimeFunction] = new HashSet[AbstractRuntimeFunction]
182 # Declare C structures and identifiers for a runtime class
183 fun declare_runtimeclass
(mtype
: MClassType)
186 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
187 v
.add_decl
("/* runtime class {mtype} */")
188 var idnum
= classids
.length
189 var idname
= "ID_" + mtype
.c_name
190 self.classids
[mtype
] = idname
191 v
.add_decl
("#define {idname} {idnum} /* {mtype} */")
193 v
.add_decl
("struct {mtype.c_name} \{")
194 v
.add_decl
("int classid; /* must be {idname} */")
196 if mtype
.mclass
.name
== "NativeArray" then
197 # NativeArrays are just a instance header followed by an array of values
198 v
.add_decl
("int length;")
199 v
.add_decl
("{mtype.arguments.first.ctype} values[1];")
202 if mtype
.ctype_extern
!= "val*" then
203 # Is the Nit type is native then the struct is a box with two fields:
204 # * the `classid` to be polymorph
205 # * the `value` that contains the native value.
206 v
.add_decl
("{mtype.ctype_extern} value;")
209 # Collect all attributes and associate them a field in the structure.
210 # Note: we do not try to optimize the order and helps CC to optimize the client code.
211 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
212 for p
in cd
.intro_mproperties
do
213 if not p
isa MAttribute then continue
214 var t
= p
.intro
.static_mtype
.as(not null)
215 t
= t
.anchor_to
(self.mainmodule
, mtype
)
216 v
.add_decl
("{t.ctype} {p.intro.c_name}; /* {p}: {t} */")
222 # Generate the init-instance of a live type (allocate + init-instance)
223 fun generate_init_instance
(mtype
: MClassType)
225 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
226 assert mtype
.ctype
== "val*"
227 var v
= self.new_visitor
229 var is_native_array
= mtype
.mclass
.name
== "NativeArray"
232 if is_native_array
then
238 self.header
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig});")
239 v
.add_decl
("/* allocate {mtype} */")
240 v
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig}) \{")
241 var res
= v
.new_var
(mtype
)
243 if is_native_array
then
244 var mtype_elt
= mtype
.arguments
.first
245 v
.add
("{res} = nit_alloc(sizeof(struct {mtype.c_name}) + length*sizeof({mtype_elt.ctype}));")
246 v
.add
("((struct {mtype.c_name}*){res})->length = length;")
248 v
.add
("{res} = nit_alloc(sizeof(struct {mtype.c_name}));")
250 v
.add
("{res}->classid = {self.classid(mtype)};")
252 self.generate_init_attr
(v
, res
, mtype
)
254 v
.add
("return {res};")
258 fun generate_box_instance
(mtype
: MClassType)
260 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
261 var v
= self.new_visitor
263 self.header
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype});")
264 v
.add_decl
("/* allocate {mtype} */")
265 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
266 v
.add
("struct {mtype.c_name}*res = nit_alloc(sizeof(struct {mtype.c_name}));")
267 v
.add
("res->classid = {self.classid(mtype)};")
268 v
.add
("res->value = value;")
269 v
.add
("return (val*)res;")
273 redef fun new_visitor
do return new GlobalCompilerVisitor(self)
275 private var collect_types_cache
: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
277 redef fun compile_nitni_structs
279 self.header
.add_decl
"""
280 struct nitni_instance \{
281 struct nitni_instance *next,
282 *prev; /* adjacent global references in global list */
283 int count; /* number of time this global reference has been marked */
290 # A visitor on the AST of property definition that generate the C code.
291 # Because of inlining, a visitor can visit more than one property.
292 class GlobalCompilerVisitor
293 super AbstractCompilerVisitor
295 redef type COMPILER: GlobalCompiler
297 redef fun autobox
(value
, mtype
)
299 if value
.mtype
== mtype
then
301 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
303 else if value
.mtype
.ctype
== "val*" then
304 return self.new_expr
("((struct {mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
305 else if mtype
.ctype
== "val*" then
306 var valtype
= value
.mtype
.as(MClassType)
307 var res
= self.new_var
(mtype
)
308 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
309 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
310 self.add
("PRINT_ERROR(\"Dead code executed
!\\n\
"); show_backtrace(1);")
313 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
315 else if value
.mtype
.ctype
== "void*" and mtype
.ctype
== "void*" then
318 # Bad things will appen!
319 var res
= self.new_var
(mtype
)
320 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
321 self.add
("PRINT_ERROR(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); show_backtrace(1);")
326 redef fun unbox_extern
(value
, mtype
)
328 if mtype
isa MClassType and mtype
.mclass
.kind
== extern_kind
and
329 mtype
.mclass
.name
!= "NativeString" then
330 var res
= self.new_var_extern
(mtype
)
331 self.add
"{res} = ((struct {mtype.c_name}*){value})->value; /* unboxing {value.mtype} */"
338 redef fun box_extern
(value
, mtype
)
340 if not mtype
isa MClassType or mtype
.mclass
.kind
!= extern_kind
or
341 mtype
.mclass
.name
== "NativeString" then return value
343 var valtype
= value
.mtype
.as(MClassType)
344 var res
= self.new_var
(mtype
)
345 if compiler
.runtime_type_analysis
!= null and not compiler
.runtime_type_analysis
.live_types
.has
(value
.mtype
.as(MClassType)) then
346 self.add
("/*no boxing of {value.mtype}: {value.mtype} is not live! */")
347 self.add
("PRINT_ERROR(\"Dead code executed
!\\n\
"); show_backtrace(1);")
350 self.add
("{res} = BOX_{valtype.c_name}({value}); /* boxing {value.mtype} */")
354 # The runtime types that are acceptable for a given receiver.
355 fun collect_types
(recv
: RuntimeVariable): Array[MClassType]
357 var mtype
= recv
.mcasttype
358 if recv
.is_exact
then
359 assert mtype
isa MClassType
360 assert self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
)
364 var cache
= self.compiler
.collect_types_cache
365 if cache
.has_key
(mtype
) then
368 var types
= new Array[MClassType]
369 var mainmodule
= self.compiler
.mainmodule
370 for t
in self.compiler
.runtime_type_analysis
.live_types
do
371 if not t
.is_subtype
(mainmodule
, null, mtype
) then continue
378 redef fun native_array_def
(pname
, ret_type
, arguments
)
380 var elttype
= arguments
.first
.mtype
381 var recv
= "((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->values"
382 if pname
== "[]" then
383 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
385 else if pname
== "[]=" then
386 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
388 else if pname
== "length" then
389 self.ret
(self.new_expr
("((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->length", ret_type
.as(not null)))
391 else if pname
== "copy_to" then
392 var recv1
= "((struct {arguments[1].mcasttype.c_name}*){arguments[1]})->values"
393 self.add
("memmove({recv1},{recv},{arguments[2]}*sizeof({elttype.ctype}));")
398 redef fun native_array_instance
(elttype
: MType, length
: RuntimeVariable): RuntimeVariable
400 var ret_type
= self.get_class
("NativeArray").get_mtype
([elttype
])
401 return self.new_expr
("NEW_{ret_type.c_name}({length})", ret_type
)
404 redef fun calloc_array
(ret_type
, arguments
)
406 self.ret
(self.new_expr
("NEW_{ret_type.c_name}({arguments[1]})", ret_type
))
409 redef fun send
(m
, args
)
411 var types
= self.collect_types
(args
.first
)
413 var res
: nullable RuntimeVariable
414 var ret
= m
.intro
.msignature
.return_mtype
416 ret
= args
.first
.mtype
417 res
= self.new_var
(ret
)
418 else if ret
== null then
421 ret
= self.resolve_for
(ret
, args
.first
)
422 res
= self.new_var
(ret
)
425 self.add
("/* send {m} on {args.first.inspect} */")
426 if args
.first
.mtype
.ctype
!= "val*" then
427 var mclasstype
= args
.first
.mtype
.as(MClassType)
428 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
429 self.add
("/* skip, no method {m} */")
432 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, mclasstype
)
433 var res2
= self.call
(propdef
, mclasstype
, args
)
434 if res
!= null then self.assign
(res
, res2
.as(not null))
437 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_null
.value
or m
.name
== "==" or m
.name
== "!="
438 if args
.first
.mcasttype
isa MNullableType or args
.first
.mcasttype
isa MNullType and consider_null
then
439 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
440 self.add
("if ({args.first} == NULL) \{ /* Special null case */")
441 if m
.name
== "==" then
443 if args
[1].mcasttype
isa MNullableType then
444 self.add
("{res} = ({args[1]} == NULL);")
445 else if args
[1].mcasttype
isa MNullType then
446 self.add
("{res} = 1; /* is null */")
448 self.add
("{res} = 0; /* {args[1].inspect} cannot be null */")
450 else if m
.name
== "!=" then
452 if args
[1].mcasttype
isa MNullableType then
453 self.add
("{res} = ({args[1]} != NULL);")
454 else if args
[1].mcasttype
isa MNullType then
455 self.add
("{res} = 0; /* is null */")
457 self.add
("{res} = 1; /* {args[1].inspect} cannot be null */")
460 self.add_abort
("Receiver is null")
464 if types
.is_empty
then
466 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
467 self.bugtype
(args
.first
)
472 self.add
("switch({args.first}->classid) \{")
473 var last
= types
.last
474 var defaultpropdef
: nullable MMethodDef = null
476 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, t
)
477 if propdef
.mclassdef
.mclass
.name
== "Object" and t
.ctype
== "val*" then
478 defaultpropdef
= propdef
481 if not self.compiler
.hardening
and t
== last
and defaultpropdef
== null then
482 self.add
("default: /* test {t} */")
484 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
486 var res2
= self.call
(propdef
, t
, args
)
487 if res
!= null then self.assign
(res
, res2
.as(not null))
490 if defaultpropdef
!= null then
491 self.add
("default: /* default is Object */")
492 var res2
= self.call
(defaultpropdef
, defaultpropdef
.mclassdef
.bound_mtype
, args
)
493 if res
!= null then self.assign
(res
, res2
.as(not null))
494 else if self.compiler
.hardening
then
495 self.add
("default: /* bug */")
496 self.bugtype
(args
.first
)
502 fun check_valid_reciever
(recvtype
: MClassType)
504 if self.compiler
.runtime_type_analysis
.live_types
.has
(recvtype
) or recvtype
.mclass
.name
== "Object" then return
505 print
"{recvtype} is not a live type"
509 # Subpart of old call function
511 # Checks if the type of the receiver is valid and corrects it if necessary
512 private fun get_recvtype
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): MClassType
514 check_valid_reciever
(recvtype
)
515 #debug("call {m} on {recvtype} on {args.first}:{args.first.mtype}")
516 if m
.mproperty
.is_toplevel
then
517 # Do not customize top-level methods
518 recvtype
= m
.mclassdef
.bound_mtype
523 # Subpart of old call function
524 # Gets the receiver boxed and casted if necessary
525 private fun get_recv
(recvtype
: MClassType, args
: Array[RuntimeVariable]): RuntimeVariable
527 return self.autoadapt
(self.autobox
(args
.first
, recvtype
), recvtype
)
530 # Finalizes a call to a method ´m´ on type ´recvtype´ with arguments ´args´
531 private fun finalize_call
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
533 assert args
.length
== m
.msignature
.arity
+ 1 else debug
("Invalid arity for {m}. {args.length} arguments given.")
535 var rm
= new CustomizedRuntimeFunction(m
, recvtype
)
536 return rm
.call
(self, args
)
539 redef fun call
(m
, recvtype
, args
)
541 var recv_type
= get_recvtype
(m
, recvtype
, args
)
542 var recv
= get_recv
(recv_type
, args
)
543 if m
.is_extern
then recv
= unbox_extern
(recv
, recv_type
)
544 var new_args
= args
.to_a
545 self.varargize
(m
, m
.msignature
.as(not null), new_args
)
546 new_args
.first
= recv
547 return finalize_call
(m
, recv_type
, new_args
)
550 # Does a call without encapsulating varargs into an array
551 # Avoids multiple encapsulation when calling a super in a variadic function
552 fun call_without_varargize
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
554 var recv_type
= get_recvtype
(m
, recvtype
, args
)
555 var recv
= get_recv
(recv_type
, args
)
556 if m
.is_extern
then recv
= unbox_extern
(recv
, recv_type
)
557 var new_args
= args
.to_a
558 new_args
.first
= recv
559 return finalize_call
(m
, recv_type
, new_args
)
562 redef fun supercall
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
564 var types
= self.collect_types
(args
.first
)
566 var res
: nullable RuntimeVariable
567 var ret
= m
.mproperty
.intro
.msignature
.return_mtype
571 ret
= self.resolve_for
(ret
, args
.first
)
572 res
= self.new_var
(ret
)
575 self.add
("/* super {m} on {args.first.inspect} */")
576 if args
.first
.mtype
.ctype
!= "val*" then
577 var mclasstype
= args
.first
.mtype
.as(MClassType)
578 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
579 self.add
("/* skip, no method {m} */")
582 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, mclasstype
)
583 var res2
= self.call_without_varargize
(propdef
, mclasstype
, args
)
584 if res
!= null then self.assign
(res
, res2
.as(not null))
588 if types
.is_empty
then
590 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
591 self.bugtype
(args
.first
)
596 self.add
("switch({args.first}->classid) \{")
597 var last
= types
.last
599 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, t
)
600 if not self.compiler
.hardening
and t
== last
then
601 self.add
("default: /* test {t} */")
603 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
605 var res2
= self.call_without_varargize
(propdef
, t
, args
)
606 if res
!= null then self.assign
(res
, res2
.as(not null))
609 if self.compiler
.hardening
then
610 self.add
("default: /* bug */")
611 self.bugtype
(args
.first
)
617 redef fun adapt_signature
(m
, args
)
619 var recv
= args
.first
620 for i
in [0..m
.msignature
.arity
[ do
621 var t
= m
.msignature
.mparameters
[i
].mtype
622 if i
== m
.msignature
.vararg_rank
then
625 t
= self.resolve_for
(t
, recv
)
626 args
[i
+1] = self.autobox
(args
[i
+1], t
)
630 redef fun unbox_signature_extern
(m
, args
)
632 var recv
= args
.first
633 for i
in [0..m
.msignature
.arity
[ do
634 var t
= m
.msignature
.mparameters
[i
].mtype
635 if i
== m
.msignature
.vararg_rank
then
638 t
= self.resolve_for
(t
, recv
)
639 if m
.is_extern
then args
[i
+1] = self.unbox_extern
(args
[i
+1], t
)
643 # FIXME: this is currently buggy since recv is not exact
644 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
646 elttype
= self.resolve_for
(elttype
, recv
)
647 return self.array_instance
(varargs
, elttype
)
650 fun bugtype
(recv
: RuntimeVariable)
652 if recv
.mtype
.ctype
!= "val*" then return
653 self.add
("PRINT_ERROR(\"BTD BUG: Dynamic type is %s
, static
type is %s\\n\
", class_names[{recv}->classid], \"{recv.mcasttype}\
");")
654 self.add
("show_backtrace(1);")
657 redef fun isset_attribute
(a
, recv
)
659 check_recv_notnull
(recv
)
661 var types
= self.collect_types
(recv
)
662 var res
= self.new_var
(bool_type
)
664 if types
.is_empty
then
665 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
669 self.add
("/* isset {a} on {recv.inspect} */")
670 self.add
("switch({recv}->classid) \{")
671 var last
= types
.last
673 if not self.compiler
.hardening
and t
== last
then
674 self.add
("default: /*{self.compiler.classid(t)}*/")
676 self.add
("case {self.compiler.classid(t)}:")
678 var recv2
= self.autoadapt
(recv
, t
)
679 var ta
= a
.intro
.static_mtype
.as(not null)
680 ta
= self.resolve_for
(ta
, recv2
)
681 var attr
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
682 if not ta
isa MNullableType then
683 if ta
.ctype
== "val*" then
684 self.add
("{res} = ({attr} != NULL);")
686 self.add
("{res} = 1; /*NOTYET isset on primitive attributes*/")
691 if self.compiler
.hardening
then
692 self.add
("default: /* Bug */")
700 redef fun read_attribute
(a
, recv
)
702 check_recv_notnull
(recv
)
704 var types
= self.collect_types
(recv
)
706 var ret
= a
.intro
.static_mtype
.as(not null)
707 ret
= self.resolve_for
(ret
, recv
)
708 var res
= self.new_var
(ret
)
710 if types
.is_empty
then
711 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
715 self.add
("/* read {a} on {recv.inspect} */")
716 self.add
("switch({recv}->classid) \{")
717 var last
= types
.last
719 if not self.compiler
.hardening
and t
== last
then
720 self.add
("default: /*{self.compiler.classid(t)}*/")
722 self.add
("case {self.compiler.classid(t)}:")
724 var recv2
= self.autoadapt
(recv
, t
)
725 var ta
= a
.intro
.static_mtype
.as(not null)
726 ta
= self.resolve_for
(ta
, recv2
)
727 var res2
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
728 if not ta
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_attr_isset
.value
then
729 if ta
.ctype
== "val*" then
730 self.add
("if ({res2} == NULL) \{")
731 self.add_abort
("Uninitialized attribute {a.name}")
734 self.add
("/*NOTYET isset on primitive attributes*/")
737 self.assign
(res
, res2
)
740 if self.compiler
.hardening
then
741 self.add
("default: /* Bug */")
749 redef fun write_attribute
(a
, recv
, value
)
751 check_recv_notnull
(recv
)
753 var types
= self.collect_types
(recv
)
755 if types
.is_empty
then
756 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
760 self.add
("/* write {a} on {recv.inspect} */")
761 self.add
("switch({recv}->classid) \{")
762 var last
= types
.last
764 if not self.compiler
.hardening
and t
== last
then
765 self.add
("default: /*{self.compiler.classid(t)}*/")
767 self.add
("case {self.compiler.classid(t)}:")
769 var recv2
= self.autoadapt
(recv
, t
)
770 var ta
= a
.intro
.static_mtype
.as(not null)
771 ta
= self.resolve_for
(ta
, recv2
)
772 self.add
("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
775 if self.compiler
.hardening
then
776 self.add
("default: /* Bug*/")
782 redef fun init_instance
(mtype
)
784 mtype
= self.anchor
(mtype
).as(MClassType)
785 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
786 debug
"problem: {mtype} was detected dead"
788 var res
= self.new_expr
("NEW_{mtype.c_name}()", mtype
)
793 redef fun type_test
(value
, mtype
, tag
)
795 mtype
= self.anchor
(mtype
)
796 if not self.compiler
.runtime_type_analysis
.live_cast_types
.has
(mtype
) then
797 debug
"problem: {mtype} was detected cast-dead"
801 var types
= self.collect_types
(value
)
802 var res
= self.new_var
(bool_type
)
804 self.add
("/* isa {mtype} on {value.inspect} */")
805 if value
.mtype
.ctype
!= "val*" then
806 if value
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
807 self.add
("{res} = 1;")
809 self.add
("{res} = 0;")
813 if value
.mcasttype
isa MNullableType or value
.mcasttype
isa MNullType then
814 self.add
("if ({value} == NULL) \{")
815 if mtype
isa MNullableType then
816 self.add
("{res} = 1; /* isa {mtype} */")
818 self.add
("{res} = 0; /* not isa {mtype} */")
822 self.add
("switch({value}->classid) \{")
824 if t
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
825 self.add
("case {self.compiler.classid(t)}: /* {t} */")
828 self.add
("{res} = 1;")
831 self.add
("{res} = 0;")
837 redef fun is_same_type_test
(value1
, value2
)
839 var res
= self.new_var
(bool_type
)
840 if value2
.mtype
.ctype
== "val*" then
841 if value1
.mtype
.ctype
== "val*" then
842 self.add
"{res} = {value1}->classid == {value2}->classid;"
844 self.add
"{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
847 if value1
.mtype
.ctype
== "val*" then
848 self.add
"{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
849 else if value1
.mcasttype
== value2
.mcasttype
then
850 self.add
"{res} = 1;"
852 self.add
"{res} = 0;"
858 redef fun class_name_string
(value
)
860 var res
= self.get_name
("var_class_name")
861 self.add_decl
("const char* {res};")
862 if value
.mtype
.ctype
== "val*" then
863 self.add
"{res} = class_names[{value}->classid];"
865 self.add
"{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
870 redef fun equal_test
(value1
, value2
)
872 var res
= self.new_var
(bool_type
)
873 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
878 if value1
.mtype
.ctype
!= "val*" then
879 if value2
.mtype
== value1
.mtype
then
880 self.add
("{res} = {value1} == {value2};")
881 else if value2
.mtype
.ctype
!= "val*" then
882 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
884 var mtype1
= value1
.mtype
.as(MClassType)
885 self.add
("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
886 self.add
("if ({res}) \{")
887 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
891 var s
= new Array[String]
892 for t
in self.compiler
.live_primitive_types
do
893 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value1
.mcasttype
) then continue
894 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value2
.mcasttype
) then continue
895 s
.add
"({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
898 if self.compiler
.mainmodule
.model
.get_mclasses_by_name
("Pointer") != null then
899 var pointer_type
= self.compiler
.mainmodule
.pointer_type
900 if value1
.mcasttype
.is_subtype
(self.compiler
.mainmodule
, null, pointer_type
) or
901 value2
.mcasttype
.is_subtype
(self.compiler
.mainmodule
, null, pointer_type
) then
902 s
.add
"(((struct {pointer_type.c_name}*){value1})->value == ((struct {pointer_type.c_name}*){value2})->value)"
907 self.add
("{res} = {value1} == {value2};")
909 self.add
("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
915 redef fun array_instance
(array
, elttype
)
917 elttype
= self.anchor
(elttype
)
918 var arraytype
= self.get_class
("Array").get_mtype
([elttype
])
919 var res
= self.init_instance
(arraytype
)
920 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
921 var nat
= self.new_var
(self.get_class
("NativeArray").get_mtype
([elttype
]))
923 self.add
("{nat} = NEW_{nat.mtype.c_name}({array.length});")
924 for i
in [0..array
.length
[ do
925 var r
= self.autobox
(array
[i
], elttype
)
926 self.add
("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
928 var length
= self.int_instance
(array
.length
)
929 self.send
(self.get_property
("with_native", arraytype
), [res
, nat
, length
])
935 # A runtime function customized on a specific monomrph receiver type
936 private class CustomizedRuntimeFunction
937 super AbstractRuntimeFunction
939 redef type COMPILER: GlobalCompiler
940 redef type VISITOR: GlobalCompilerVisitor
942 # The considered reciever
943 # (usually is a live type but no strong guarantee)
946 init(mmethoddef
: MMethodDef, recv
: MClassType)
952 redef fun build_c_name
954 var res
= self.c_name_cache
955 if res
!= null then return res
956 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
957 res
= self.mmethoddef
.c_name
959 res
= "{mmethoddef.c_name}__{recv.c_name}"
961 self.c_name_cache
= res
965 # used in the compiler worklist
968 if not o
isa CustomizedRuntimeFunction then return false
969 if self.mmethoddef
!= o
.mmethoddef
then return false
970 if self.recv
!= o
.recv
then return false
974 # used in the compiler work-list
975 redef fun hash
do return self.mmethoddef
.hash
+ self.recv
.hash
979 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
980 return self.mmethoddef
.to_s
982 return "{self.mmethoddef}@{self.recv}"
986 # compile the code customized for the reciever
987 redef fun compile_to_c
(compiler
)
990 var mmethoddef
= self.mmethoddef
991 if not recv
.is_subtype
(compiler
.mainmodule
, null, mmethoddef
.mclassdef
.bound_mtype
) then
992 print
("problem: why do we compile {self} for {recv}?")
996 var v
= compiler
.new_visitor
997 var selfvar
= new RuntimeVariable("self", recv
, recv
)
998 if compiler
.runtime_type_analysis
.live_types
.has
(recv
) then
999 selfvar
.is_exact
= true
1001 var arguments
= new Array[RuntimeVariable]
1002 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
1005 var sig
= new FlatBuffer
1006 var comment
= new FlatBuffer
1007 var ret
= mmethoddef
.msignature
.return_mtype
1009 ret
= v
.resolve_for
(ret
, selfvar
)
1010 sig
.append
("{ret.ctype} ")
1011 else if mmethoddef
.mproperty
.is_new
then
1013 sig
.append
("{ret.ctype} ")
1017 sig
.append
(self.c_name
)
1018 sig
.append
("({recv.ctype} {selfvar}")
1019 comment
.append
("(self: {recv}")
1020 arguments
.add
(selfvar
)
1021 for i
in [0..mmethoddef
.msignature
.arity
[ do
1022 var mtype
= mmethoddef
.msignature
.mparameters
[i
].mtype
1023 if i
== mmethoddef
.msignature
.vararg_rank
then
1024 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
1026 mtype
= v
.resolve_for
(mtype
, selfvar
)
1027 comment
.append
(", {mtype}")
1028 sig
.append
(", {mtype.ctype} p{i}")
1029 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
1030 arguments
.add
(argvar
)
1035 comment
.append
(": {ret}")
1037 compiler
.header
.add_decl
("{sig};")
1039 v
.add_decl
("/* method {self} for {comment} */")
1040 v
.add_decl
("{sig} \{")
1041 #v.add("printf(\"method {self} for {comment}\\n\");")
1043 frame
.returnvar
= v
.new_var
(ret
)
1045 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1047 mmethoddef
.compile_inside_to_c
(v
, arguments
)
1049 v
.add
("{frame.returnlabel.as(not null)}:;")
1051 v
.add
("return {frame.returnvar.as(not null)};")
1054 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})"
1057 redef fun call
(v
: VISITOR, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
1059 var ret
= self.mmethoddef
.msignature
.return_mtype
1060 if self.mmethoddef
.mproperty
.is_new
then
1064 ret
= v
.resolve_for
(ret
, arguments
.first
)
1066 if self.mmethoddef
.can_inline
(v
) then
1067 var frame
= new Frame(v
, self.mmethoddef
, self.recv
, arguments
)
1068 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1070 frame
.returnvar
= v
.new_var
(ret
)
1072 var old_frame
= v
.frame
1074 v
.add
("\{ /* Inline {self} ({arguments.join(",")}) */")
1075 self.mmethoddef
.compile_inside_to_c
(v
, arguments
)
1076 v
.add
("{frame.returnlabel.as(not null)}:(void)0;")
1079 return frame
.returnvar
1081 v
.adapt_signature
(self.mmethoddef
, arguments
)
1082 v
.compiler
.todo
(self)
1084 v
.add
("{self.c_name}({arguments.join(",")});")
1087 var res
= v
.new_var
(ret
)
1088 v
.add
("{res} = {self.c_name}({arguments.join(",")});")