nit: restrict some module visibility
[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
299 # Declare/initialize local variables
300 for i in [0..std_slots_nb[ do
301 v.add_instr("fra.me.REG[{i}] = NIT_NULL;")
302 end
303 for i in [0..tag_slots_nb[ do
304 v.add_decl("val_t REGB{i};")
305 end
306 var iclosdecls = closure_decls
307 if iclosdecls != null then
308 v.add_decl("fun_t CREG[{iclosdecls.length}];")
309 v.add_instr("fra.me.closure_ctx = closctx_param;")
310 v.add_instr("fra.me.closure_funs = CREG;")
311 end
312 var k = 0
313 for r in params do
314 if r.slot_index != null then v.add_assignment(v.register(r), args[k])
315 k += 1
316 end
317 if iclosdecls != null then
318 for i in [0..iclosdecls.length[ do
319 var iclosdecl = iclosdecls[i]
320 v.add_instr("CREG[{i}] = {args[params.length+i]};")
321 v.closures[iclosdecl] = i.to_s
322 var cs = iclosdecl.closure.signature # Closure signature
323 var subparams = new Array[String] # Parameters of the closure
324 subparams.add("struct stack_frame_t *")
325 for j in [0..cs.arity[ do
326 var p = "val_t"
327 subparams.add(p)
328 end
329 var r = "void"
330 if cs.return_type != null then r = "val_t"
331 v.clostypes[iclosdecl] = "{r} (*)({subparams.join(", ")})"
332 end
333 end
334 v.add_decl("val_t tmp;")
335
336 # Prepare return
337 var old_rl = v.return_label
338 v.return_label = body
339
340 # Compile body
341 body.compile_to_c(v)
342
343 v.add_instr("stack_frame_head = fra.me.prev;")
344 v.return_label = old_rl
345 var r = result
346 if r != null then
347 return v.register(r)
348 else
349 return null
350 end
351 end
352
353 # Full compilation of the routine
354 # cv must be in the correct function
355 fun compile_to_c(cv: CompilerVisitor, cname: String, args: Array[String]): nullable String
356 do
357 var v = new I2CCompilerVisitor(cv, self, cname)
358 return compile_inside_to_c(v, args)
359 end
360 end
361
362 redef class ICode
363 # Full compilation of the icode
364 fun compile_to_c(v: I2CCompilerVisitor) is abstract
365
366 # Is a result really needed
367 private fun need_result: Bool
368 do
369 var r = result
370 return r != null and r.slot_index != null
371 end
372
373 # Store s in the result value of self
374 private fun store_result(v: I2CCompilerVisitor, w: nullable Writer)
375 do
376 var r = result
377 if r != null and r.slot_index != null then
378 assert w != null
379 var w2 = v.new_instr
380 w2.add(v.register(r))
381 w2.add(" = ")
382 w2.append(w)
383 w2.add(";\n")
384 else if w != null and not is_pure then
385 # ICode with side effects must be evaluated
386 # even if the result is not wanted
387 var w2 = v.new_instr
388 w2.append(w)
389 w2.add(";\n")
390 end
391 end
392
393 # Prepare a writer if the expression icode need to be compiled
394 # * Result assigment is automatic if needed
395 private fun new_result(v: I2CCompilerVisitor): Writer
396 do
397 assert need_result or not is_pure
398 var w2 = v.new_instr
399 var r = result
400 if r != null and r.slot_index != null then
401 w2.add(v.register(r))
402 w2.add(" = ")
403 end
404 var w = w2.sub
405 w2.add(";\n")
406 return w
407 end
408 end
409
410 redef class ISeq
411 redef fun compile_to_c(v)
412 do
413 v.add_location(location)
414 v.local_labels.add(self)
415 var mark = iescape_mark
416 if mark != null then v.marks_to_seq[mark] = self
417 for ic in icodes do
418 ic.compile_to_c(v)
419 end
420 v.add_label(self)
421 end
422 end
423
424 redef class IIf
425 redef fun compile_to_c(v)
426 do
427 v.add_location(location)
428 var w = v.new_instr
429 w.add("if (UNTAG_Bool(")
430 w.add(v.register(expr))
431 w.add(")) \{\n")
432 if not then_seq.icodes.is_empty then
433 v.indent
434 then_seq.compile_to_c(v)
435 v.unindent
436 end
437 if not else_seq.icodes.is_empty then
438 v.add_instr("\} else \{")
439 v.indent
440 else_seq.compile_to_c(v)
441 v.unindent
442 end
443 v.add_instr("\}")
444 end
445 end
446
447 redef class ILoop
448 redef fun compile_to_c(v)
449 do
450 v.add_location(location)
451 v.local_labels.add(self)
452 var mark = iescape_mark
453 if mark != null then v.marks_to_seq[mark] = self
454 v.add_instr("while(1) \{")
455 v.indent
456 for ic in icodes do
457 ic.compile_to_c(v)
458 end
459 v.unindent
460 v.add_instr("\}")
461 v.add_label(self)
462 end
463 end
464
465 redef class IEscape
466 redef fun compile_to_c(v)
467 do
468 v.add_location(location)
469 v.add_goto(v.marks_to_seq[iescape_mark])
470 end
471 end
472
473 redef class IAbsCall
474 redef fun compile_to_c(v)
475 do
476 v.add_location(location)
477 var args = v.registers(exprs)
478
479 # Compile closure definitions
480 var old_el = v.escaped_labels
481 var closdefs = closure_defs
482 var closctx: nullable String = null # The closure context of closdefs
483 if closdefs != null then
484 # Get the closure context
485 if v.closure then
486 closctx = "closctx"
487 else
488 closctx = "(&(fra.me))"
489 end
490
491 # First aditionnal arguments is the closure context
492 args.add(closctx)
493
494 # We are in a new escape boundary
495 v.escaped_labels = new HashMap[ISeq, Int]
496
497 # Compile each closures and add each sub-function as an other additionnal parameter
498 for cd in closdefs do
499 if cd != null then
500 var cn = cd.compile_closure(v)
501 args.add(cn)
502 else
503 args.add("NULL")
504 end
505 end
506 end
507
508 # Compile the real call
509 var call = compile_call_to_c(v, args)
510 var res: nullable Writer = call
511
512 # Intercept escapes
513 if closctx != null then
514 var els = v.escaped_labels
515 v.escaped_labels = old_el
516 # Is there possible escapes?
517 if not els.is_empty then
518 # Call in a tmp variable to avoid 'break' overwrite
519 var w = v.new_instr
520 if need_result then
521 w.add("tmp")
522 w.add(" = ")
523 w.append(call)
524 w.add(";\n")
525 res = new Writer
526 res.add("tmp")
527 else
528 res = null
529 w.append(call)
530 w.add(";\n")
531 end
532 # What are the expected escape indexes
533 v.new_instr.add("switch (").add(closctx).add("->has_broke) \{\n")
534 v.indent
535 # No escape occured, continue as usual
536 v.add_instr("case 0: break;")
537 var lls = v.local_labels
538 var iels = els.iterator
539 var forward_escape = false
540 while iels.is_ok do
541 var seq = iels.key
542 if lls.has(seq) then
543 # Local escape occured
544 # Clear the has_broke information and go to the target
545 v.new_instr.add("case ").add(iels.item.to_s).add(": ").add(closctx).add("->has_broke = 0; goto ").add(v.lab(seq)).add(";\n")
546 else
547 # Forward escape occured: register the escape label
548 assert v.closure
549 v.register_escape_label(seq)
550 forward_escape = true
551 end
552 iels.next
553 end
554 # If forward escape occured, just pass to the next one
555 if forward_escape then
556 # Do not need to copy 'has_broke' value since it is shared by the next one.
557 # So just exit the C function.
558 v.new_instr.add("default: goto ").add(v.lab(v.return_label.as(not null))).add(";\n")
559 end
560 v.unindent
561 v.add_instr("\}")
562 end
563 end
564
565 if res != null then
566 var w = new_result(v)
567 w.append(res)
568 end
569 end
570
571 # The single invocation witout fancy stuffs
572 private fun compile_call_to_c(v: I2CCompilerVisitor, args: Array[String]): Writer is abstract
573 end
574
575 redef class ICall
576 redef fun compile_call_to_c(v, args)
577 do
578 var w = new Writer
579 var prop = property
580 if prop.global.is_init then args.add("init_table")
581 w.add(prop.global.meth_call)
582 w.add("(")
583 w.add(args.first)
584 w.add(")(")
585 w.add_all(args, ", ")
586 w.add(")")
587 return w
588 end
589 end
590
591 redef class ISuper
592 redef fun compile_call_to_c(v, args)
593 do
594 var prop = property
595 if prop.global.is_init then args.add("init_table")
596 var w = new Writer
597 w.add(prop.super_meth_call)
598 w.add("(")
599 w.add(args.first)
600 w.add(")(")
601 w.add_all(args, ", ")
602 w.add(")")
603 return w
604 end
605 end
606
607 redef class INew
608 redef fun compile_call_to_c(v, args)
609 do
610 var w = new Writer
611 w.add("NEW_")
612 w.add(stype.local_class.to_s)
613 w.add("_")
614 w.add(property.global.intro.cname)
615 w.add("(")
616 w.add_all(args, ", ")
617 w.add(")")
618 return w
619 end
620 end
621
622 redef class IAllocateInstance
623 redef fun compile_to_c(v)
624 do
625 v.add_location(location)
626 var w = new_result(v)
627 w.add("NEW_")
628 w.add(stype.local_class.cname)
629 w.add("()")
630 end
631 end
632
633 redef class ICheckInstance
634 redef fun compile_to_c(v)
635 do
636 v.add_location(location)
637 var w = new_result(v)
638 w.add("CHECKNEW_")
639 w.add(stype.local_class.cname)
640 w.add("(")
641 w.add(v.register(expr))
642 w.add(")")
643 end
644 end
645
646 redef class IInitAttributes
647 redef fun compile_to_c(v)
648 do
649 v.add_location(location)
650 var w = v.new_instr
651 w.add("INIT_ATTRIBUTES__")
652 w.add(stype.local_class.cname)
653 w.add("(")
654 w.add(v.register(expr))
655 w.add(");\n")
656 end
657 end
658
659 redef class IStaticCall
660 redef fun compile_call_to_c(v, args)
661 do
662 var prop = property
663 if prop.global.is_init then args.add("init_table")
664 var w = new Writer
665 w.add(property.cname)
666 w.add("(")
667 w.add_all(args, ", ")
668 w.add(")")
669 return w
670 end
671 end
672
673 redef class INative
674 redef fun compile_to_c(v)
675 do
676 v.add_location(location)
677 if method.is_intern then
678 compile_intern_method_to_c(v)
679 else
680 compile_extern_method_to_c(v)
681 end
682 end
683
684 fun compile_extern_method_to_c(v: I2CCompilerVisitor)
685 do
686 var ename = method.extern_name.as(not null)#"{method.module.name}_{method.local_class.name}_{method.local_class.name}_{method.name}_{method.signature.arity}"
687 var sig = method.signature
688 assert exprs.length == sig.arity + 1
689
690 var regs = v.registers(exprs)
691
692 var args = new Array[String]
693 args.add(sig.recv.unboxtype(regs[0]))
694 for i in [0..sig.arity[ do
695 args.add(sig[i].unboxtype(regs[i+1]))
696 end
697 var s = "{ename}({args.join(", ")})"
698
699 if need_result then s = sig.return_type.boxtype(s)
700 var w = new_result(v)
701 w.add(s)
702 end
703
704 fun compile_intern_method_to_c(v: I2CCompilerVisitor)
705 do
706 var sig = method.signature
707 assert exprs.length == sig.arity + 1
708 var c = method.local_class.name
709 var n = method.name
710 var regs = v.registers(exprs)
711 var s: nullable String = null
712 if c == once "Int".to_symbol then
713 if n == once "object_id".to_symbol then
714 s = regs[0]
715 else if n == once "unary -".to_symbol then
716 s = "TAG_Int(-UNTAG_Int({regs[0]}))"
717 else if n == once "output".to_symbol then
718 s = "printf(\"%ld\\n\", UNTAG_Int({regs[0]}));"
719 else if n == once "ascii".to_symbol then
720 s = "TAG_Char(UNTAG_Int({regs[0]}))"
721 else if n == once "succ".to_symbol then
722 s = "TAG_Int(UNTAG_Int({regs[0]})+1)"
723 else if n == once "prec".to_symbol then
724 s = "TAG_Int(UNTAG_Int({regs[0]})-1)"
725 else if n == once "to_f".to_symbol then
726 s = "BOX_Float((float)UNTAG_Int({regs[0]}))"
727 else if n == once "+".to_symbol then
728 s = "TAG_Int(UNTAG_Int({regs[0]})+UNTAG_Int({regs[1]}))"
729 else if n == once "-".to_symbol then
730 s = "TAG_Int(UNTAG_Int({regs[0]})-UNTAG_Int({regs[1]}))"
731 else if n == once "*".to_symbol then
732 s = "TAG_Int(UNTAG_Int({regs[0]})*UNTAG_Int({regs[1]}))"
733 else if n == once "/".to_symbol then
734 s = "TAG_Int(UNTAG_Int({regs[0]})/UNTAG_Int({regs[1]}))"
735 else if n == once "%".to_symbol then
736 s = "TAG_Int(UNTAG_Int({regs[0]})%UNTAG_Int({regs[1]}))"
737 else if n == once "<".to_symbol then
738 s = "TAG_Bool(UNTAG_Int({regs[0]})<UNTAG_Int({regs[1]}))"
739 else if n == once ">".to_symbol then
740 s = "TAG_Bool(UNTAG_Int({regs[0]})>UNTAG_Int({regs[1]}))"
741 else if n == once "<=".to_symbol then
742 s = "TAG_Bool(UNTAG_Int({regs[0]})<=UNTAG_Int({regs[1]}))"
743 else if n == once ">=".to_symbol then
744 s = "TAG_Bool(UNTAG_Int({regs[0]})>=UNTAG_Int({regs[1]}))"
745 else if n == once "lshift".to_symbol then
746 s = "TAG_Int(UNTAG_Int({regs[0]})<<UNTAG_Int({regs[1]}))"
747 else if n == once "rshift".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_Bool(({regs[0]})==({regs[1]}))"
751 else if n == once "!=".to_symbol then
752 s = "TAG_Bool(({regs[0]})!=({regs[1]}))"
753 end
754 else if c == once "Float".to_symbol then
755 if n == once "object_id".to_symbol then
756 s = "TAG_Int((bigint)UNBOX_Float({regs[0]}))"
757 else if n == once "unary -".to_symbol then
758 s = "BOX_Float(-UNBOX_Float({regs[0]}))"
759 else if n == once "output".to_symbol then
760 s = "printf(\"%f\\n\", UNBOX_Float({regs[0]}));"
761 else if n == once "to_i".to_symbol then
762 s = "TAG_Int((bigint)UNBOX_Float({regs[0]}))"
763 else if n == once "+".to_symbol then
764 s = "BOX_Float(UNBOX_Float({regs[0]})+UNBOX_Float({regs[1]}))"
765 else if n == once "-".to_symbol then
766 s = "BOX_Float(UNBOX_Float({regs[0]})-UNBOX_Float({regs[1]}))"
767 else if n == once "*".to_symbol then
768 s = "BOX_Float(UNBOX_Float({regs[0]})*UNBOX_Float({regs[1]}))"
769 else if n == once "/".to_symbol then
770 s = "BOX_Float(UNBOX_Float({regs[0]})/UNBOX_Float({regs[1]}))"
771 else if n == once "<".to_symbol then
772 s = "TAG_Bool(UNBOX_Float({regs[0]})<UNBOX_Float({regs[1]}))"
773 else if n == once ">".to_symbol then
774 s = "TAG_Bool(UNBOX_Float({regs[0]})>UNBOX_Float({regs[1]}))"
775 else if n == once "<=".to_symbol then
776 s = "TAG_Bool(UNBOX_Float({regs[0]})<=UNBOX_Float({regs[1]}))"
777 else if n == once ">=".to_symbol then
778 s = "TAG_Bool(UNBOX_Float({regs[0]})>=UNBOX_Float({regs[1]}))"
779 end
780 else if c == once "Char".to_symbol then
781 if n == once "object_id".to_symbol then
782 s = "TAG_Int(UNTAG_Char({regs[0]}))"
783 else if n == once "unary -".to_symbol then
784 s = "TAG_Char(-UNTAG_Char({regs[0]}))"
785 else if n == once "output".to_symbol then
786 s = "printf(\"%c\", (unsigned char)UNTAG_Char({regs[0]}));"
787 else if n == once "ascii".to_symbol then
788 s = "TAG_Int((unsigned char)UNTAG_Char({regs[0]}))"
789 else if n == once "succ".to_symbol then
790 s = "TAG_Char(UNTAG_Char({regs[0]})+1)"
791 else if n == once "prec".to_symbol then
792 s = "TAG_Char(UNTAG_Char({regs[0]})-1)"
793 else if n == once "to_i".to_symbol then
794 s = "TAG_Int(UNTAG_Char({regs[0]})-'0')"
795 else if n == once "+".to_symbol then
796 s = "TAG_Char(UNTAG_Char({regs[0]})+UNTAG_Char({regs[1]}))"
797 else if n == once "-".to_symbol then
798 s = "TAG_Char(UNTAG_Char({regs[0]})-UNTAG_Char({regs[1]}))"
799 else if n == once "*".to_symbol then
800 s = "TAG_Char(UNTAG_Char({regs[0]})*UNTAG_Char({regs[1]}))"
801 else if n == once "/".to_symbol then
802 s = "TAG_Char(UNTAG_Char({regs[0]})/UNTAG_Char({regs[1]}))"
803 else if n == once "%".to_symbol then
804 s = "TAG_Char(UNTAG_Char({regs[0]})%UNTAG_Char({regs[1]}))"
805 else if n == once "<".to_symbol then
806 s = "TAG_Bool(UNTAG_Char({regs[0]})<UNTAG_Char({regs[1]}))"
807 else if n == once ">".to_symbol then
808 s = "TAG_Bool(UNTAG_Char({regs[0]})>UNTAG_Char({regs[1]}))"
809 else if n == once "<=".to_symbol then
810 s = "TAG_Bool(UNTAG_Char({regs[0]})<=UNTAG_Char({regs[1]}))"
811 else if n == once ">=".to_symbol then
812 s = "TAG_Bool(UNTAG_Char({regs[0]})>=UNTAG_Char({regs[1]}))"
813 else if n == once "==".to_symbol then
814 s = "TAG_Bool(({regs[0]})==({regs[1]}))"
815 else if n == once "!=".to_symbol then
816 s = "TAG_Bool(({regs[0]})!=({regs[1]}))"
817 end
818 else if c == once "Bool".to_symbol then
819 if n == once "object_id".to_symbol then
820 s = "TAG_Int(UNTAG_Bool({regs[0]}))"
821 else if n == once "unary -".to_symbol then
822 s = "TAG_Bool(-UNTAG_Bool({regs[0]}))"
823 else if n == once "output".to_symbol then
824 s = "(void)printf(UNTAG_Bool({regs[0]})?\"true\\n\":\"false\\n\");"
825 else if n == once "ascii".to_symbol then
826 s = "TAG_Bool(UNTAG_Bool({regs[0]}))"
827 else if n == once "to_i".to_symbol then
828 s = "TAG_Int(UNTAG_Bool({regs[0]}))"
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 "NativeArray".to_symbol then
835 if n == once "object_id".to_symbol then
836 s = "TAG_Int(((Nit_NativeArray){regs[0]})->object_id)"
837 else if n == once "[]".to_symbol then
838 s = "((Nit_NativeArray){regs[0]})->val[UNTAG_Int({regs[1]})]"
839 else if n == once "[]=".to_symbol then
840 s = "((Nit_NativeArray){regs[0]})->val[UNTAG_Int({regs[1]})]={regs[2]}"
841 else if n == once "copy_to".to_symbol then
842 s = "(void)memcpy(((Nit_NativeArray ){regs[1]})->val, ((Nit_NativeArray){regs[0]})->val, UNTAG_Int({regs[2]})*sizeof(val_t))"
843 end
844 else if c == once "NativeString".to_symbol then
845 if n == once "object_id".to_symbol then
846 s = "TAG_Int(UNBOX_NativeString({regs[0]}))"
847 else if n == once "atoi".to_symbol then
848 s = "TAG_Int(atoi(UNBOX_NativeString({regs[0]})))"
849 else if n == once "[]".to_symbol then
850 s = "TAG_Char(UNBOX_NativeString({regs[0]})[UNTAG_Int({regs[1]})])"
851 else if n == once "[]=".to_symbol then
852 s = "UNBOX_NativeString({regs[0]})[UNTAG_Int({regs[1]})]=UNTAG_Char({regs[2]});"
853 else if n == once "copy_to".to_symbol then
854 s = "(void)memcpy(UNBOX_NativeString({regs[1]})+UNTAG_Int({regs[4]}), UNBOX_NativeString({regs[0]})+UNTAG_Int({regs[3]}), UNTAG_Int({regs[2]}));"
855 end
856 else if n == once "object_id".to_symbol then
857 s = "TAG_Int((bigint)((obj_t){regs[0]})[1].object_id)"
858 else if n == once "sys".to_symbol then
859 s = "(G_sys)"
860 else if n == once "is_same_type".to_symbol then
861 s = "TAG_Bool((VAL2VFT({regs[0]})==VAL2VFT({regs[1]})))"
862 else if n == once "exit".to_symbol then
863 s = "exit(UNTAG_Int({regs[1]}));"
864 else if n == once "calloc_array".to_symbol then
865 s = "NEW_NativeArray(UNTAG_Int({regs[1]}), sizeof(val_t))"
866 else if n == once "calloc_string".to_symbol then
867 s = "BOX_NativeString((char*)raw_alloc((UNTAG_Int({regs[1]}) * sizeof(char))))"
868 # Add output_class_name native implementation
869 else if n == once "output_class_name".to_symbol then
870 s = "printf(\"%s\\n\", VAL2VFT({regs[0]})[2].cname);"
871 # Add class_name implementation
872 else if n == once "native_class_name".to_symbol then
873 s = "BOX_NativeString(VAL2VFT({regs[0]})[2].cname);"
874 end
875
876 if s == null then
877 var ll = location
878 if ll != null then v.add_instr("fprintf(stderr, \"{ll.to_s}: \");")
879 v.add_instr("fprintf(stderr, \"Fatal error: unknown intern method {method.full_name}.\\n\");")
880 v.add_instr("nit_exit(1);")
881 s = "NIT_NULL"
882 end
883 if result == null then
884 v.new_instr.add(s).add(";\n")
885 else if need_result then
886 var w = new_result(v)
887 w.add(s)
888 end
889 end
890 end
891
892 redef class IIntValue
893 redef fun compile_to_c(v)
894 do
895 v.add_location(location)
896 var w = new_result(v)
897 w.add("TAG_Int(").add(value.to_s).add(")")
898 end
899 end
900
901 redef class IBoolValue
902 redef fun compile_to_c(v)
903 do
904 v.add_location(location)
905 var w = new_result(v)
906 w.add("TAG_Bool(")
907 if value then w.add("true") else w.add("false")
908 w.add(")")
909 end
910 end
911
912 redef class ICharValue
913 redef fun compile_to_c(v)
914 do
915 v.add_location(location)
916 var w = new_result(v)
917 w.add("TAG_Char(").add(value).add(")")
918 end
919 end
920
921 redef class IFloatValue
922 redef fun compile_to_c(v)
923 do
924 v.add_location(location)
925 var w = new_result(v)
926 w.add("BOX_Float(").add(value).add(")")
927 end
928 end
929
930 redef class IStringValue
931 redef fun compile_to_c(v)
932 do
933 v.add_location(location)
934 var w = new_result(v)
935 w.add("BOX_NativeString(\"").add(value).add("\")")
936 end
937 end
938
939 redef class IAbort
940 redef fun compile_to_c(v)
941 do
942 v.add_location(location)
943 var w = v.new_instr
944 w.add("nit_abort(\"")
945 w.add(texts[0])
946 if texts.length > 1 then
947 w.add("\", \"")
948 w.add(texts[1])
949 w.add("\"")
950 else
951 w.add("\", NULL")
952 end
953 w.add(", LOCATE_")
954 w.add(module_location.cname)
955 var ll = location
956 if ll != null then
957 w.add(", ")
958 w.add(ll.line_start.to_s)
959 else
960 w.add(", 0")
961 end
962 w.add(");\n")
963 end
964 end
965
966 redef class IMove
967 redef fun compile_to_c(v)
968 do
969 if not need_result then return
970 var e = v.register(expr)
971 var r = v.register(result.as(not null))
972 if e == r then return
973 v.add_location(location)
974 var w = v.new_instr
975 w.add(r)
976 w.add(" = ")
977 w.add(e)
978 w.add(";\n")
979 end
980 end
981
982 redef class IAttrRead
983 redef fun compile_to_c(v)
984 do
985 if not need_result then return
986 v.add_location(location)
987 var w = new_result(v)
988 w.add(property.global.attr_access)
989 w.add("(")
990 w.add(v.register(expr))
991 w.add(")")
992 end
993 end
994
995 redef class IAttrIsset
996 redef fun compile_to_c(v)
997 do
998 if not need_result then return
999 v.add_location(location)
1000 var w = new_result(v)
1001 w.add("TAG_Bool(")
1002 w.add(property.global.attr_access)
1003 w.add("(")
1004 w.add(v.register(expr))
1005 w.add(")!=NIT_NULL)")
1006 end
1007 end
1008
1009 redef class IAttrWrite
1010 redef fun compile_to_c(v)
1011 do
1012 v.add_location(location)
1013 var w = v.new_instr
1014 w.add(property.global.attr_access)
1015 w.add("(")
1016 w.add(v.register(expr1))
1017 w.add(") = ")
1018 w.add(v.register(expr2))
1019 w.add(";\n")
1020 end
1021 end
1022
1023 redef class ITypeCheck
1024 redef fun compile_to_c(v)
1025 do
1026 if not need_result then return
1027 v.add_location(location)
1028 var recv = v.register(expr2)
1029 var w = new_result(v)
1030 w.add("TAG_Bool(")
1031 if expr2.stype.is_nullable then
1032 if stype.is_nullable then
1033 w.add("(")
1034 w.add(recv)
1035 w.add("==NIT_NULL) || ")
1036 else if stype.as_nullable == expr2.stype then
1037 w.add(recv)
1038 w.add("!=NIT_NULL)")
1039 return
1040 else
1041 w.add("(")
1042 w.add(recv)
1043 w.add("!=NIT_NULL) && ")
1044 end
1045 end
1046 # FIXME handle formaltypes
1047 var t = stype
1048 if t isa MMVirtualType then
1049 var slf = v.register(expr1)
1050 var g = t.property.global
1051 w.add("VAL_ISA(")
1052 w.add(recv)
1053 w.add(", ")
1054 w.add(g.vt_class_color)
1055 w.add("(")
1056 w.add(slf)
1057 w.add(")")
1058 w.add(", ")
1059 w.add(g.vt_class_id)
1060 w.add("(")
1061 w.add(slf)
1062 w.add(")")
1063 w.add(")) /*cast ")
1064 w.add(t.to_s)
1065 w.add("*/")
1066 else
1067 var g = t.local_class.global
1068 w.add("VAL_ISA(")
1069 w.add(recv)
1070 w.add(", ")
1071 w.add(g.color_id)
1072 w.add(", ")
1073 w.add(g.id_id)
1074 w.add(")) /*cast ")
1075 w.add(t.to_s)
1076 w.add("*/")
1077 end
1078 end
1079 end
1080
1081 redef class IIs
1082 redef fun compile_to_c(v)
1083 do
1084 if not need_result then return
1085 v.add_location(location)
1086 var w = new_result(v)
1087 w.add("TAG_Bool(")
1088 var t1 = expr1.stype
1089 var t2 = expr2.stype
1090 if t1 isa MMTypeNone then
1091 if t2 isa MMTypeNone then
1092 w.add("1)")
1093 return
1094 else if t2.is_nullable then
1095 w.add(v.register(expr2))
1096 w.add("==NIT_NULL)")
1097 return
1098 else
1099 w.add("0)")
1100 return
1101 end
1102 else if t1.is_nullable then
1103 if t2 isa MMTypeNone then
1104 w.add(v.register(expr1))
1105 w.add("==NIT_NULL)")
1106 return
1107 else if t2.is_nullable then
1108 w.add("IS_EQUAL_NN(")
1109 else
1110 w.add("IS_EQUAL_ON(")
1111 w.add(v.register(expr2))
1112 w.add(",")
1113 w.add(v.register(expr1))
1114 w.add("))")
1115 return
1116 end
1117 else
1118 if t2 isa MMTypeNone then
1119 w.add("0)")
1120 return
1121 else if t2.is_nullable then
1122 w.add("IS_EQUAL_ON(")
1123 else
1124 w.add("IS_EQUAL_OO(")
1125 end
1126 end
1127 w.add(v.register(expr1))
1128 w.add(",")
1129 w.add(v.register(expr2))
1130 w.add("))")
1131 end
1132 end
1133
1134 redef class INot
1135 redef fun compile_to_c(v)
1136 do
1137 if not need_result then return
1138 v.add_location(location)
1139 var w = new_result(v)
1140 w.add("TAG_Bool(!UNTAG_Bool(")
1141 w.add(v.register(expr))
1142 w.add("))")
1143 end
1144 end
1145
1146 redef class IOnce
1147 redef fun compile_to_c(v)
1148 do
1149 v.add_location(location)
1150 var i = v.new_number
1151 var res = result.as(not null)
1152 if res.stype.is_nullable then
1153 v.add_decl("static val_t once_value_{i}; static int once_bool_{i}; /* Once value */")
1154 v.add_instr("if (!once_bool_{i}) \{")
1155 else
1156 # Since the value is not nullable, we use the null value to represent the boolean
1157 v.add_decl("static val_t once_value_{i}; /* Once value */")
1158 v.add_instr("if (!once_value_{i}) \{")
1159 end
1160 v.indent
1161 body.compile_to_c(v)
1162 var e = v.register(res)
1163 v.add_instr("once_value_{i} = {e};")
1164 v.add_instr("register_static_object(&once_value_{i});")
1165 if res.stype.is_nullable then v.add_instr("once_bool_{i} = true;")
1166 v.unindent
1167 v.add_instr("\} else {e} = once_value_{i};")
1168 var w = new_result(v)
1169 w.add(e)
1170 end
1171 end
1172
1173 redef class IClosCall
1174 redef fun compile_to_c(v: I2CCompilerVisitor)
1175 do
1176 v.add_location(location)
1177 var ivar: String
1178 var args: Array[String]
1179 if v.closure then
1180 ivar = "closctx->closure_funs[{v.closures[closure_decl]}]"
1181 args = ["closctx->closure_ctx"]
1182 else
1183 ivar = "CREG[{v.closures[closure_decl]}]"
1184 args = ["closctx_param"]
1185 end
1186 args.append(v.registers(exprs))
1187
1188 var s = "(({v.clostypes[closure_decl]})({ivar}))({args.join(", ")})"
1189 var w = new Writer
1190 w.add(s)
1191 store_result(v, w)
1192
1193 # Intercept escape
1194 v.add_instr("if ({args.first}->has_broke) \{")
1195 v.indent
1196 var bs = break_seq
1197 if bs != null then
1198 bs.compile_to_c(v)
1199 end
1200 v.add_goto(v.iroutine.body)
1201 v.unindent
1202 v.add_instr("\}")
1203 end
1204 end
1205
1206 redef class IHasClos
1207 redef fun compile_to_c(v)
1208 do
1209 if not need_result then return
1210 v.add_location(location)
1211 var w = new_result(v)
1212 w.add("TAG_Bool(")
1213 if v.closure then
1214 w.add("closctx->closure_funs[")
1215 w.add(v.closures[closure_decl])
1216 w.add("]")
1217 else
1218 w.add("CREG[")
1219 w.add(v.closures[closure_decl])
1220 w.add("]")
1221 end
1222 w.add(" != NULL)")
1223 end
1224 end
1225
1226 redef class IClosureDef
1227 # Compile the closure as a separate C function in the visitor out_contexts.
1228 # Return a fun_t pointer to the function.
1229 fun compile_closure(v: I2CCompilerVisitor): String
1230 do
1231 var cv = v.visitor
1232
1233 # We are now in a closure
1234 var cfc_old = v.closure
1235 v.closure = true
1236
1237 # We are now in a escape boundary
1238 var lls_old = v.local_labels
1239 v.local_labels = new HashSet[ISeq]
1240
1241 # We are now in a new C context
1242 var decl_writer_old = cv.decl_writer
1243 var writer_old = cv.writer
1244 cv.writer = cv.top_writer.sub
1245 cv.decl_writer = cv.header_writer.sub
1246
1247 # Generate the C function
1248 var cname = "OC_{v.basecname}_{v.new_number}"
1249 var args = compile_signature_to_c(v.visitor, cname, null, "struct stack_frame_t *closctx", null)
1250 cv.decl_writer = cv.writer.sub
1251
1252 var s = compile_inside_to_c(v, args)
1253 if s == null then
1254 v.add_instr("return;")
1255 else
1256 v.add_instr("return {s};")
1257 end
1258 v.unindent
1259 v.add_instr("\}")
1260
1261 # Restore things
1262 cv.writer = writer_old
1263 cv.decl_writer = decl_writer_old
1264 v.closure = cfc_old
1265 v.local_labels = lls_old
1266 return "((fun_t){cname})"
1267 end
1268 end