ni: adds system to manage native local references to Nit objects
[nit.git] / src / compiling / compiling_icode.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2009 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 # Generate C code from intermediate code representation
18 package compiling_icode
19
20 import icode
21 private import analysis
22 import primitive_info
23 import compiling_base
24
25 # Compiler context from ICode to C
26 class I2CCompilerVisitor
27 # Associate things
28 var _ids: HashMap[Object, String] = new HashMap[Object, String]
29 # Associate other things
30 var _ids2: HashMap[Object, String] = new HashMap[Object, String]
31
32 # Return the string associated with a register
33 fun register(e: IRegister): String
34 do
35 if e.stype isa MMTypeNone then return "NIT_NULL"
36 var ids = _ids
37 if closure and not e.is_local then ids = _ids2
38 if ids.has_key(e) then
39 return ids[e]
40 else
41 var i = e.slot_index
42 if i == null then
43 # The register is dead
44 var s = "NIT_NULL"
45 ids[e] = s
46 return s
47 else
48 var s: String
49 var strs: HashMap[Int, String]
50 if e.in_tag_slots then
51 strs = once new HashMap[Int, String]
52 if not strs.has_key(i) then strs[i] = "REGB{i}"
53 else if closure and not e.is_local then
54 strs = once new HashMap[Int, String]
55 if not strs.has_key(i) then strs[i] = "closctx->REG[{i}]"
56 else
57 strs = once new HashMap[Int, String]
58 if not strs.has_key(i) then strs[i] = "fra.me.REG[{i}]"
59 end
60 s = strs[i]
61 ids[e] = s
62 return s
63 end
64 end
65 end
66
67 # Return the strings associated with registers
68 fun registers(a: Collection[IRegister]): Array[String]
69 do
70 var r = new Array[String].with_capacity(a.length)
71 for e in a do
72 r.add(register(e))
73 end
74 return r
75 end
76
77 var _last_number: Int = 0
78 # Give a new unique number (unique for the visitor)
79 fun new_number: Int
80 do
81 _last_number += 1
82 return _last_number
83 end
84
85 # Return the string associated with a escape label
86 fun lab(e: ISeq): String
87 do
88 if _ids.has_key(e) then
89 return _ids[e]
90 else
91 var s = "label{new_number}"
92 _ids[e] = s
93 return s
94 end
95 end
96
97 # The rank (number) of each closure
98 readable var _closures: HashMap[IClosureDecl, String] = new HashMap[IClosureDecl, String]
99
100 # The functionnal type of each closure
101 readable var _clostypes: HashMap[IClosureDecl, String] = new HashMap[IClosureDecl, String]
102
103 # label locally accessibles
104 readable writable var _local_labels: HashSet[ISeq] = new HashSet[ISeq]
105
106 # Not local escaped labels
107 # The integer value is an index identifying the label
108 readable writable var _escaped_labels: HashMap[ISeq, Int] = new HashMap[ISeq, Int]
109
110 # Register a escape to a non local label and return an index identifying the label
111 fun register_escape_label(e: ISeq): Int
112 do
113 if _escaped_labels.has_key(e) then
114 return _escaped_labels[e]
115 else
116 var res = _escaped_labels.length + 1
117 _escaped_labels[e] = res
118 return res
119 end
120 end
121
122 # Add a C label mark (if needed)
123 fun add_label(e: ISeq)
124 do
125 if _ids.has_key(e) then
126 add_instr("{_ids[e]}: while(0);")
127 end
128 end
129
130 # Add a goto to a label (even outside a closure)
131 fun add_goto(seq: ISeq)
132 do
133 if local_labels.has(seq) then
134 add_instr("goto {lab(seq)};")
135 else
136 assert closure
137 var ind = register_escape_label(seq)
138 add_instr("closctx->has_broke = {ind};")
139 add_instr("goto {lab(return_label.as(not null))};")
140 end
141 end
142
143 # Association between IEscapeMarks and visited ISeq
144 readable var _marks_to_seq: Map[IEscapeMark, ISeq] = new HashMap[IEscapeMark, ISeq]
145
146 # Are we in a closure ?
147 readable writable var _closure: Bool = false
148
149 # The current compiler visitor
150 readable var _visitor: CompilerVisitor
151
152 # The current compiled iroutine
153 readable var _iroutine: IRoutine
154
155 # The return label of the current compiling C function
156 readable writable var _return_label: nullable ISeq = null
157
158 fun add_decl(s: String)
159 do
160 visitor.add_decl(s)
161 end
162
163 # Prepare a new instuction (indent, comment)
164 # Caller must ensure to add a new line to finish its instr
165 fun new_instr: Writer
166 do
167 var w = visitor.writer
168 var l = _next_location
169 if l != null then
170 visitor.add_indent(w)
171 w.add("/* ")
172 w.add(l.file.filename)
173 w.add(":")
174 w.add(l.line_start.to_s)
175 w.add(" */\n")
176 _next_location = null
177 end
178 visitor.add_indent(w)
179 return w
180 end
181
182 fun add_instr(s: String)
183 do
184 new_instr.add(s).add("\n")
185 end
186
187 fun indent
188 do
189 visitor.indent
190 end
191
192 fun unindent
193 do
194 visitor.unindent
195 end
196
197 fun add_assignment(to, from: String)
198 do
199 visitor.add_assignment(to, from)
200 end
201
202 var _last_location: nullable Location = null
203 var _next_location: nullable Location = null
204
205 # Add location information in a comment
206 # Do nothing if the last location added is the same
207 fun add_location(l: nullable Location)
208 do
209 var last = _last_location
210 if last == l or l == null then return
211 _last_location = l
212 if last != null and last.file == l.file and last.line_start == l.line_start then
213 return
214 else
215 _next_location = l
216 end
217 end
218
219 # The C fonction name of the iroutine
220 readable var _basecname: String
221
222 init(v: CompilerVisitor, ir: IRoutine, cname: String)
223 do
224 _visitor = v
225 _iroutine = ir
226 _basecname = cname
227 end
228 end
229
230 redef class IRoutine
231 # Declare and start a C function that match the routine
232 # Return what must be given to compile_inside_to_c or to compile_to_c
233 # After the method, an openinig { and and indent is added.
234 # So, do not forget to add a sub_context, to unintent and to add a closing }
235 fun compile_signature_to_c(v: CompilerVisitor, cname: String, human_name: nullable String, before_params, after_params: nullable String): Array[String]
236 do
237 var cargs = new Array[String]
238 var cparams = new Array[String]
239 if before_params != null then cparams.add(before_params)
240 for i in [0..params.length[ do
241 cargs.add("p{i}")
242 cparams.add("val_t p{i}")
243 end
244 if closure_decls != null then
245 cparams.add("struct stack_frame_t *closctx_param")
246 for i in [0..closure_decls.length[ do
247 var closcn = "CLOS_{cname}_{i}"
248 var cs = closure_decls[i].closure.signature
249 var subparams = new Array[String] # Parameters of the closure
250 subparams.add("struct stack_frame_t *")
251 for j in [0..cs.arity[ do
252 subparams.add("val_t")
253 end
254 var rr = "void"
255 if cs.return_type != null then rr = "val_t"
256 v.add_decl("typedef {rr} (*{closcn})({subparams.join(", ")});")
257 cargs.add("clos_fun{i}")
258 cparams.add("fun_t clos_fun{i}")
259 end
260 end
261 if after_params != null then cparams.add(after_params)
262 var r = "void"
263 if result != null then r = "val_t"
264 var p: String
265 if cparams.is_empty then
266 p = "void"
267 else
268 p = cparams.join(", ")
269 end
270 if human_name != null then v.add_decl("static const char * const LOCATE_{cname} = \"{human_name}\";")
271 v.add_decl("{r} {cname}({p});")
272 v.add_decl("typedef {r} (*{cname}_t)({p});")
273 v.add_instr("{r} {cname}({p})\{")
274 v.indent
275 return cargs
276 end
277
278 # Compile the body of the routine, return the result value is any
279 fun compile_inside_to_c(v: I2CCompilerVisitor, args: Array[String]): nullable String
280 do
281 # Create and push the stack frame
282 var ll = 0
283 if location != null then
284 ll = location.line_start
285 end
286 # Encapsulate the frame ('me') in a larger structure ('fra') that has enough space to store the local variables (REG)
287 if std_slots_nb > 1 then
288 v.add_decl("struct \{struct stack_frame_t me; val_t MORE_REG[{std_slots_nb-1}];\} fra;")
289 else
290 v.add_decl("struct \{struct stack_frame_t me;\} fra;")
291 end
292 v.add_instr("fra.me.prev = stack_frame_head; stack_frame_head = &fra.me;")
293 v.add_instr("fra.me.file = LOCATE_{v.visitor.mmmodule.cname};")
294 v.add_instr("fra.me.line = {ll};")
295 v.add_instr("fra.me.meth = LOCATE_{v.basecname};")
296 v.add_instr("fra.me.has_broke = 0;")
297 v.add_instr("fra.me.REG_size = {std_slots_nb};")
298 v.add_instr("fra.me.nitni_local_ref_head = NULL;")
299
300 # Declare/initialize local variables
301 for i in [0..std_slots_nb[ do
302 v.add_instr("fra.me.REG[{i}] = NIT_NULL;")
303 end
304 for i in [0..tag_slots_nb[ do
305 v.add_decl("val_t REGB{i};")
306 end
307 var iclosdecls = closure_decls
308 if iclosdecls != null then
309 v.add_decl("fun_t CREG[{iclosdecls.length}];")
310 v.add_instr("fra.me.closure_ctx = closctx_param;")
311 v.add_instr("fra.me.closure_funs = CREG;")
312 end
313 var k = 0
314 for r in params do
315 if r.slot_index != null then v.add_assignment(v.register(r), args[k])
316 k += 1
317 end
318 if iclosdecls != null then
319 for i in [0..iclosdecls.length[ do
320 var iclosdecl = iclosdecls[i]
321 v.add_instr("CREG[{i}] = {args[params.length+i]};")
322 v.closures[iclosdecl] = i.to_s
323 var cs = iclosdecl.closure.signature # Closure signature
324 var subparams = new Array[String] # Parameters of the closure
325 subparams.add("struct stack_frame_t *")
326 for j in [0..cs.arity[ do
327 var p = "val_t"
328 subparams.add(p)
329 end
330 var r = "void"
331 if cs.return_type != null then r = "val_t"
332 v.clostypes[iclosdecl] = "{r} (*)({subparams.join(", ")})"
333 end
334 end
335 v.add_decl("val_t tmp;")
336
337 # Prepare return
338 var old_rl = v.return_label
339 v.return_label = body
340
341 # Compile body
342 body.compile_to_c(v)
343
344 v.add_instr("stack_frame_head = fra.me.prev;")
345 v.return_label = old_rl
346 var r = result
347 if r != null then
348 return v.register(r)
349 else
350 return null
351 end
352 end
353
354 # Full compilation of the routine
355 # cv must be in the correct function
356 fun compile_to_c(cv: CompilerVisitor, cname: String, args: Array[String]): nullable String
357 do
358 var v = new I2CCompilerVisitor(cv, self, cname)
359 return compile_inside_to_c(v, args)
360 end
361 end
362
363 redef class ICode
364 # Full compilation of the icode
365 fun compile_to_c(v: I2CCompilerVisitor) is abstract
366
367 # Is a result really needed
368 private fun need_result: Bool
369 do
370 var r = result
371 return r != null and r.slot_index != null
372 end
373
374 # Store s in the result value of self
375 private fun store_result(v: I2CCompilerVisitor, w: nullable Writer)
376 do
377 var r = result
378 if r != null and r.slot_index != null then
379 assert w != null
380 var w2 = v.new_instr
381 w2.add(v.register(r))
382 w2.add(" = ")
383 w2.append(w)
384 w2.add(";\n")
385 else if w != null and not is_pure then
386 # ICode with side effects must be evaluated
387 # even if the result is not wanted
388 var w2 = v.new_instr
389 w2.append(w)
390 w2.add(";\n")
391 end
392 end
393
394 # Prepare a writer if the expression icode need to be compiled
395 # * Result assigment is automatic if needed
396 private fun new_result(v: I2CCompilerVisitor): Writer
397 do
398 assert need_result or not is_pure
399 var w2 = v.new_instr
400 var r = result
401 if r != null and r.slot_index != null then
402 w2.add(v.register(r))
403 w2.add(" = ")
404 end
405 var w = w2.sub
406 w2.add(";\n")
407 return w
408 end
409 end
410
411 redef class ISeq
412 redef fun compile_to_c(v)
413 do
414 v.add_location(location)
415 v.local_labels.add(self)
416 var mark = iescape_mark
417 if mark != null then v.marks_to_seq[mark] = self
418 for ic in icodes do
419 ic.compile_to_c(v)
420 end
421 v.add_label(self)
422 end
423 end
424
425 redef class IIf
426 redef fun compile_to_c(v)
427 do
428 v.add_location(location)
429 var w = v.new_instr
430 w.add("if (UNTAG_Bool(")
431 w.add(v.register(expr))
432 w.add(")) \{\n")
433 if not then_seq.icodes.is_empty then
434 v.indent
435 then_seq.compile_to_c(v)
436 v.unindent
437 end
438 if not else_seq.icodes.is_empty then
439 v.add_instr("\} else \{")
440 v.indent
441 else_seq.compile_to_c(v)
442 v.unindent
443 end
444 v.add_instr("\}")
445 end
446 end
447
448 redef class ILoop
449 redef fun compile_to_c(v)
450 do
451 v.add_location(location)
452 v.local_labels.add(self)
453 var mark = iescape_mark
454 if mark != null then v.marks_to_seq[mark] = self
455 v.add_instr("while(1) \{")
456 v.indent
457 for ic in icodes do
458 ic.compile_to_c(v)
459 end
460 v.unindent
461 v.add_instr("\}")
462 v.add_label(self)
463 end
464 end
465
466 redef class IEscape
467 redef fun compile_to_c(v)
468 do
469 v.add_location(location)
470 v.add_goto(v.marks_to_seq[iescape_mark])
471 end
472 end
473
474 redef class IAbsCall
475 redef fun compile_to_c(v)
476 do
477 v.add_location(location)
478 var args = v.registers(exprs)
479
480 # Compile closure definitions
481 var old_el = v.escaped_labels
482 var closdefs = closure_defs
483 var closctx: nullable String = null # The closure context of closdefs
484 if closdefs != null then
485 # Get the closure context
486 if v.closure then
487 closctx = "closctx"
488 else
489 closctx = "(&(fra.me))"
490 end
491
492 # First aditionnal arguments is the closure context
493 args.add(closctx)
494
495 # We are in a new escape boundary
496 v.escaped_labels = new HashMap[ISeq, Int]
497
498 # Compile each closures and add each sub-function as an other additionnal parameter
499 for cd in closdefs do
500 if cd != null then
501 var cn = cd.compile_closure(v)
502 args.add(cn)
503 else
504 args.add("NULL")
505 end
506 end
507 end
508
509 # Compile the real call
510 var call = compile_call_to_c(v, args)
511 var res: nullable Writer = call
512
513 # Intercept escapes
514 if closctx != null then
515 var els = v.escaped_labels
516 v.escaped_labels = old_el
517 # Is there possible escapes?
518 if not els.is_empty then
519 # Call in a tmp variable to avoid 'break' overwrite
520 var w = v.new_instr
521 if need_result then
522 w.add("tmp")
523 w.add(" = ")
524 w.append(call)
525 w.add(";\n")
526 res = new Writer
527 res.add("tmp")
528 else
529 res = null
530 w.append(call)
531 w.add(";\n")
532 end
533 # What are the expected escape indexes
534 v.new_instr.add("switch (").add(closctx).add("->has_broke) \{\n")
535 v.indent
536 # No escape occured, continue as usual
537 v.add_instr("case 0: break;")
538 var lls = v.local_labels
539 var iels = els.iterator
540 var forward_escape = false
541 while iels.is_ok do
542 var seq = iels.key
543 if lls.has(seq) then
544 # Local escape occured
545 # Clear the has_broke information and go to the target
546 v.new_instr.add("case ").add(iels.item.to_s).add(": ").add(closctx).add("->has_broke = 0; goto ").add(v.lab(seq)).add(";\n")
547 else
548 # Forward escape occured: register the escape label
549 assert v.closure
550 v.register_escape_label(seq)
551 forward_escape = true
552 end
553 iels.next
554 end
555 # If forward escape occured, just pass to the next one
556 if forward_escape then
557 # Do not need to copy 'has_broke' value since it is shared by the next one.
558 # So just exit the C function.
559 v.new_instr.add("default: goto ").add(v.lab(v.return_label.as(not null))).add(";\n")
560 end
561 v.unindent
562 v.add_instr("\}")
563 end
564 end
565
566 if res != null then
567 var w = new_result(v)
568 w.append(res)
569 end
570 end
571
572 # The single invocation witout fancy stuffs
573 private fun compile_call_to_c(v: I2CCompilerVisitor, args: Array[String]): Writer is abstract
574 end
575
576 redef class ICall
577 redef fun compile_call_to_c(v, args)
578 do
579 var w = new Writer
580
581 # do not compile explicit calls from native methods
582 # theses are really manually called in the native implementation
583 if is_explicit_from_extern then return w
584
585 var prop = property
586 if prop.global.is_init then args.add("init_table")
587 w.add(prop.global.meth_call)
588 w.add("(")
589 w.add(args.first)
590 w.add(")(")
591 w.add_all(args, ", ")
592 w.add(")")
593 return w
594 end
595 end
596
597 redef class ISuper
598 redef fun compile_call_to_c(v, args)
599 do
600 # do not compile explicit calls from native methods
601 # theses are really manually called in the native implementation
602 if is_explicit_from_extern then return new Writer
603
604 var prop = property
605 if prop.global.is_init then args.add("init_table")
606 var w = new Writer
607 w.add(prop.super_meth_call)
608 w.add("(")
609 w.add(args.first)
610 w.add(")(")
611 w.add_all(args, ", ")
612 w.add(")")
613 return w
614 end
615 end
616
617 redef class INew
618 redef fun compile_call_to_c(v, args)
619 do
620 var w = new Writer
621
622 # do not compile explicit calls from native methods
623 # theses are really manually called in the native implementation
624 if is_explicit_from_extern then return w
625
626 w.add("NEW_")
627 w.add(stype.local_class.to_s)
628 w.add("_")
629 w.add(property.global.intro.cname)
630 w.add("(")
631 w.add_all(args, ", ")
632 w.add(")")
633 return w
634 end
635 end
636
637 redef class IAllocateInstance
638 redef fun compile_to_c(v)
639 do
640 v.add_location(location)
641 var w = new_result(v)
642 w.add("NEW_")
643 w.add(stype.local_class.cname)
644 w.add("()")
645 end
646 end
647
648 redef class ICheckInstance
649 redef fun compile_to_c(v)
650 do
651 v.add_location(location)
652 var w = new_result(v)
653 w.add("CHECKNEW_")
654 w.add(stype.local_class.cname)
655 w.add("(")
656 w.add(v.register(expr))
657 w.add(")")
658 end
659 end
660
661 redef class IInitAttributes
662 redef fun compile_to_c(v)
663 do
664 v.add_location(location)
665 var w = v.new_instr
666 w.add("INIT_ATTRIBUTES__")
667 w.add(stype.local_class.cname)
668 w.add("(")
669 w.add(v.register(expr))
670 w.add(");\n")
671 end
672 end
673
674 redef class IStaticCall
675 redef fun compile_call_to_c(v, args)
676 do
677 var prop = property
678 if prop.global.is_init then args.add("init_table")
679 var w = new Writer
680 w.add(property.cname)
681 w.add("(")
682 w.add_all(args, ", ")
683 w.add(")")
684 return w
685 end
686 end
687
688 redef class INative
689 redef fun compile_to_c(v)
690 do
691 v.add_location(location)
692 if method.is_intern then
693 compile_intern_method_to_c(v)
694 else if not method.global.is_init then
695 compile_extern_method_to_c(v)
696 end
697 end
698
699 fun compile_extern_method_to_c(v: I2CCompilerVisitor)
700 do
701 var ename = "{method.friendly_extern_name(method.local_class)}___out"
702
703 var sig = method.signature
704 assert exprs.length == sig.arity + 1
705
706 var regs = v.registers(exprs)
707
708 var args = new Array[String]
709 args.add(regs[0])
710 for i in [0..sig.arity[ do
711 args.add(regs[i+1])
712 end
713 var s = "{ename}({args.join(", ")})"
714
715 if need_result then s = s # sig.return_type.boxtype(s)
716 var w = new_result(v)
717 w.add(s)
718 end
719
720 fun compile_intern_method_to_c(v: I2CCompilerVisitor)
721 do
722 var sig = method.signature
723 assert exprs.length == sig.arity + 1
724 var c = method.local_class.name
725 var n = method.name
726 var regs = v.registers(exprs)
727 var s: nullable String = null
728 if c == once "Int".to_symbol then
729 if n == once "object_id".to_symbol then
730 s = regs[0]
731 else if n == once "unary -".to_symbol then
732 s = "TAG_Int(-UNTAG_Int({regs[0]}))"
733 else if n == once "output".to_symbol then
734 s = "printf(\"%ld\\n\", UNTAG_Int({regs[0]}));"
735 else if n == once "ascii".to_symbol then
736 s = "TAG_Char(UNTAG_Int({regs[0]}))"
737 else if n == once "succ".to_symbol then
738 s = "TAG_Int(UNTAG_Int({regs[0]})+1)"
739 else if n == once "prec".to_symbol then
740 s = "TAG_Int(UNTAG_Int({regs[0]})-1)"
741 else if n == once "to_f".to_symbol then
742 s = "BOX_Float((float)UNTAG_Int({regs[0]}))"
743 else if n == once "+".to_symbol then
744 s = "TAG_Int(UNTAG_Int({regs[0]})+UNTAG_Int({regs[1]}))"
745 else if n == once "-".to_symbol then
746 s = "TAG_Int(UNTAG_Int({regs[0]})-UNTAG_Int({regs[1]}))"
747 else if n == once "*".to_symbol then
748 s = "TAG_Int(UNTAG_Int({regs[0]})*UNTAG_Int({regs[1]}))"
749 else if n == once "/".to_symbol then
750 s = "TAG_Int(UNTAG_Int({regs[0]})/UNTAG_Int({regs[1]}))"
751 else if n == once "%".to_symbol then
752 s = "TAG_Int(UNTAG_Int({regs[0]})%UNTAG_Int({regs[1]}))"
753 else if n == once "<".to_symbol then
754 s = "TAG_Bool(UNTAG_Int({regs[0]})<UNTAG_Int({regs[1]}))"
755 else if n == once ">".to_symbol then
756 s = "TAG_Bool(UNTAG_Int({regs[0]})>UNTAG_Int({regs[1]}))"
757 else if n == once "<=".to_symbol then
758 s = "TAG_Bool(UNTAG_Int({regs[0]})<=UNTAG_Int({regs[1]}))"
759 else if n == once ">=".to_symbol then
760 s = "TAG_Bool(UNTAG_Int({regs[0]})>=UNTAG_Int({regs[1]}))"
761 else if n == once "lshift".to_symbol then
762 s = "TAG_Int(UNTAG_Int({regs[0]})<<UNTAG_Int({regs[1]}))"
763 else if n == once "rshift".to_symbol then
764 s = "TAG_Int(UNTAG_Int({regs[0]})>>UNTAG_Int({regs[1]}))"
765 else if n == once "==".to_symbol then
766 s = "TAG_Bool(({regs[0]})==({regs[1]}))"
767 else if n == once "!=".to_symbol then
768 s = "TAG_Bool(({regs[0]})!=({regs[1]}))"
769 end
770 else if c == once "Float".to_symbol then
771 if n == once "object_id".to_symbol then
772 s = "TAG_Int((bigint)UNBOX_Float({regs[0]}))"
773 else if n == once "unary -".to_symbol then
774 s = "BOX_Float(-UNBOX_Float({regs[0]}))"
775 else if n == once "output".to_symbol then
776 s = "printf(\"%f\\n\", UNBOX_Float({regs[0]}));"
777 else if n == once "to_i".to_symbol then
778 s = "TAG_Int((bigint)UNBOX_Float({regs[0]}))"
779 else if n == once "+".to_symbol then
780 s = "BOX_Float(UNBOX_Float({regs[0]})+UNBOX_Float({regs[1]}))"
781 else if n == once "-".to_symbol then
782 s = "BOX_Float(UNBOX_Float({regs[0]})-UNBOX_Float({regs[1]}))"
783 else if n == once "*".to_symbol then
784 s = "BOX_Float(UNBOX_Float({regs[0]})*UNBOX_Float({regs[1]}))"
785 else if n == once "/".to_symbol then
786 s = "BOX_Float(UNBOX_Float({regs[0]})/UNBOX_Float({regs[1]}))"
787 else if n == once "<".to_symbol then
788 s = "TAG_Bool(UNBOX_Float({regs[0]})<UNBOX_Float({regs[1]}))"
789 else if n == once ">".to_symbol then
790 s = "TAG_Bool(UNBOX_Float({regs[0]})>UNBOX_Float({regs[1]}))"
791 else if n == once "<=".to_symbol then
792 s = "TAG_Bool(UNBOX_Float({regs[0]})<=UNBOX_Float({regs[1]}))"
793 else if n == once ">=".to_symbol then
794 s = "TAG_Bool(UNBOX_Float({regs[0]})>=UNBOX_Float({regs[1]}))"
795 end
796 else if c == once "Char".to_symbol then
797 if n == once "object_id".to_symbol then
798 s = "TAG_Int(UNTAG_Char({regs[0]}))"
799 else if n == once "unary -".to_symbol then
800 s = "TAG_Char(-UNTAG_Char({regs[0]}))"
801 else if n == once "output".to_symbol then
802 s = "printf(\"%c\", (unsigned char)UNTAG_Char({regs[0]}));"
803 else if n == once "ascii".to_symbol then
804 s = "TAG_Int((unsigned char)UNTAG_Char({regs[0]}))"
805 else if n == once "succ".to_symbol then
806 s = "TAG_Char(UNTAG_Char({regs[0]})+1)"
807 else if n == once "prec".to_symbol then
808 s = "TAG_Char(UNTAG_Char({regs[0]})-1)"
809 else if n == once "to_i".to_symbol then
810 s = "TAG_Int(UNTAG_Char({regs[0]})-'0')"
811 else if n == once "+".to_symbol then
812 s = "TAG_Char(UNTAG_Char({regs[0]})+UNTAG_Char({regs[1]}))"
813 else if n == once "-".to_symbol then
814 s = "TAG_Char(UNTAG_Char({regs[0]})-UNTAG_Char({regs[1]}))"
815 else if n == once "*".to_symbol then
816 s = "TAG_Char(UNTAG_Char({regs[0]})*UNTAG_Char({regs[1]}))"
817 else if n == once "/".to_symbol then
818 s = "TAG_Char(UNTAG_Char({regs[0]})/UNTAG_Char({regs[1]}))"
819 else if n == once "%".to_symbol then
820 s = "TAG_Char(UNTAG_Char({regs[0]})%UNTAG_Char({regs[1]}))"
821 else if n == once "<".to_symbol then
822 s = "TAG_Bool(UNTAG_Char({regs[0]})<UNTAG_Char({regs[1]}))"
823 else if n == once ">".to_symbol then
824 s = "TAG_Bool(UNTAG_Char({regs[0]})>UNTAG_Char({regs[1]}))"
825 else if n == once "<=".to_symbol then
826 s = "TAG_Bool(UNTAG_Char({regs[0]})<=UNTAG_Char({regs[1]}))"
827 else if n == once ">=".to_symbol then
828 s = "TAG_Bool(UNTAG_Char({regs[0]})>=UNTAG_Char({regs[1]}))"
829 else if n == once "==".to_symbol then
830 s = "TAG_Bool(({regs[0]})==({regs[1]}))"
831 else if n == once "!=".to_symbol then
832 s = "TAG_Bool(({regs[0]})!=({regs[1]}))"
833 end
834 else if c == once "Bool".to_symbol then
835 if n == once "object_id".to_symbol then
836 s = "TAG_Int(UNTAG_Bool({regs[0]}))"
837 else if n == once "unary -".to_symbol then
838 s = "TAG_Bool(-UNTAG_Bool({regs[0]}))"
839 else if n == once "output".to_symbol then
840 s = "(void)printf(UNTAG_Bool({regs[0]})?\"true\\n\":\"false\\n\");"
841 else if n == once "ascii".to_symbol then
842 s = "TAG_Bool(UNTAG_Bool({regs[0]}))"
843 else if n == once "to_i".to_symbol then
844 s = "TAG_Int(UNTAG_Bool({regs[0]}))"
845 else if n == once "==".to_symbol then
846 s = "TAG_Bool(({regs[0]})==({regs[1]}))"
847 else if n == once "!=".to_symbol then
848 s = "TAG_Bool(({regs[0]})!=({regs[1]}))"
849 end
850 else if c == once "NativeArray".to_symbol then
851 if n == once "object_id".to_symbol then
852 s = "TAG_Int(((Nit_NativeArray){regs[0]})->object_id)"
853 else if n == once "[]".to_symbol then
854 s = "((Nit_NativeArray){regs[0]})->val[UNTAG_Int({regs[1]})]"
855 else if n == once "[]=".to_symbol then
856 s = "((Nit_NativeArray){regs[0]})->val[UNTAG_Int({regs[1]})]={regs[2]}"
857 else if n == once "copy_to".to_symbol then
858 s = "(void)memcpy(((Nit_NativeArray ){regs[1]})->val, ((Nit_NativeArray){regs[0]})->val, UNTAG_Int({regs[2]})*sizeof(val_t))"
859 end
860 else if c == once "NativeString".to_symbol then
861 if n == once "object_id".to_symbol then
862 s = "TAG_Int(UNBOX_NativeString({regs[0]}))"
863 else if n == once "atoi".to_symbol then
864 s = "TAG_Int(atoi(UNBOX_NativeString({regs[0]})))"
865 else if n == once "[]".to_symbol then
866 s = "TAG_Char(UNBOX_NativeString({regs[0]})[UNTAG_Int({regs[1]})])"
867 else if n == once "[]=".to_symbol then
868 s = "UNBOX_NativeString({regs[0]})[UNTAG_Int({regs[1]})]=UNTAG_Char({regs[2]});"
869 else if n == once "copy_to".to_symbol then
870 s = "(void)memcpy(UNBOX_NativeString({regs[1]})+UNTAG_Int({regs[4]}), UNBOX_NativeString({regs[0]})+UNTAG_Int({regs[3]}), UNTAG_Int({regs[2]}));"
871 end
872 else if c == once "Sys".to_symbol then
873 if n == once "force_garbage_collection".to_symbol then
874 s = "Nit_gc_force_garbage_collection()"
875 end
876 else if n == once "object_id".to_symbol then
877 s = "TAG_Int((bigint)((obj_t){regs[0]})[1].object_id)"
878 else if n == once "sys".to_symbol then
879 s = "(G_sys)"
880 else if n == once "is_same_type".to_symbol then
881 s = "TAG_Bool((VAL2VFT({regs[0]})==VAL2VFT({regs[1]})))"
882 else if n == once "exit".to_symbol then
883 s = "exit(UNTAG_Int({regs[1]}));"
884 else if n == once "calloc_array".to_symbol then
885 s = "NEW_NativeArray(UNTAG_Int({regs[1]}), sizeof(val_t))"
886 else if n == once "calloc_string".to_symbol then
887 s = "BOX_NativeString((char*)raw_alloc((UNTAG_Int({regs[1]}) * sizeof(char))))"
888 # Add output_class_name native implementation
889 else if n == once "output_class_name".to_symbol then
890 s = "printf(\"%s\\n\", VAL2VFT({regs[0]})[2].cname);"
891 # Add class_name implementation
892 else if n == once "native_class_name".to_symbol then
893 s = "BOX_NativeString(VAL2VFT({regs[0]})[2].cname);"
894 end
895
896 if s == null then
897 var ll = location
898 if ll != null then v.add_instr("fprintf(stderr, \"{ll.to_s}: \");")
899 v.add_instr("fprintf(stderr, \"Fatal error: unknown intern method {method.full_name}.\\n\");")
900 v.add_instr("nit_exit(1);")
901 s = "NIT_NULL"
902 end
903 if result == null then
904 v.new_instr.add(s).add(";\n")
905 else if need_result then
906 var w = new_result(v)
907 w.add(s)
908 end
909 end
910 end
911
912 redef class IIntValue
913 redef fun compile_to_c(v)
914 do
915 v.add_location(location)
916 var w = new_result(v)
917 w.add("TAG_Int(").add(value.to_s).add(")")
918 end
919 end
920
921 redef class IBoolValue
922 redef fun compile_to_c(v)
923 do
924 v.add_location(location)
925 var w = new_result(v)
926 w.add("TAG_Bool(")
927 if value then w.add("true") else w.add("false")
928 w.add(")")
929 end
930 end
931
932 redef class ICharValue
933 redef fun compile_to_c(v)
934 do
935 v.add_location(location)
936 var w = new_result(v)
937 w.add("TAG_Char(").add(value).add(")")
938 end
939 end
940
941 redef class IFloatValue
942 redef fun compile_to_c(v)
943 do
944 v.add_location(location)
945 var w = new_result(v)
946 w.add("BOX_Float(").add(value).add(")")
947 end
948 end
949
950 redef class IStringValue
951 redef fun compile_to_c(v)
952 do
953 v.add_location(location)
954 var w = new_result(v)
955 w.add("BOX_NativeString(\"").add(value).add("\")")
956 end
957 end
958
959 redef class IAbort
960 redef fun compile_to_c(v)
961 do
962 v.add_location(location)
963 var w = v.new_instr
964 w.add("nit_abort(\"")
965 w.add(texts[0])
966 if texts.length > 1 then
967 w.add("\", \"")
968 w.add(texts[1])
969 w.add("\"")
970 else
971 w.add("\", NULL")
972 end
973 w.add(", LOCATE_")
974 w.add(module_location.cname)
975 var ll = location
976 if ll != null then
977 w.add(", ")
978 w.add(ll.line_start.to_s)
979 else
980 w.add(", 0")
981 end
982 w.add(");\n")
983 end
984 end
985
986 redef class IMove
987 redef fun compile_to_c(v)
988 do
989 if not need_result then return
990 var e = v.register(expr)
991 var r = v.register(result.as(not null))
992 if e == r then return
993 v.add_location(location)
994 var w = v.new_instr
995 w.add(r)
996 w.add(" = ")
997 w.add(e)
998 w.add(";\n")
999 end
1000 end
1001
1002 redef class IAttrRead
1003 redef fun compile_to_c(v)
1004 do
1005 if not need_result then return
1006 v.add_location(location)
1007 var w = new_result(v)
1008 w.add(property.global.attr_access)
1009 w.add("(")
1010 w.add(v.register(expr))
1011 w.add(")")
1012 end
1013 end
1014
1015 redef class IAttrIsset
1016 redef fun compile_to_c(v)
1017 do
1018 if not need_result then return
1019 v.add_location(location)
1020 var w = new_result(v)
1021 w.add("TAG_Bool(")
1022 w.add(property.global.attr_access)
1023 w.add("(")
1024 w.add(v.register(expr))
1025 w.add(")!=NIT_NULL)")
1026 end
1027 end
1028
1029 redef class IAttrWrite
1030 redef fun compile_to_c(v)
1031 do
1032 v.add_location(location)
1033 var w = v.new_instr
1034 w.add(property.global.attr_access)
1035 w.add("(")
1036 w.add(v.register(expr1))
1037 w.add(") = ")
1038 w.add(v.register(expr2))
1039 w.add(";\n")
1040 end
1041 end
1042
1043 redef class ITypeCheck
1044 redef fun compile_to_c(v)
1045 do
1046 if not need_result then return
1047 v.add_location(location)
1048 var recv = v.register(expr2)
1049 var w = new_result(v)
1050 w.add("TAG_Bool(")
1051 if expr2.stype.is_nullable then
1052 if stype.is_nullable then
1053 w.add("(")
1054 w.add(recv)
1055 w.add("==NIT_NULL) || ")
1056 else if stype.as_nullable == expr2.stype then
1057 w.add(recv)
1058 w.add("!=NIT_NULL)")
1059 return
1060 else
1061 w.add("(")
1062 w.add(recv)
1063 w.add("!=NIT_NULL) && ")
1064 end
1065 end
1066 # FIXME handle formaltypes
1067 var t = stype
1068 if t isa MMVirtualType then
1069 var slf = v.register(expr1)
1070 var g = t.property.global
1071 w.add("VAL_ISA(")
1072 w.add(recv)
1073 w.add(", ")
1074 w.add(g.vt_class_color)
1075 w.add("(")
1076 w.add(slf)
1077 w.add(")")
1078 w.add(", ")
1079 w.add(g.vt_class_id)
1080 w.add("(")
1081 w.add(slf)
1082 w.add(")")
1083 w.add(")) /*cast ")
1084 w.add(t.to_s)
1085 w.add("*/")
1086 else
1087 var g = t.local_class.global
1088 w.add("VAL_ISA(")
1089 w.add(recv)
1090 w.add(", ")
1091 w.add(g.color_id)
1092 w.add(", ")
1093 w.add(g.id_id)
1094 w.add(")) /*cast ")
1095 w.add(t.to_s)
1096 w.add("*/")
1097 end
1098 end
1099 end
1100
1101 redef class IIs
1102 redef fun compile_to_c(v)
1103 do
1104 if not need_result then return
1105 v.add_location(location)
1106 var w = new_result(v)
1107 w.add("TAG_Bool(")
1108 var t1 = expr1.stype
1109 var t2 = expr2.stype
1110 if t1 isa MMTypeNone then
1111 if t2 isa MMTypeNone then
1112 w.add("1)")
1113 return
1114 else if t2.is_nullable then
1115 w.add(v.register(expr2))
1116 w.add("==NIT_NULL)")
1117 return
1118 else
1119 w.add("0)")
1120 return
1121 end
1122 else if t1.is_nullable then
1123 if t2 isa MMTypeNone then
1124 w.add(v.register(expr1))
1125 w.add("==NIT_NULL)")
1126 return
1127 else if t2.is_nullable then
1128 w.add("IS_EQUAL_NN(")
1129 else
1130 w.add("IS_EQUAL_ON(")
1131 w.add(v.register(expr2))
1132 w.add(",")
1133 w.add(v.register(expr1))
1134 w.add("))")
1135 return
1136 end
1137 else
1138 if t2 isa MMTypeNone then
1139 w.add("0)")
1140 return
1141 else if t2.is_nullable then
1142 w.add("IS_EQUAL_ON(")
1143 else
1144 w.add("IS_EQUAL_OO(")
1145 end
1146 end
1147 w.add(v.register(expr1))
1148 w.add(",")
1149 w.add(v.register(expr2))
1150 w.add("))")
1151 end
1152 end
1153
1154 redef class INot
1155 redef fun compile_to_c(v)
1156 do
1157 if not need_result then return
1158 v.add_location(location)
1159 var w = new_result(v)
1160 w.add("TAG_Bool(!UNTAG_Bool(")
1161 w.add(v.register(expr))
1162 w.add("))")
1163 end
1164 end
1165
1166 redef class IOnce
1167 redef fun compile_to_c(v)
1168 do
1169 v.add_location(location)
1170 var i = v.new_number
1171 var res = result.as(not null)
1172 if res.stype.is_nullable then
1173 v.add_decl("static val_t once_value_{i}; static int once_bool_{i}; /* Once value */")
1174 v.add_instr("if (!once_bool_{i}) \{")
1175 else
1176 # Since the value is not nullable, we use the null value to represent the boolean
1177 v.add_decl("static val_t once_value_{i}; /* Once value */")
1178 v.add_instr("if (!once_value_{i}) \{")
1179 end
1180 v.indent
1181 body.compile_to_c(v)
1182 var e = v.register(res)
1183 v.add_instr("once_value_{i} = {e};")
1184 v.add_instr("register_static_object(&once_value_{i});")
1185 if res.stype.is_nullable then v.add_instr("once_bool_{i} = true;")
1186 v.unindent
1187 v.add_instr("\} else {e} = once_value_{i};")
1188 var w = new_result(v)
1189 w.add(e)
1190 end
1191 end
1192
1193 redef class IClosCall
1194 redef fun compile_to_c(v: I2CCompilerVisitor)
1195 do
1196 v.add_location(location)
1197 var ivar: String
1198 var args: Array[String]
1199 if v.closure then
1200 ivar = "closctx->closure_funs[{v.closures[closure_decl]}]"
1201 args = ["closctx->closure_ctx"]
1202 else
1203 ivar = "CREG[{v.closures[closure_decl]}]"
1204 args = ["closctx_param"]
1205 end
1206 args.append(v.registers(exprs))
1207
1208 var s = "(({v.clostypes[closure_decl]})({ivar}))({args.join(", ")})"
1209 var w = new Writer
1210 w.add(s)
1211 store_result(v, w)
1212
1213 # Intercept escape
1214 v.add_instr("if ({args.first}->has_broke) \{")
1215 v.indent
1216 var bs = break_seq
1217 if bs != null then
1218 bs.compile_to_c(v)
1219 end
1220 v.add_goto(v.iroutine.body)
1221 v.unindent
1222 v.add_instr("\}")
1223 end
1224 end
1225
1226 redef class IHasClos
1227 redef fun compile_to_c(v)
1228 do
1229 if not need_result then return
1230 v.add_location(location)
1231 var w = new_result(v)
1232 w.add("TAG_Bool(")
1233 if v.closure then
1234 w.add("closctx->closure_funs[")
1235 w.add(v.closures[closure_decl])
1236 w.add("]")
1237 else
1238 w.add("CREG[")
1239 w.add(v.closures[closure_decl])
1240 w.add("]")
1241 end
1242 w.add(" != NULL)")
1243 end
1244 end
1245
1246 redef class IClosureDef
1247 # Compile the closure as a separate C function in the visitor out_contexts.
1248 # Return a fun_t pointer to the function.
1249 fun compile_closure(v: I2CCompilerVisitor): String
1250 do
1251 var cv = v.visitor
1252
1253 # We are now in a closure
1254 var cfc_old = v.closure
1255 v.closure = true
1256
1257 # We are now in a escape boundary
1258 var lls_old = v.local_labels
1259 v.local_labels = new HashSet[ISeq]
1260
1261 # We are now in a new C context
1262 var decl_writer_old = cv.decl_writer
1263 var writer_old = cv.writer
1264 cv.writer = cv.top_writer.sub
1265 cv.decl_writer = cv.header_writer.sub
1266
1267 # Generate the C function
1268 var cname = "OC_{v.basecname}_{v.new_number}"
1269 var args = compile_signature_to_c(v.visitor, cname, null, "struct stack_frame_t *closctx", null)
1270 cv.decl_writer = cv.writer.sub
1271
1272 var s = compile_inside_to_c(v, args)
1273 if s == null then
1274 v.add_instr("return;")
1275 else
1276 v.add_instr("return {s};")
1277 end
1278 v.unindent
1279 v.add_instr("\}")
1280
1281 # Restore things
1282 cv.writer = writer_old
1283 cv.decl_writer = decl_writer_old
1284 v.closure = cfc_old
1285 v.local_labels = lls_old
1286 return "((fun_t){cname})"
1287 end
1288 end