7a374d341802f788e301a058af7cf08b9895edb5
1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2009 Jean Privat <jean@pryen.org>
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 # Generate C code from intermediate code representation
18 package compiling_icode
21 private import analysis
24 # Compiler context from ICode to C
25 class I2CCompilerVisitor
27 var _ids
: HashMap[Object, String] = new HashMap[Object, String]
28 # Associate other things
29 var _ids2
: HashMap[Object, String] = new HashMap[Object, String]
31 # Return the string associated with a register
32 fun register
(e
: IRegister): String
34 if e
.stype
isa MMTypeNone then return "NIT_NULL"
36 if closure
and not e
.is_local
then ids
= _ids2
37 if ids
.has_key
(e
) then
42 # The register is dead
48 var strs
: HashMap[Int, String]
49 if e
.in_tag_slots
then
50 strs
= once
new HashMap[Int, String]
51 if not strs
.has_key
(i
) then strs
[i
] = "REGB{i}"
52 else if closure
and not e
.is_local
then
53 strs
= once
new HashMap[Int, String]
54 if not strs
.has_key
(i
) then strs
[i
] = "closctx->REG[{i}]"
56 strs
= once
new HashMap[Int, String]
57 if not strs
.has_key
(i
) then strs
[i
] = "fra.me.REG[{i}]"
66 # Return the strings associated with registers
67 fun registers
(a
: Collection[IRegister]): Array[String]
69 var r
= new Array[String].with_capacity
(a
.length
)
76 var _last_number
: Int = 0
77 # Give a new unique number (unique for the visitor)
84 # Return the string associated with a escape label
85 fun lab
(e
: ISeq): String
87 if _ids
.has_key
(e
) then
90 var s
= "label{new_number}"
96 # The rank (number) of each closure
97 readable var _closures
: HashMap[IClosureDecl, Int] = new HashMap[IClosureDecl, Int]
99 # The functionnal type of each closure
100 readable var _clostypes
: HashMap[IClosureDecl, String] = new HashMap[IClosureDecl, String]
102 # label locally accessibles
103 readable writable var _local_labels
: HashSet[ISeq] = new HashSet[ISeq]
105 # Not local escaped labels
106 # The integer value is an index identifying the label
107 readable writable var _escaped_labels
: HashMap[ISeq, Int] = new HashMap[ISeq, Int]
109 # Register a escape to a non local label and return an index identifying the label
110 fun register_escape_label
(e
: ISeq): Int
112 if _escaped_labels
.has_key
(e
) then
113 return _escaped_labels
[e
]
115 var res
= _escaped_labels
.length
+ 1
116 _escaped_labels
[e
] = res
121 # Add a C label mark (if needed)
122 fun add_label
(e
: ISeq)
124 if _ids
.has_key
(e
) then
125 add_instr
("{_ids[e]}: while(0);")
129 # Add a goto to a label (even outside a closure)
130 fun add_goto
(seq
: ISeq)
132 if local_labels
.has
(seq
) then
133 add_instr
("goto {lab(seq)};")
136 var ind
= register_escape_label
(seq
)
137 add_instr
("closctx->has_broke = {ind};")
138 add_instr
("goto {lab(return_label.as(not null))};")
142 # Are we in a closure ?
143 readable writable var _closure
: Bool = false
145 # The current compiler visitor
146 readable var _visitor
: CompilerVisitor
148 # The current compiled iroutine
149 readable var _iroutine
: IRoutine
151 # The return label of the current compiling C function
152 readable writable var _return_label
: nullable ISeq = null
154 fun add_decl
(s
: String)
159 fun add_instr
(s
: String)
161 var l
= _next_location
163 visitor
.add_instr
("/* ", l
.file
, ":", l
.line_start
.to_s
, " */")
164 _next_location
= null
179 fun add_assignment
(to
, from
: String)
181 visitor
.add_assignment
(to
, from
)
184 var _last_location
: nullable Location = null
185 var _next_location
: nullable Location = null
187 # Add location information in a comment
188 # Do nothing if the last location added is the same
189 fun add_location
(l
: nullable Location)
191 var last
= _last_location
192 if last
== l
or l
== null then return
194 if last
!= null and last
.file
== l
.file
and last
.line_start
== l
.line_start
then
201 # The C fonction name of the iroutine
202 readable var _basecname
: String
204 init(v
: CompilerVisitor, ir
: IRoutine, cname
: String)
213 # Declare and start a C function that match the routine
214 # Return what must be given to compile_inside_to_c or to compile_to_c
215 # After the method, an openinig { and and indent is added.
216 # So, do not forget to add a sub_context, to unintent and to add a closing }
217 fun compile_signature_to_c
(v
: CompilerVisitor, cname
: String, human_name
: nullable String, before_params
, after_params
: nullable String): Array[String]
219 var cargs
= new Array[String]
220 var cparams
= new Array[String]
221 if before_params
!= null then cparams
.add
(before_params
)
222 for i
in [0..params
.length
[ do
224 cparams
.add
("val_t p{i}")
226 if closure_decls
!= null then
227 cparams
.add
("struct stack_frame_t *closctx_param")
228 for i
in [0..closure_decls
.length
[ do
229 var closcn
= "CLOS_{cname}_{i}"
230 var cs
= closure_decls
[i
].closure
.signature
231 var subparams
= new Array[String] # Parameters of the closure
232 subparams
.add
("struct stack_frame_t *")
233 for j
in [0..cs
.arity
[ do
234 subparams
.add
("val_t")
237 if cs
.return_type
!= null then rr
= "val_t"
238 v
.add_decl
("typedef {rr} (*{closcn})({subparams.join(", ")});")
239 cargs
.add
("clos_fun{i}")
240 cparams
.add
("fun_t clos_fun{i}")
243 if after_params
!= null then cparams
.add
(after_params
)
245 if result
!= null then r
= "val_t"
247 if cparams
.is_empty
then
250 p
= cparams
.join
(", ")
252 if human_name
!= null then v
.add_decl
("#define LOCATE_", cname
, " \"", human_name, "\
"")
253 v
.add_decl
(r
, " ", cname
, "(", p
, ");")
254 v
.add_decl
("typedef ", r
, " (*", cname
, "_t)(", p
, ");")
255 v
.add_instr
(r
, " ", cname
, "(", p
, ")\{")
260 # Compile the body of the routine, return the result value is any
261 fun compile_inside_to_c
(v
: I2CCompilerVisitor, args
: Array[String]): nullable String
263 # Create and push the stack frame
265 if location
!= null then
266 ll
= location
.line_start
268 # Encapsulate the frame ('me') in a larger structure ('fra') that has enough space to store the local variables (REG)
269 if std_slots_nb
> 1 then
270 v
.add_decl
("struct \{struct stack_frame_t me; val_t MORE_REG[{std_slots_nb-1}];\} fra;")
272 v
.add_decl
("struct \{struct stack_frame_t me;\} fra;")
274 v
.add_instr
("fra.me.prev = stack_frame_head; stack_frame_head = &fra.me;")
275 v
.add_instr
("fra.me.file = LOCATE_{v.visitor.module.name};")
276 v
.add_instr
("fra.me.line = {ll};")
277 v
.add_instr
("fra.me.meth = LOCATE_{v.basecname};")
278 v
.add_instr
("fra.me.has_broke = 0;")
279 v
.add_instr
("fra.me.REG_size = {std_slots_nb};")
281 # Declare/initialize local variables
282 for i
in [0..std_slots_nb
[ do
283 v
.add_instr
("fra.me.REG[{i}] = NIT_NULL;")
285 for i
in [0..tag_slots_nb
[ do
286 v
.add_decl
("val_t REGB{i};")
288 var iclosdecls
= closure_decls
289 if iclosdecls
!= null then
290 v
.add_decl
("fun_t CREG[{iclosdecls.length}];")
291 v
.add_instr
("fra.me.closure_ctx = closctx_param;")
292 v
.add_instr
("fra.me.closure_funs = CREG;")
296 if r
.slot_index
!= null then v
.add_assignment
(v
.register
(r
), args
[k
])
299 if iclosdecls
!= null then
300 for i
in [0..iclosdecls
.length
[ do
301 var iclosdecl
= iclosdecls
[i
]
302 v
.add_instr
("CREG[{i}] = {args[params.length+i]};")
303 v
.closures
[iclosdecl
] = i
304 var cs
= iclosdecl
.closure
.signature
# Closure signature
305 var subparams
= new Array[String] # Parameters of the closure
306 subparams
.add
("struct stack_frame_t *")
307 for j
in [0..cs
.arity
[ do
312 if cs
.return_type
!= null then r
= "val_t"
313 v
.clostypes
[iclosdecl
] = "{r} (*)({subparams.join(", ")})"
316 v
.add_decl
("val_t tmp;")
319 var old_rl
= v
.return_label
320 v
.return_label
= body
325 v
.add_instr
("stack_frame_head = fra.me.prev;")
326 v
.return_label
= old_rl
335 # Full compilation of the routine
336 # Including optimization and other stuff.
337 # cv must be in the correct function
338 fun compile_to_c
(cv
: CompilerVisitor, cname
: String, args
: Array[String]): nullable String
341 var v
= new I2CCompilerVisitor(cv
, self, cname
)
342 return compile_inside_to_c
(v
, args
)
347 # Full compilation of the icode
348 fun compile_to_c
(v
: I2CCompilerVisitor)
350 v
.add_location
(location
)
351 store_result
(v
, inner_compile_to_c
(v
))
354 # Is a result really needed
355 private fun need_result
: Bool
358 return r
!= null and r
.slot_index
!= null
361 # Store s in the result value of self
362 private fun store_result
(v
: I2CCompilerVisitor, s
: nullable String)
365 if r
!= null and r
.slot_index
!= null then
367 v
.add_assignment
(v
.register
(r
), s
)
368 else if s
!= null and not is_pure
then
369 # ICode with side effects must be evaluated
370 # even if the result is not wanted
375 # Compilation of without the result assigment
376 # Return the right value is case of expression
377 # Return the full expression (witout ;) in case of statement
378 private fun inner_compile_to_c
(v
: I2CCompilerVisitor): nullable String is abstract
382 redef fun inner_compile_to_c
(v
)
384 v
.local_labels
.add
(self)
394 redef fun inner_compile_to_c
(v
)
396 v
.add_instr
("if (UNTAG_Bool({v.register(expr)})) \{")
397 if not then_seq
.icodes
.is_empty
then
399 then_seq
.inner_compile_to_c
(v
)
402 if not else_seq
.icodes
.is_empty
then
403 v
.add_instr
("} else \{")
405 else_seq
.inner_compile_to_c
(v
)
414 redef fun inner_compile_to_c
(v
)
416 v
.local_labels
.add
(self)
417 v
.add_instr
("while(1) \{")
430 redef fun inner_compile_to_c
(v
)
438 redef fun compile_to_c
(v
)
440 v
.add_location
(location
)
441 var args
= v
.registers
(exprs
)
443 # Compile closure definitions
444 var old_el
= v
.escaped_labels
445 var closdefs
= closure_defs
446 var closctx
: nullable String = null # The closure context of closdefs
447 if closdefs
!= null then
448 # Get the closure context
452 closctx
= "(&(fra.me))"
455 # First aditionnal arguments is the closure context
458 # We are in a new escape boundary
459 v
.escaped_labels
= new HashMap[ISeq, Int]
461 # Compile each closures and add each sub-function as an other additionnal parameter
462 for cd
in closdefs
do
464 var cn
= cd
.compile_closure
(v
)
472 # Compile the real call
473 var s
= compile_call_to_c
(v
, args
)
474 var r
: nullable String = s
477 if closctx
!= null then
478 var els
= v
.escaped_labels
479 v
.escaped_labels
= old_el
480 # Is there possible escapes?
481 if not els
.is_empty
then
482 # Call in a tmp variable to avoid 'break' overwrite
485 v
.add_assignment
(r
, s
)
490 # What are the expected escape indexes
491 v
.add_instr
("switch ({closctx}->has_broke) \{")
493 # No escape occured, continue as usual
494 v
.add_instr
("case 0: break;")
495 var lls
= v
.local_labels
496 var iels
= els
.iterator
497 var forward_escape
= false
501 # Local escape occured
502 # Clear the has_broke information and go to the target
503 v
.add_instr
("case {iels.item}: {closctx}->has_broke = 0; goto {v.lab(seq)};")
505 # Forward escape occured: register the escape label
507 v
.register_escape_label
(seq
)
508 forward_escape
= true
512 # If forward escape occured, just pass to the next one
513 if forward_escape
then
514 # Do not need to copy 'has_broke' value since it is shared by the next one.
515 # So just exit the C function.
516 v
.add_instr
("default: goto {v.lab(v.return_label.as(not null))};")
526 redef fun inner_compile_to_c
(v
) do abort
528 # The single invocation witout fancy stuffs
529 private fun compile_call_to_c
(v
: I2CCompilerVisitor, args
: Array[String]): String is abstract
533 redef fun compile_call_to_c
(v
, args
)
536 if prop
.global
.is_init
then args
.add
("init_table")
537 if prop
.name
== (once
("add".to_symbol
)) and prop
.local_class
.name
== (once
("Array".to_symbol
)) then
538 return "{prop.cname}({args.join(", ")})"
540 return "{prop.global.meth_call}({args[0]})({args.join(", ")})"
546 redef fun compile_call_to_c
(v
, args
)
549 if prop
.global
.is_init
then args
.add
("init_table")
550 return "{prop.super_meth_call}({args[0]})({args.join(", ")})"
555 redef fun compile_call_to_c
(v
, args
)
557 return "NEW_{stype.local_class}_{property.global.intro.cname}({args.join(", ")})"
562 redef fun inner_compile_to_c
(v
)
564 if exprs
.is_empty
then
569 var c
= code
.split_with
("@@@")
572 if i
< exprs
.length
and i
< c
.length-1
then
573 res
.append
(v
.register
(exprs
[i
]))
583 redef fun inner_compile_to_c
(v
)
585 var s
= new Buffer.from
("fprintf(stderr")
587 s
.append
(", \"{t}\
"")
593 s
= new Buffer.from
("fprintf(stderr, \" (%s
")
597 s.append(")\\n\
", LOCATE_{module_location.name}")
599 s
.append
(", {ll.line_start}")
604 v
.add_instr
("nit_exit(1);")
610 redef fun inner_compile_to_c
(v
)
612 return v
.register
(expr
)
616 redef class IAttrRead
617 redef fun inner_compile_to_c
(v
)
619 return "{property.global.attr_access}({v.register(expr)})"
623 redef class IAttrIsset
624 redef fun inner_compile_to_c
(v
)
626 return "TAG_Bool({property.global.attr_access}({v.register(expr)})!=NIT_NULL)"
630 redef class IAttrWrite
631 redef fun inner_compile_to_c
(v
)
633 v
.add_instr
("{property.global.attr_access}({v.register(expr1)}) = {v.register(expr2)};")
638 redef class ITypeCheck
639 redef fun inner_compile_to_c
(v
)
641 # FIXME handle formaltypes
642 var g
= stype
.local_class
.global
643 var recv
= v
.register
(expr
)
645 if expr
.stype
.is_nullable
then
646 if stype
.is_nullable
then
647 s
= "({recv}==NIT_NULL) || "
648 else if stype
.as_nullable
== expr
.stype
then
649 return "TAG_Bool({recv}!=NIT_NULL)"
651 s
= "({recv}!=NIT_NULL) && "
654 return "TAG_Bool({s}VAL_ISA({recv}, {g.color_id}, {g.id_id})) /*cast {stype}*/"
659 redef fun inner_compile_to_c
(v
)
663 if t1
isa MMTypeNone then
664 if t2
isa MMTypeNone then
666 else if t2
.is_nullable
then
667 return "TAG_Bool({v.register(expr2)}==NIT_NULL)"
671 else if t1
.is_nullable
then
672 if t2
isa MMTypeNone then
673 return "TAG_Bool({v.register(expr1)}==NIT_NULL)"
674 else if t2
.is_nullable
then
675 return "TAG_Bool(IS_EQUAL_NN({v.register(expr1)},{v.register(expr2)}))"
677 return "TAG_Bool(IS_EQUAL_ON({v.register(expr2)},{v.register(expr1)}))"
680 if t2
isa MMTypeNone then
682 else if t2
.is_nullable
then
683 return "TAG_Bool(IS_EQUAL_ON({v.register(expr1)},{v.register(expr2)}))"
685 return "TAG_Bool(IS_EQUAL_OO({v.register(expr1)},{v.register(expr2)}))"
692 redef fun inner_compile_to_c
(v
)
694 return "TAG_Bool(!UNTAG_Bool({v.register(expr)}))"
699 redef fun inner_compile_to_c
(v
)
702 var res
= result
.as(not null)
703 if res
.stype
.is_nullable
then
704 v
.add_decl
("static val_t once_value_{i}; static int once_bool_{i}; /* Once value */")
705 v
.add_instr
("if (!once_bool_{i}) \{")
707 # Since the value is not nullable, we use the null value to represent the boolean
708 v
.add_decl
("static val_t once_value_{i}; /* Once value */")
709 v
.add_instr
("if (!once_value_{i}) \{")
713 var e
= v
.register
(result
.as(not null))
714 v
.add_instr
("once_value_{i} = {e};")
715 v
.add_instr
("register_static_object(&once_value_{i});")
716 if res
.stype
.is_nullable
then v
.add_instr
("once_bool_{i} = true;")
718 v
.add_instr
("} else {e} = once_value_{i};")
723 redef class IClosCall
724 redef fun compile_to_c
(v
: I2CCompilerVisitor)
726 v
.add_location
(location
)
728 var args
: Array[String]
730 ivar
= "closctx->closure_funs[{v.closures[closure_decl]}]"
731 args
= ["closctx->closure_ctx"]
733 ivar
= "CREG[{v.closures[closure_decl]}]"
734 args
= ["closctx_param"]
736 args
.append
(v
.registers
(exprs
))
738 var s
= "(({v.clostypes[closure_decl]})({ivar}))({args.join(", ")})"
742 v
.add_instr
("if ({args.first}->has_broke) \{")
748 v
.add_goto
(v
.iroutine
.body
)
753 redef fun inner_compile_to_c
(v
) do abort
757 redef fun inner_compile_to_c
(v
)
761 ivar
= "closctx->closure_funs[{v.closures[closure_decl]}]"
763 ivar
= "CREG[{v.closures[closure_decl]}]"
765 return "TAG_Bool({ivar} != NULL)"
769 redef class IClosureDef
770 # Compile the closure as a separate C function in the visitor out_contexts.
771 # Return a fun_t pointer to the function.
772 fun compile_closure
(v
: I2CCompilerVisitor): String
776 # We are now in a closure
777 var cfc_old
= v
.closure
780 # We are now in a escape boundary
781 var lls_old
= v
.local_labels
782 v
.local_labels
= new HashSet[ISeq]
784 # We are now in a new C context
786 cv
.ctx
= new CContext
787 cv
.out_contexts
.add
(cv
.ctx
)
789 # Generate the C function
790 var cname
= "OC_{v.basecname}_{v.new_number}"
791 var args
= compile_signature_to_c
(v
.visitor
, cname
, null, "struct stack_frame_t *closctx", null)
792 var ctx_old2
= cv
.ctx
793 cv
.ctx
= new CContext
794 var s
= compile_inside_to_c
(v
, args
)
796 v
.add_instr
("return;")
798 v
.add_instr
("return {s};")
800 ctx_old2
.append
(cv
.ctx
)
808 v
.local_labels
= lls_old
809 return "((fun_t){cname})"