Merge branch 'master' into polymorphic_extern_classes
[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(mainmodule: MModule, modelbuilder: ModelBuilder, runtime_type_analysis: RapidTypeAnalysis)
118 do
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)
127 end
128 end
129 end
130
131 # Compile class names (for the class_name and output_class_name methods)
132 protected fun compile_class_names do
133 var v = new_visitor
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)} */")
138 end
139 v.add("\};")
140 end
141
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
145 do
146 if self.classids.has_key(mtype) then
147 return self.classids[mtype]
148 end
149 print "No classid for {mtype}"
150 abort
151 end
152
153 # Cache for classid
154 protected var classids: HashMap[MClassType, String] = new HashMap[MClassType, String]
155
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. */")
162 end
163
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]
167
168 # Add a new todo task
169 fun todo(m: AbstractRuntimeFunction)
170 do
171 if seen.has(m) then return
172 todos.add(m)
173 seen.add(m)
174 end
175
176 # runtime_functions that need to be compiled
177 private var todos: List[AbstractRuntimeFunction] = new List[AbstractRuntimeFunction]
178
179 # runtime_functions already seen (todo or done)
180 private var seen: HashSet[AbstractRuntimeFunction] = new HashSet[AbstractRuntimeFunction]
181
182 # Declare C structures and identifiers for a runtime class
183 fun declare_runtimeclass(mtype: MClassType)
184 do
185 var v = self.header
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} */")
192
193 v.add_decl("struct {mtype.c_name} \{")
194 v.add_decl("int classid; /* must be {idname} */")
195
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];")
200 end
201
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;")
207 end
208
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} */")
217 end
218 end
219 v.add_decl("\};")
220 end
221
222 # Generate the init-instance of a live type (allocate + init-instance)
223 fun generate_init_instance(mtype: MClassType)
224 do
225 assert self.runtime_type_analysis.live_types.has(mtype)
226 assert mtype.ctype == "val*"
227 var v = self.new_visitor
228
229 var is_native_array = mtype.mclass.name == "NativeArray"
230
231 var sig
232 if is_native_array then
233 sig = "int length"
234 else
235 sig = "void"
236 end
237
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)
242 res.is_exact = true
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;")
247 else
248 v.add("{res} = nit_alloc(sizeof(struct {mtype.c_name}));")
249 end
250 v.add("{res}->classid = {self.classid(mtype)};")
251
252 self.generate_init_attr(v, res, mtype)
253 v.set_finalizer res
254 v.add("return {res};")
255 v.add("\}")
256 end
257
258 fun generate_box_instance(mtype: MClassType)
259 do
260 assert self.runtime_type_analysis.live_types.has(mtype)
261 var v = self.new_visitor
262
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;")
270 v.add("\}")
271 end
272
273 redef fun new_visitor do return new GlobalCompilerVisitor(self)
274
275 private var collect_types_cache: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
276
277 redef fun compile_nitni_structs
278 do
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 */
284 val *value;
285 \};"""
286 super
287 end
288 end
289
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
294
295 redef type COMPILER: GlobalCompiler
296
297 redef fun autobox(value, mtype)
298 do
299 if value.mtype == mtype then
300 return value
301 else if value.mtype.ctype == "val*" and mtype.ctype == "val*" then
302 return value
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);")
311 return res
312 end
313 self.add("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
314 return res
315 else if value.mtype.ctype == "void*" and mtype.ctype == "void*" then
316 return value
317 else
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);")
322 return res
323 end
324 end
325
326 redef fun unbox_extern(value, mtype)
327 do
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} */"
332 return res
333 else
334 return value
335 end
336 end
337
338 redef fun box_extern(value, mtype)
339 do
340 if not mtype isa MClassType or mtype.mclass.kind != extern_kind or
341 mtype.mclass.name == "NativeString" then return value
342
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);")
348 return res
349 end
350 self.add("{res} = BOX_{valtype.c_name}({value}); /* boxing {value.mtype} */")
351 return res
352 end
353
354 # The runtime types that are acceptable for a given receiver.
355 fun collect_types(recv: RuntimeVariable): Array[MClassType]
356 do
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)
361 var types = [mtype]
362 return types
363 end
364 var cache = self.compiler.collect_types_cache
365 if cache.has_key(mtype) then
366 return cache[mtype]
367 end
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
372 types.add(t)
373 end
374 cache[mtype] = types
375 return types
376 end
377
378 redef fun native_array_def(pname, ret_type, arguments)
379 do
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)))
384 return
385 else if pname == "[]=" then
386 self.add("{recv}[{arguments[1]}]={arguments[2]};")
387 return
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)))
390 return
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}));")
394 return
395 end
396 end
397
398 redef fun native_array_instance(elttype: MType, length: RuntimeVariable): RuntimeVariable
399 do
400 var ret_type = self.get_class("NativeArray").get_mtype([elttype])
401 return self.new_expr("NEW_{ret_type.c_name}({length})", ret_type)
402 end
403
404 redef fun calloc_array(ret_type, arguments)
405 do
406 self.ret(self.new_expr("NEW_{ret_type.c_name}({arguments[1]})", ret_type))
407 end
408
409 redef fun send(m, args)
410 do
411 var types = self.collect_types(args.first)
412
413 var res: nullable RuntimeVariable
414 var ret = m.intro.msignature.return_mtype
415 if m.is_new then
416 ret = args.first.mtype
417 res = self.new_var(ret)
418 else if ret == null then
419 res = null
420 else
421 ret = self.resolve_for(ret, args.first)
422 res = self.new_var(ret)
423 end
424
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} */")
430 return res
431 end
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))
435 return res
436 end
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
442 assert res != null
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 */")
447 else
448 self.add("{res} = 0; /* {args[1].inspect} cannot be null */")
449 end
450 else if m.name == "!=" then
451 assert res != null
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 */")
456 else
457 self.add("{res} = 1; /* {args[1].inspect} cannot be null */")
458 end
459 else
460 self.add_abort("Receiver is null")
461 end
462 self.add "\} else"
463 end
464 if types.is_empty then
465 self.add("\{")
466 self.add("/*BUG: no live types for {args.first.inspect} . {m}*/")
467 self.bugtype(args.first)
468 self.add("\}")
469 return res
470 end
471
472 self.add("switch({args.first}->classid) \{")
473 var last = types.last
474 var defaultpropdef: nullable MMethodDef = null
475 for t in types do
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
479 continue
480 end
481 if not self.compiler.hardening and t == last and defaultpropdef == null then
482 self.add("default: /* test {t} */")
483 else
484 self.add("case {self.compiler.classid(t)}: /* test {t} */")
485 end
486 var res2 = self.call(propdef, t, args)
487 if res != null then self.assign(res, res2.as(not null))
488 self.add "break;"
489 end
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)
497 end
498 self.add("\}")
499 return res
500 end
501
502 fun check_valid_reciever(recvtype: MClassType)
503 do
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"
506 abort
507 end
508
509 # Subpart of old call function
510 #
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
513 do
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
519 end
520 return recvtype
521 end
522
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
526 do
527 return self.autoadapt(self.autobox(args.first, recvtype), recvtype)
528 end
529
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
532 do
533 assert args.length == m.msignature.arity + 1 else debug("Invalid arity for {m}. {args.length} arguments given.")
534
535 var rm = new CustomizedRuntimeFunction(m, recvtype)
536 return rm.call(self, args)
537 end
538
539 redef fun call(m, recvtype, args)
540 do
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)
548 end
549
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
553 do
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)
560 end
561
562 redef fun supercall(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): nullable RuntimeVariable
563 do
564 var types = self.collect_types(args.first)
565
566 var res: nullable RuntimeVariable
567 var ret = m.mproperty.intro.msignature.return_mtype
568 if ret == null then
569 res = null
570 else
571 ret = self.resolve_for(ret, args.first)
572 res = self.new_var(ret)
573 end
574
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} */")
580 return res
581 end
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))
585 return res
586 end
587
588 if types.is_empty then
589 self.add("\{")
590 self.add("/*BUG: no live types for {args.first.inspect} . {m}*/")
591 self.bugtype(args.first)
592 self.add("\}")
593 return res
594 end
595
596 self.add("switch({args.first}->classid) \{")
597 var last = types.last
598 for t in types do
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} */")
602 else
603 self.add("case {self.compiler.classid(t)}: /* test {t} */")
604 end
605 var res2 = self.call_without_varargize(propdef, t, args)
606 if res != null then self.assign(res, res2.as(not null))
607 self.add "break;"
608 end
609 if self.compiler.hardening then
610 self.add("default: /* bug */")
611 self.bugtype(args.first)
612 end
613 self.add("\}")
614 return res
615 end
616
617 redef fun adapt_signature(m, args)
618 do
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
623 t = args[i+1].mtype
624 end
625 t = self.resolve_for(t, recv)
626 args[i+1] = self.autobox(args[i+1], t)
627 end
628 end
629
630 redef fun unbox_signature_extern(m, args)
631 do
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
636 t = args[i+1].mtype
637 end
638 t = self.resolve_for(t, recv)
639 if m.is_extern then args[i+1] = self.unbox_extern(args[i+1], t)
640 end
641 end
642
643 # FIXME: this is currently buggy since recv is not exact
644 redef fun vararg_instance(mpropdef, recv, varargs, elttype)
645 do
646 elttype = self.resolve_for(elttype, recv)
647 return self.array_instance(varargs, elttype)
648 end
649
650 fun bugtype(recv: RuntimeVariable)
651 do
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);")
655 end
656
657 redef fun isset_attribute(a, recv)
658 do
659 check_recv_notnull(recv)
660
661 var types = self.collect_types(recv)
662 var res = self.new_var(bool_type)
663
664 if types.is_empty then
665 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
666 self.bugtype(recv)
667 return res
668 end
669 self.add("/* isset {a} on {recv.inspect} */")
670 self.add("switch({recv}->classid) \{")
671 var last = types.last
672 for t in types do
673 if not self.compiler.hardening and t == last then
674 self.add("default: /*{self.compiler.classid(t)}*/")
675 else
676 self.add("case {self.compiler.classid(t)}:")
677 end
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);")
685 else
686 self.add("{res} = 1; /*NOTYET isset on primitive attributes*/")
687 end
688 end
689 self.add("break;")
690 end
691 if self.compiler.hardening then
692 self.add("default: /* Bug */")
693 self.bugtype(recv)
694 end
695 self.add("\}")
696
697 return res
698 end
699
700 redef fun read_attribute(a, recv)
701 do
702 check_recv_notnull(recv)
703
704 var types = self.collect_types(recv)
705
706 var ret = a.intro.static_mtype.as(not null)
707 ret = self.resolve_for(ret, recv)
708 var res = self.new_var(ret)
709
710 if types.is_empty then
711 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
712 self.bugtype(recv)
713 return res
714 end
715 self.add("/* read {a} on {recv.inspect} */")
716 self.add("switch({recv}->classid) \{")
717 var last = types.last
718 for t in types do
719 if not self.compiler.hardening and t == last then
720 self.add("default: /*{self.compiler.classid(t)}*/")
721 else
722 self.add("case {self.compiler.classid(t)}:")
723 end
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}")
732 self.add("\}")
733 else
734 self.add("/*NOTYET isset on primitive attributes*/")
735 end
736 end
737 self.assign(res, res2)
738 self.add("break;")
739 end
740 if self.compiler.hardening then
741 self.add("default: /* Bug */")
742 self.bugtype(recv)
743 end
744 self.add("\}")
745
746 return res
747 end
748
749 redef fun write_attribute(a, recv, value)
750 do
751 check_recv_notnull(recv)
752
753 var types = self.collect_types(recv)
754
755 if types.is_empty then
756 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
757 self.bugtype(recv)
758 return
759 end
760 self.add("/* write {a} on {recv.inspect} */")
761 self.add("switch({recv}->classid) \{")
762 var last = types.last
763 for t in types do
764 if not self.compiler.hardening and t == last then
765 self.add("default: /*{self.compiler.classid(t)}*/")
766 else
767 self.add("case {self.compiler.classid(t)}:")
768 end
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)};")
773 self.add("break;")
774 end
775 if self.compiler.hardening then
776 self.add("default: /* Bug*/")
777 self.bugtype(recv)
778 end
779 self.add("\}")
780 end
781
782 redef fun init_instance(mtype)
783 do
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"
787 end
788 var res = self.new_expr("NEW_{mtype.c_name}()", mtype)
789 res.is_exact = true
790 return res
791 end
792
793 redef fun type_test(value, mtype, tag)
794 do
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"
798 abort
799 end
800
801 var types = self.collect_types(value)
802 var res = self.new_var(bool_type)
803
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;")
808 else
809 self.add("{res} = 0;")
810 end
811 return res
812 end
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} */")
817 else
818 self.add("{res} = 0; /* not isa {mtype} */")
819 end
820 self.add("\} else ")
821 end
822 self.add("switch({value}->classid) \{")
823 for t in types do
824 if t.is_subtype(self.compiler.mainmodule, null, mtype) then
825 self.add("case {self.compiler.classid(t)}: /* {t} */")
826 end
827 end
828 self.add("{res} = 1;")
829 self.add("break;")
830 self.add("default:")
831 self.add("{res} = 0;")
832 self.add("\}")
833
834 return res
835 end
836
837 redef fun is_same_type_test(value1, value2)
838 do
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;"
843 else
844 self.add "{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
845 end
846 else
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;"
851 else
852 self.add "{res} = 0;"
853 end
854 end
855 return res
856 end
857
858 redef fun class_name_string(value)
859 do
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];"
864 else
865 self.add "{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
866 end
867 return res
868 end
869
870 redef fun equal_test(value1, value2)
871 do
872 var res = self.new_var(bool_type)
873 if value2.mtype.ctype != "val*" and value1.mtype.ctype == "val*" then
874 var tmp = value1
875 value1 = value2
876 value2 = tmp
877 end
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}*/")
883 else
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});")
888 self.add("\}")
889 end
890 else
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)"
896 end
897
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)"
903 end
904 end
905
906 if s.is_empty then
907 self.add("{res} = {value1} == {value2};")
908 else
909 self.add("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
910 end
911 end
912 return res
913 end
914
915 redef fun array_instance(array, elttype)
916 do
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]))
922 nat.is_exact = true
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};")
927 end
928 var length = self.int_instance(array.length)
929 self.send(self.get_property("with_native", arraytype), [res, nat, length])
930 self.add("\}")
931 return res
932 end
933 end
934
935 # A runtime function customized on a specific monomrph receiver type
936 private class CustomizedRuntimeFunction
937 super AbstractRuntimeFunction
938
939 redef type COMPILER: GlobalCompiler
940 redef type VISITOR: GlobalCompilerVisitor
941
942 # The considered reciever
943 # (usually is a live type but no strong guarantee)
944 var recv: MClassType
945
946 init(mmethoddef: MMethodDef, recv: MClassType)
947 do
948 super(mmethoddef)
949 self.recv = recv
950 end
951
952 redef fun build_c_name
953 do
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
958 else
959 res = "{mmethoddef.c_name}__{recv.c_name}"
960 end
961 self.c_name_cache = res
962 return res
963 end
964
965 # used in the compiler worklist
966 redef fun ==(o)
967 do
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
971 return true
972 end
973
974 # used in the compiler work-list
975 redef fun hash do return self.mmethoddef.hash + self.recv.hash
976
977 redef fun to_s
978 do
979 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
980 return self.mmethoddef.to_s
981 else
982 return "{self.mmethoddef}@{self.recv}"
983 end
984 end
985
986 # compile the code customized for the reciever
987 redef fun compile_to_c(compiler)
988 do
989 var recv = self.recv
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}?")
993 abort
994 end
995
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
1000 end
1001 var arguments = new Array[RuntimeVariable]
1002 var frame = new Frame(v, mmethoddef, recv, arguments)
1003 v.frame = frame
1004
1005 var sig = new FlatBuffer
1006 var comment = new FlatBuffer
1007 var ret = mmethoddef.msignature.return_mtype
1008 if ret != null then
1009 ret = v.resolve_for(ret, selfvar)
1010 sig.append("{ret.ctype} ")
1011 else if mmethoddef.mproperty.is_new then
1012 ret = recv
1013 sig.append("{ret.ctype} ")
1014 else
1015 sig.append("void ")
1016 end
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])
1025 end
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)
1031 end
1032 sig.append(")")
1033 comment.append(")")
1034 if ret != null then
1035 comment.append(": {ret}")
1036 end
1037 compiler.header.add_decl("{sig};")
1038
1039 v.add_decl("/* method {self} for {comment} */")
1040 v.add_decl("{sig} \{")
1041 #v.add("printf(\"method {self} for {comment}\\n\");")
1042 if ret != null then
1043 frame.returnvar = v.new_var(ret)
1044 end
1045 frame.returnlabel = v.get_name("RET_LABEL")
1046
1047 mmethoddef.compile_inside_to_c(v, arguments)
1048
1049 v.add("{frame.returnlabel.as(not null)}:;")
1050 if ret != null then
1051 v.add("return {frame.returnvar.as(not null)};")
1052 end
1053 v.add("\}")
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})"
1055 end
1056
1057 redef fun call(v: VISITOR, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
1058 do
1059 var ret = self.mmethoddef.msignature.return_mtype
1060 if self.mmethoddef.mproperty.is_new then
1061 ret = recv
1062 end
1063 if ret != null then
1064 ret = v.resolve_for(ret, arguments.first)
1065 end
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")
1069 if ret != null then
1070 frame.returnvar = v.new_var(ret)
1071 end
1072 var old_frame = v.frame
1073 v.frame = 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;")
1077 v.add("\}")
1078 v.frame = old_frame
1079 return frame.returnvar
1080 end
1081 v.adapt_signature(self.mmethoddef, arguments)
1082 v.compiler.todo(self)
1083 if ret == null then
1084 v.add("{self.c_name}({arguments.join(",")});")
1085 return null
1086 else
1087 var res = v.new_var(ret)
1088 v.add("{res} = {self.c_name}({arguments.join(",")});")
1089 return res
1090 end
1091 end
1092 end