typing&engines: accept `is_same_instance` on `null`
[nit.git] / src / compiler / global_compiler.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2012 Jean Privat <jean@pryen.org>
4 #
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
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
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.
16
17 # Global compilation of a Nit program
18 #
19 # Techniques used are:
20 # * heterogeneous generics
21 # * customization
22 # * switch dispatch
23 # * inlining
24 module global_compiler
25
26 import abstract_compiler
27 import rapid_type_analysis
28
29 redef class ToolContext
30 # option --global
31 var opt_global = new OptionBool("Use global compilation", "--global")
32
33 var global_compiler_phase = new GlobalCompilerPhase(self, null)
34
35 redef init do
36 super
37 option_context.add_option(opt_global)
38 end
39 end
40
41 class GlobalCompilerPhase
42 super Phase
43 redef fun process_mainmodule(mainmodule, given_mmodules) do
44 if not toolcontext.opt_global.value then return
45
46 var modelbuilder = toolcontext.modelbuilder
47 var analysis = modelbuilder.do_rapid_type_analysis(mainmodule)
48 modelbuilder.run_global_compiler(mainmodule, analysis)
49 end
50 end
51
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)
57 do
58 var time0 = get_time
59 self.toolcontext.info("*** GENERATING C ***", 1)
60
61 var compiler = new GlobalCompiler(mainmodule, self, runtime_type_analysis)
62 compiler.compile_header
63
64 if mainmodule.model.get_mclasses_by_name("Pointer") != null then
65 runtime_type_analysis.live_types.add(mainmodule.pointer_type)
66 end
67 for t in runtime_type_analysis.live_types do
68 compiler.declare_runtimeclass(t)
69 end
70
71 compiler.compile_class_names
72
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)
79 end
80 else
81 compiler.generate_box_instance(t)
82 end
83 end
84
85 # The main function of the C
86 compiler.compile_nitni_global_ref_functions
87 compiler.compile_main_function
88
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)
94 end
95 self.toolcontext.info("Total methods to compile to C: {compiler.seen.length}", 2)
96
97 compiler.display_stats
98
99 var time1 = get_time
100 self.toolcontext.info("*** END GENERATING C: {time1-time0} ***", 2)
101 write_and_make(compiler)
102 end
103 end
104
105 # Compiler that use global compilation and perform hard optimisations like:
106 # * customization
107 # * switch dispatch
108 # * inlining
109 class GlobalCompiler
110 super AbstractCompiler
111
112 redef type VISITOR: GlobalCompilerVisitor
113
114 # The result of the RTA (used to know live types and methods)
115 var runtime_type_analysis: RapidTypeAnalysis
116
117 init
118 do
119 var file = new_file("{mainmodule.c_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)
125 end
126 end
127 end
128
129 # Compile class names (for the class_name and output_class_name methods)
130 protected fun compile_class_names do
131 var v = new_visitor
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)} */")
136 end
137 v.add("\};")
138 end
139
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
143 do
144 if self.classids.has_key(mtype) then
145 return self.classids[mtype]
146 end
147 print "No classid for {mtype}"
148 abort
149 end
150
151 # Cache for classid
152 protected var classids: HashMap[MClassType, String] = new HashMap[MClassType, String]
153
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. */")
160 end
161
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
165
166 # Add a new todo task
167 fun todo(m: AbstractRuntimeFunction)
168 do
169 if seen.has(m) then return
170 todos.add(m)
171 seen.add(m)
172 end
173
174 # runtime_functions that need to be compiled
175 private var todos: List[AbstractRuntimeFunction] = new List[AbstractRuntimeFunction]
176
177 # runtime_functions already seen (todo or done)
178 private var seen: HashSet[AbstractRuntimeFunction] = new HashSet[AbstractRuntimeFunction]
179
180 # Declare C structures and identifiers for a runtime class
181 fun declare_runtimeclass(mtype: MClassType)
182 do
183 var v = self.header
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} */")
190
191 v.add_decl("struct {mtype.c_name} \{")
192 v.add_decl("int classid; /* must be {idname} */")
193
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];")
198 end
199
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;")
205 end
206
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} */")
215 end
216 end
217 v.add_decl("\};")
218 end
219
220 # Generate the init-instance of a live type (allocate + init-instance)
221 fun generate_init_instance(mtype: MClassType)
222 do
223 assert self.runtime_type_analysis.live_types.has(mtype)
224 assert mtype.ctype == "val*"
225 var v = self.new_visitor
226
227 var is_native_array = mtype.mclass.name == "NativeArray"
228
229 var sig
230 if is_native_array then
231 sig = "int length"
232 else
233 sig = "void"
234 end
235
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)
240 res.is_exact = true
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;")
245 else
246 v.add("{res} = nit_alloc(sizeof(struct {mtype.c_name}));")
247 end
248 v.add("{res}->classid = {self.classid(mtype)};")
249
250 self.generate_init_attr(v, res, mtype)
251 v.set_finalizer res
252 v.add("return {res};")
253 v.add("\}")
254 end
255
256 fun generate_box_instance(mtype: MClassType)
257 do
258 assert self.runtime_type_analysis.live_types.has(mtype)
259 var v = self.new_visitor
260
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;")
268 v.add("\}")
269 end
270
271 redef fun new_visitor do return new GlobalCompilerVisitor(self)
272
273 private var collect_types_cache: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
274
275 redef fun compile_nitni_structs
276 do
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 */
282 val *value;
283 \};"""
284 super
285 end
286 end
287
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
292
293 redef type COMPILER: GlobalCompiler
294
295 redef fun autobox(value, mtype)
296 do
297 if value.mtype == mtype then
298 return value
299 else if value.mtype.ctype == "val*" and mtype.ctype == "val*" then
300 return value
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);")
309 return res
310 end
311 self.add("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
312 return res
313 else if value.mtype.ctype == "void*" and mtype.ctype == "void*" then
314 return value
315 else
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);")
320 return res
321 end
322 end
323
324 redef fun unbox_extern(value, mtype)
325 do
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} */"
330 return res
331 else
332 return value
333 end
334 end
335
336 redef fun box_extern(value, mtype)
337 do
338 if not mtype isa MClassType or mtype.mclass.kind != extern_kind or
339 mtype.mclass.name == "NativeString" then return value
340
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);")
346 return res
347 end
348 self.add("{res} = BOX_{valtype.c_name}({value}); /* boxing {value.mtype} */")
349 return res
350 end
351
352 # The runtime types that are acceptable for a given receiver.
353 fun collect_types(recv: RuntimeVariable): Array[MClassType]
354 do
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)
359 var types = [mtype]
360 return types
361 end
362 var cache = self.compiler.collect_types_cache
363 if cache.has_key(mtype) then
364 return cache[mtype]
365 end
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
370 types.add(t)
371 end
372 cache[mtype] = types
373 return types
374 end
375
376 redef fun native_array_def(pname, ret_type, arguments)
377 do
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)))
382 return
383 else if pname == "[]=" then
384 self.add("{recv}[{arguments[1]}]={arguments[2]};")
385 return
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)))
388 return
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}));")
392 return
393 end
394 end
395
396 redef fun native_array_instance(elttype: MType, length: RuntimeVariable): RuntimeVariable
397 do
398 var ret_type = self.get_class("NativeArray").get_mtype([elttype])
399 ret_type = anchor(ret_type).as(MClassType)
400 return self.new_expr("NEW_{ret_type.c_name}({length})", ret_type)
401 end
402
403 redef fun calloc_array(ret_type, arguments)
404 do
405 self.ret(self.new_expr("NEW_{ret_type.c_name}({arguments[1]})", ret_type))
406 end
407
408 redef fun send(m, args)
409 do
410 var types = self.collect_types(args.first)
411
412 var res: nullable RuntimeVariable
413 var ret = m.intro.msignature.return_mtype
414 if ret == null then
415 res = null
416 else
417 ret = self.resolve_for(ret, args.first)
418 res = self.new_var(ret)
419 end
420
421 self.add("/* send {m} on {args.first.inspect} */")
422 if args.first.mtype.ctype != "val*" then
423 var mclasstype = args.first.mtype.as(MClassType)
424 if not self.compiler.runtime_type_analysis.live_types.has(mclasstype) then
425 self.add("/* skip, no method {m} */")
426 return res
427 end
428 var propdef = m.lookup_first_definition(self.compiler.mainmodule, mclasstype)
429 var res2 = self.call(propdef, mclasstype, args)
430 if res != null then self.assign(res, res2.as(not null))
431 return res
432 end
433 var consider_null = not self.compiler.modelbuilder.toolcontext.opt_no_check_null.value or m.name == "==" or m.name == "!="
434 if args.first.mcasttype isa MNullableType or args.first.mcasttype isa MNullType and consider_null then
435 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
436 self.add("if ({args.first} == NULL) \{ /* Special null case */")
437 if m.name == "==" or m.name == "is_same_instance" then
438 assert res != null
439 if args[1].mcasttype isa MNullableType then
440 self.add("{res} = ({args[1]} == NULL);")
441 else if args[1].mcasttype isa MNullType then
442 self.add("{res} = 1; /* is null */")
443 else
444 self.add("{res} = 0; /* {args[1].inspect} cannot be null */")
445 end
446 else if m.name == "!=" then
447 assert res != null
448 if args[1].mcasttype isa MNullableType then
449 self.add("{res} = ({args[1]} != NULL);")
450 else if args[1].mcasttype isa MNullType then
451 self.add("{res} = 0; /* is null */")
452 else
453 self.add("{res} = 1; /* {args[1].inspect} cannot be null */")
454 end
455 else
456 self.add_abort("Receiver is null")
457 end
458 self.add "\} else"
459 end
460 if types.is_empty then
461 self.add("\{")
462 self.add("/*BUG: no live types for {args.first.inspect} . {m}*/")
463 self.bugtype(args.first)
464 self.add("\}")
465 return res
466 end
467
468 self.add("switch({args.first}->classid) \{")
469 var last = types.last
470 var defaultpropdef: nullable MMethodDef = null
471 for t in types do
472 var propdef = m.lookup_first_definition(self.compiler.mainmodule, t)
473 if propdef.mclassdef.mclass.name == "Object" and t.ctype == "val*" then
474 defaultpropdef = propdef
475 continue
476 end
477 if not self.compiler.hardening and t == last and defaultpropdef == null then
478 self.add("default: /* test {t} */")
479 else
480 self.add("case {self.compiler.classid(t)}: /* test {t} */")
481 end
482 var res2 = self.call(propdef, t, args)
483 if res != null then self.assign(res, res2.as(not null))
484 self.add "break;"
485 end
486 if defaultpropdef != null then
487 self.add("default: /* default is Object */")
488 var res2 = self.call(defaultpropdef, defaultpropdef.mclassdef.bound_mtype, args)
489 if res != null then self.assign(res, res2.as(not null))
490 else if self.compiler.hardening then
491 self.add("default: /* bug */")
492 self.bugtype(args.first)
493 end
494 self.add("\}")
495 return res
496 end
497
498 fun check_valid_reciever(recvtype: MClassType)
499 do
500 if self.compiler.runtime_type_analysis.live_types.has(recvtype) or recvtype.mclass.name == "Object" then return
501 print "{recvtype} is not a live type"
502 abort
503 end
504
505 # Subpart of old call function
506 #
507 # Checks if the type of the receiver is valid and corrects it if necessary
508 private fun get_recvtype(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): MClassType
509 do
510 check_valid_reciever(recvtype)
511 #debug("call {m} on {recvtype} on {args.first}:{args.first.mtype}")
512 if m.mproperty.is_toplevel then
513 # Do not customize top-level methods
514 recvtype = m.mclassdef.bound_mtype
515 end
516 return recvtype
517 end
518
519 redef fun call(m, recvtype, args)
520 do
521 var recv_type = get_recvtype(m, recvtype, args)
522 var recv = self.autoadapt(self.autobox(args.first, recvtype), recvtype)
523 if m.is_extern then recv = unbox_extern(recv, recv_type)
524
525 args = args.to_a
526 args.first = recv
527
528 assert args.length == m.msignature.arity + 1 else debug("Invalid arity for {m}. {args.length} arguments given.")
529
530 var rm = new CustomizedRuntimeFunction(m, recvtype)
531 return rm.call(self, args)
532 end
533
534 redef fun supercall(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): nullable RuntimeVariable
535 do
536 var types = self.collect_types(args.first)
537
538 var res: nullable RuntimeVariable
539 var ret = m.mproperty.intro.msignature.return_mtype
540 if ret == null then
541 res = null
542 else
543 ret = self.resolve_for(ret, args.first)
544 res = self.new_var(ret)
545 end
546
547 self.add("/* super {m} on {args.first.inspect} */")
548 if args.first.mtype.ctype != "val*" then
549 var mclasstype = args.first.mtype.as(MClassType)
550 if not self.compiler.runtime_type_analysis.live_types.has(mclasstype) then
551 self.add("/* skip, no method {m} */")
552 return res
553 end
554 var propdef = m.lookup_next_definition(self.compiler.mainmodule, mclasstype)
555 var res2 = self.call(propdef, mclasstype, args)
556 if res != null then self.assign(res, res2.as(not null))
557 return res
558 end
559
560 if types.is_empty then
561 self.add("\{")
562 self.add("/*BUG: no live types for {args.first.inspect} . {m}*/")
563 self.bugtype(args.first)
564 self.add("\}")
565 return res
566 end
567
568 self.add("switch({args.first}->classid) \{")
569 var last = types.last
570 for t in types do
571 var propdef = m.lookup_next_definition(self.compiler.mainmodule, t)
572 if not self.compiler.hardening and t == last then
573 self.add("default: /* test {t} */")
574 else
575 self.add("case {self.compiler.classid(t)}: /* test {t} */")
576 end
577 var res2 = self.call(propdef, t, args)
578 if res != null then self.assign(res, res2.as(not null))
579 self.add "break;"
580 end
581 if self.compiler.hardening then
582 self.add("default: /* bug */")
583 self.bugtype(args.first)
584 end
585 self.add("\}")
586 return res
587 end
588
589 redef fun adapt_signature(m, args)
590 do
591 var recv = args.first
592 for i in [0..m.msignature.arity[ do
593 var t = m.msignature.mparameters[i].mtype
594 if i == m.msignature.vararg_rank then
595 t = args[i+1].mtype
596 end
597 t = self.resolve_for(t, recv)
598 args[i+1] = self.autobox(args[i+1], t)
599 end
600 end
601
602 redef fun unbox_signature_extern(m, args)
603 do
604 var recv = args.first
605 for i in [0..m.msignature.arity[ do
606 var t = m.msignature.mparameters[i].mtype
607 if i == m.msignature.vararg_rank then
608 t = args[i+1].mtype
609 end
610 t = self.resolve_for(t, recv)
611 if m.is_extern then args[i+1] = self.unbox_extern(args[i+1], t)
612 end
613 end
614
615 # FIXME: this is currently buggy since recv is not exact
616 redef fun vararg_instance(mpropdef, recv, varargs, elttype)
617 do
618 elttype = self.resolve_for(elttype, recv)
619 return self.array_instance(varargs, elttype)
620 end
621
622 fun bugtype(recv: RuntimeVariable)
623 do
624 if recv.mtype.ctype != "val*" then return
625 self.add("PRINT_ERROR(\"BTD BUG: Dynamic type is %s, static type is %s\\n\", class_names[{recv}->classid], \"{recv.mcasttype}\");")
626 self.add("show_backtrace(1);")
627 end
628
629 redef fun isset_attribute(a, recv)
630 do
631 check_recv_notnull(recv)
632
633 var types = self.collect_types(recv)
634 var res = self.new_var(bool_type)
635
636 if types.is_empty then
637 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
638 self.bugtype(recv)
639 return res
640 end
641 self.add("/* isset {a} on {recv.inspect} */")
642 self.add("switch({recv}->classid) \{")
643 var last = types.last
644 for t in types do
645 if not self.compiler.hardening and t == last then
646 self.add("default: /*{self.compiler.classid(t)}*/")
647 else
648 self.add("case {self.compiler.classid(t)}:")
649 end
650 var recv2 = self.autoadapt(recv, t)
651 var ta = a.intro.static_mtype.as(not null)
652 ta = self.resolve_for(ta, recv2)
653 var attr = self.new_expr("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta)
654 if not ta isa MNullableType then
655 if ta.ctype == "val*" then
656 self.add("{res} = ({attr} != NULL);")
657 else
658 self.add("{res} = 1; /*NOTYET isset on primitive attributes*/")
659 end
660 end
661 self.add("break;")
662 end
663 if self.compiler.hardening then
664 self.add("default: /* Bug */")
665 self.bugtype(recv)
666 end
667 self.add("\}")
668
669 return res
670 end
671
672 redef fun read_attribute(a, recv)
673 do
674 check_recv_notnull(recv)
675
676 var types = self.collect_types(recv)
677
678 var ret = a.intro.static_mtype.as(not null)
679 ret = self.resolve_for(ret, recv)
680 var res = self.new_var(ret)
681
682 if types.is_empty then
683 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
684 self.bugtype(recv)
685 return res
686 end
687 self.add("/* read {a} on {recv.inspect} */")
688 self.add("switch({recv}->classid) \{")
689 var last = types.last
690 for t in types do
691 if not self.compiler.hardening and t == last then
692 self.add("default: /*{self.compiler.classid(t)}*/")
693 else
694 self.add("case {self.compiler.classid(t)}:")
695 end
696 var recv2 = self.autoadapt(recv, t)
697 var ta = a.intro.static_mtype.as(not null)
698 ta = self.resolve_for(ta, recv2)
699 var res2 = self.new_expr("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta)
700 if not ta isa MNullableType and not self.compiler.modelbuilder.toolcontext.opt_no_check_attr_isset.value then
701 if ta.ctype == "val*" then
702 self.add("if ({res2} == NULL) \{")
703 self.add_abort("Uninitialized attribute {a.name}")
704 self.add("\}")
705 else
706 self.add("/*NOTYET isset on primitive attributes*/")
707 end
708 end
709 self.assign(res, res2)
710 self.add("break;")
711 end
712 if self.compiler.hardening then
713 self.add("default: /* Bug */")
714 self.bugtype(recv)
715 end
716 self.add("\}")
717
718 return res
719 end
720
721 redef fun write_attribute(a, recv, value)
722 do
723 check_recv_notnull(recv)
724
725 var types = self.collect_types(recv)
726
727 if types.is_empty then
728 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
729 self.bugtype(recv)
730 return
731 end
732 self.add("/* write {a} on {recv.inspect} */")
733 self.add("switch({recv}->classid) \{")
734 var last = types.last
735 for t in types do
736 if not self.compiler.hardening and t == last then
737 self.add("default: /*{self.compiler.classid(t)}*/")
738 else
739 self.add("case {self.compiler.classid(t)}:")
740 end
741 var recv2 = self.autoadapt(recv, t)
742 var ta = a.intro.static_mtype.as(not null)
743 ta = self.resolve_for(ta, recv2)
744 self.add("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
745 self.add("break;")
746 end
747 if self.compiler.hardening then
748 self.add("default: /* Bug*/")
749 self.bugtype(recv)
750 end
751 self.add("\}")
752 end
753
754 redef fun init_instance(mtype)
755 do
756 mtype = self.anchor(mtype).as(MClassType)
757 if not self.compiler.runtime_type_analysis.live_types.has(mtype) then
758 debug "problem: {mtype} was detected dead"
759 end
760 var res = self.new_expr("NEW_{mtype.c_name}()", mtype)
761 res.is_exact = true
762 return res
763 end
764
765 redef fun type_test(value, mtype, tag)
766 do
767 mtype = self.anchor(mtype)
768 if not self.compiler.runtime_type_analysis.live_cast_types.has(mtype) then
769 debug "problem: {mtype} was detected cast-dead"
770 abort
771 end
772
773 var types = self.collect_types(value)
774 var res = self.new_var(bool_type)
775
776 self.add("/* isa {mtype} on {value.inspect} */")
777 if value.mtype.ctype != "val*" then
778 if value.mtype.is_subtype(self.compiler.mainmodule, null, mtype) then
779 self.add("{res} = 1;")
780 else
781 self.add("{res} = 0;")
782 end
783 return res
784 end
785 if value.mcasttype isa MNullableType or value.mcasttype isa MNullType then
786 self.add("if ({value} == NULL) \{")
787 if mtype isa MNullableType then
788 self.add("{res} = 1; /* isa {mtype} */")
789 else
790 self.add("{res} = 0; /* not isa {mtype} */")
791 end
792 self.add("\} else ")
793 end
794 self.add("switch({value}->classid) \{")
795 for t in types do
796 if t.is_subtype(self.compiler.mainmodule, null, mtype) then
797 self.add("case {self.compiler.classid(t)}: /* {t} */")
798 end
799 end
800 self.add("{res} = 1;")
801 self.add("break;")
802 self.add("default:")
803 self.add("{res} = 0;")
804 self.add("\}")
805
806 return res
807 end
808
809 redef fun is_same_type_test(value1, value2)
810 do
811 var res = self.new_var(bool_type)
812 if value2.mtype.ctype == "val*" then
813 if value1.mtype.ctype == "val*" then
814 self.add "{res} = {value1}->classid == {value2}->classid;"
815 else
816 self.add "{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
817 end
818 else
819 if value1.mtype.ctype == "val*" then
820 self.add "{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
821 else if value1.mcasttype == value2.mcasttype then
822 self.add "{res} = 1;"
823 else
824 self.add "{res} = 0;"
825 end
826 end
827 return res
828 end
829
830 redef fun class_name_string(value)
831 do
832 var res = self.get_name("var_class_name")
833 self.add_decl("const char* {res};")
834 if value.mtype.ctype == "val*" then
835 self.add "{res} = class_names[{value}->classid];"
836 else
837 self.add "{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
838 end
839 return res
840 end
841
842 redef fun equal_test(value1, value2)
843 do
844 var res = self.new_var(bool_type)
845 if value2.mtype.ctype != "val*" and value1.mtype.ctype == "val*" then
846 var tmp = value1
847 value1 = value2
848 value2 = tmp
849 end
850 if value1.mtype.ctype != "val*" then
851 if value2.mtype == value1.mtype then
852 self.add("{res} = {value1} == {value2};")
853 else if value2.mtype.ctype != "val*" then
854 self.add("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
855 else
856 var mtype1 = value1.mtype.as(MClassType)
857 self.add("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
858 self.add("if ({res}) \{")
859 self.add("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
860 self.add("\}")
861 end
862 else
863 var s = new Array[String]
864 for t in self.compiler.live_primitive_types do
865 if not t.is_subtype(self.compiler.mainmodule, null, value1.mcasttype) then continue
866 if not t.is_subtype(self.compiler.mainmodule, null, value2.mcasttype) then continue
867 s.add "({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
868 end
869
870 if self.compiler.mainmodule.model.get_mclasses_by_name("Pointer") != null then
871 var pointer_type = self.compiler.mainmodule.pointer_type
872 if value1.mcasttype.is_subtype(self.compiler.mainmodule, null, pointer_type) or
873 value2.mcasttype.is_subtype(self.compiler.mainmodule, null, pointer_type) then
874 s.add "(((struct {pointer_type.c_name}*){value1})->value == ((struct {pointer_type.c_name}*){value2})->value)"
875 end
876 end
877
878 if s.is_empty then
879 self.add("{res} = {value1} == {value2};")
880 else
881 self.add("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
882 end
883 end
884 return res
885 end
886
887 redef fun array_instance(array, elttype)
888 do
889 elttype = self.anchor(elttype)
890 var arraytype = self.get_class("Array").get_mtype([elttype])
891 var res = self.init_instance(arraytype)
892 self.add("\{ /* {res} = array_instance Array[{elttype}] */")
893 var nat = self.new_var(self.get_class("NativeArray").get_mtype([elttype]))
894 nat.is_exact = true
895 self.add("{nat} = NEW_{nat.mtype.c_name}({array.length});")
896 for i in [0..array.length[ do
897 var r = self.autobox(array[i], elttype)
898 self.add("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
899 end
900 var length = self.int_instance(array.length)
901 self.send(self.get_property("with_native", arraytype), [res, nat, length])
902 self.add("\}")
903 return res
904 end
905 end
906
907 # A runtime function customized on a specific monomrph receiver type
908 private class CustomizedRuntimeFunction
909 super AbstractRuntimeFunction
910
911 redef type COMPILER: GlobalCompiler
912 redef type VISITOR: GlobalCompilerVisitor
913
914 # The considered reciever
915 # (usually is a live type but no strong guarantee)
916 var recv: MClassType
917
918 redef fun build_c_name
919 do
920 var res = self.c_name_cache
921 if res != null then return res
922 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
923 res = self.mmethoddef.c_name
924 else
925 res = "{mmethoddef.c_name}__{recv.c_name}"
926 end
927 self.c_name_cache = res
928 return res
929 end
930
931 # used in the compiler worklist
932 redef fun ==(o)
933 do
934 if not o isa CustomizedRuntimeFunction then return false
935 if self.mmethoddef != o.mmethoddef then return false
936 if self.recv != o.recv then return false
937 return true
938 end
939
940 # used in the compiler work-list
941 redef fun hash do return self.mmethoddef.hash + self.recv.hash
942
943 redef fun to_s
944 do
945 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
946 return self.mmethoddef.to_s
947 else
948 return "{self.mmethoddef}@{self.recv}"
949 end
950 end
951
952 # compile the code customized for the reciever
953 redef fun compile_to_c(compiler)
954 do
955 var recv = self.recv
956 var mmethoddef = self.mmethoddef
957 if not recv.is_subtype(compiler.mainmodule, null, mmethoddef.mclassdef.bound_mtype) then
958 print("problem: why do we compile {self} for {recv}?")
959 abort
960 end
961
962 var v = compiler.new_visitor
963 var selfvar = new RuntimeVariable("self", recv, recv)
964 if compiler.runtime_type_analysis.live_types.has(recv) then
965 selfvar.is_exact = true
966 end
967 var arguments = new Array[RuntimeVariable]
968 var frame = new Frame(v, mmethoddef, recv, arguments)
969 v.frame = frame
970
971 var sig = new FlatBuffer
972 var comment = new FlatBuffer
973 var ret = mmethoddef.msignature.return_mtype
974 if ret != null then
975 ret = v.resolve_for(ret, selfvar)
976 sig.append("{ret.ctype} ")
977 else
978 sig.append("void ")
979 end
980 sig.append(self.c_name)
981 sig.append("({recv.ctype} {selfvar}")
982 comment.append("(self: {recv}")
983 arguments.add(selfvar)
984 for i in [0..mmethoddef.msignature.arity[ do
985 var mtype = mmethoddef.msignature.mparameters[i].mtype
986 if i == mmethoddef.msignature.vararg_rank then
987 mtype = v.get_class("Array").get_mtype([mtype])
988 end
989 mtype = v.resolve_for(mtype, selfvar)
990 comment.append(", {mtype}")
991 sig.append(", {mtype.ctype} p{i}")
992 var argvar = new RuntimeVariable("p{i}", mtype, mtype)
993 arguments.add(argvar)
994 end
995 sig.append(")")
996 comment.append(")")
997 if ret != null then
998 comment.append(": {ret}")
999 end
1000 compiler.header.add_decl("{sig};")
1001
1002 v.add_decl("/* method {self} for {comment} */")
1003 v.add_decl("{sig} \{")
1004 #v.add("printf(\"method {self} for {comment}\\n\");")
1005 if ret != null then
1006 frame.returnvar = v.new_var(ret)
1007 end
1008 frame.returnlabel = v.get_name("RET_LABEL")
1009
1010 mmethoddef.compile_inside_to_c(v, arguments)
1011
1012 v.add("{frame.returnlabel.as(not null)}:;")
1013 if ret != null then
1014 v.add("return {frame.returnvar.as(not null)};")
1015 end
1016 v.add("\}")
1017 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})"
1018 end
1019
1020 redef fun call(v: VISITOR, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
1021 do
1022 var ret = self.mmethoddef.msignature.return_mtype
1023 if ret != null then
1024 ret = v.resolve_for(ret, arguments.first)
1025 end
1026 if self.mmethoddef.can_inline(v) then
1027 var frame = new Frame(v, self.mmethoddef, self.recv, arguments)
1028 frame.returnlabel = v.get_name("RET_LABEL")
1029 if ret != null then
1030 frame.returnvar = v.new_var(ret)
1031 end
1032 var old_frame = v.frame
1033 v.frame = frame
1034 v.add("\{ /* Inline {self} ({arguments.join(",")}) */")
1035 self.mmethoddef.compile_inside_to_c(v, arguments)
1036 v.add("{frame.returnlabel.as(not null)}:(void)0;")
1037 v.add("\}")
1038 v.frame = old_frame
1039 return frame.returnvar
1040 end
1041 v.adapt_signature(self.mmethoddef, arguments)
1042 v.compiler.todo(self)
1043 if ret == null then
1044 v.add("{self.c_name}({arguments.join(",")});")
1045 return null
1046 else
1047 var res = v.new_var(ret)
1048 v.add("{res} = {self.c_name}({arguments.join(",")});")
1049 return res
1050 end
1051 end
1052 end