7902aeac19bfffdfa9b9273eef57c2976b38fc72
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->variable[{i}]"
56 strs
= once
new HashMap[Int, String]
57 if not strs
.has_key
(i
) then strs
[i
] = "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 = (val_t*){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 for i
in [0..closure_decls
.length
[ do
228 var closcn
= "CLOS_{cname}_{i}"
229 var cs
= closure_decls
[i
].closure
.signature
230 var subparams
= new Array[String] # Parameters of the closure
231 subparams
.add
("struct WBT_ *")
232 for j
in [0..cs
.arity
[ do
233 subparams
.add
("val_t")
236 if cs
.return_type
!= null then rr
= "val_t"
237 v
.add_decl
("typedef {rr} (*{closcn})({subparams.join(", ")});")
239 cparams
.add
("struct WBT_ *wd{i}")
242 if after_params
!= null then cparams
.add
(after_params
)
244 if result
!= null then r
= "val_t"
246 if cparams
.is_empty
then
249 p
= cparams
.join
(", ")
251 if human_name
!= null then v
.add_decl
("#define LOCATE_", cname
, " \"", human_name, "\
"")
252 v
.add_decl
(r
, " ", cname
, "(", p
, ");")
253 v
.add_decl
("typedef ", r
, " (*", cname
, "_t)(", p
, ");")
254 v
.add_instr
(r
, " ", cname
, "(", p
, ")\{")
259 # Compile the body of the routine, return the result value is any
260 fun compile_inside_to_c
(v
: I2CCompilerVisitor, args
: Array[String]): nullable String
264 if location
!= null then
265 ll
= location
.line_start
267 v
.add_decl
("struct trace_t trace = \{NULL, NULL, {ll}, LOCATE_{v.basecname}\};")
268 v
.add_instr
("trace.prev = tracehead; tracehead = &trace;")
269 v
.add_instr
("trace.file = LOCATE_{v.visitor.module.name};")
271 # Add local variables
272 if std_slots_nb
== 0 then
273 v
.add_decl
("val_t *REG = NULL;")
275 var init_vals
= new Buffer
276 init_vals
.append
"val_t REG[{std_slots_nb}] = \{ NIT_NULL"
277 for i
in [1..std_slots_nb
[ do init_vals
.append
(", NIT_NULL")
278 init_vals
.append
" \};"
279 v
.add_decl
(init_vals
.to_s
)
281 for i
in [0..tag_slots_nb
[ do
282 v
.add_decl
("val_t REGB{i};")
284 var iclosdecls
= closure_decls
285 if iclosdecls
!= null then
286 v
.add_decl
("struct WBT_ *CREG[{iclosdecls.length}];")
288 v
.add_decl
("struct WBT_ **CREG = NULL;")
292 if r
.slot_index
!= null then v
.add_assignment
(v
.register
(r
), args
[k
])
295 if iclosdecls
!= null then
296 for i
in [0..iclosdecls
.length
[ do
297 var iclosdecl
= iclosdecls
[i
]
298 v
.add_instr
("CREG[{i}] = {args[params.length+i]};")
299 v
.closures
[iclosdecl
] = i
300 var cs
= iclosdecl
.closure
.signature
# Closure signature
301 var subparams
= new Array[String] # Parameters of the closure
302 subparams
.add
("struct WBT_ *")
303 for j
in [0..cs
.arity
[ do
308 if cs
.return_type
!= null then r
= "val_t"
309 v
.clostypes
[iclosdecl
] = "{r} (*)({subparams.join(", ")})"
312 v
.add_decl
("val_t tmp;")
315 var old_rl
= v
.return_label
316 v
.return_label
= body
321 v
.add_instr
("tracehead = trace.prev;")
322 v
.return_label
= old_rl
331 # Full compilation of the routine
332 # Including optimization and other stuff.
333 # cv must be in the correct function
334 fun compile_to_c
(cv
: CompilerVisitor, cname
: String, args
: Array[String]): nullable String
337 var v
= new I2CCompilerVisitor(cv
, self, cname
)
338 return compile_inside_to_c
(v
, args
)
343 # Full compilation of the icode
344 fun compile_to_c
(v
: I2CCompilerVisitor)
346 v
.add_location
(location
)
347 store_result
(v
, inner_compile_to_c
(v
))
350 # Is a result really needed
351 private fun need_result
: Bool
354 return r
!= null and r
.slot_index
!= null
357 # Store s in the result value of self
358 private fun store_result
(v
: I2CCompilerVisitor, s
: nullable String)
361 if r
!= null and r
.slot_index
!= null then
363 v
.add_assignment
(v
.register
(r
), s
)
364 else if s
!= null and not is_pure
then
365 # ICode with side effects must be evaluated
366 # even if the result is not wanted
371 # Compilation of without the result assigment
372 # Return the right value is case of expression
373 # Return the full expression (witout ;) in case of statement
374 private fun inner_compile_to_c
(v
: I2CCompilerVisitor): nullable String is abstract
378 redef fun inner_compile_to_c
(v
)
380 v
.local_labels
.add
(self)
390 redef fun inner_compile_to_c
(v
)
392 v
.add_instr
("if (UNTAG_Bool({v.register(expr)})) \{")
393 if not then_seq
.icodes
.is_empty
then
395 then_seq
.inner_compile_to_c
(v
)
398 if not else_seq
.icodes
.is_empty
then
399 v
.add_instr
("} else \{")
401 else_seq
.inner_compile_to_c
(v
)
410 redef fun inner_compile_to_c
(v
)
412 v
.local_labels
.add
(self)
413 v
.add_instr
("while(1) \{")
426 redef fun inner_compile_to_c
(v
)
434 redef fun compile_to_c
(v
)
436 v
.add_location
(location
)
437 var args
= v
.registers
(exprs
)
439 # Compile closure definitions
440 var old_el
= v
.escaped_labels
441 var closdefs
= closure_defs
442 var closcns
: nullable Array[String] = null
443 if closdefs
!= null then
444 v
.escaped_labels
= new HashMap[ISeq, Int]
445 closcns
= new Array[String]
446 for cd
in closdefs
do
448 var cn
= cd
.compile_closure
(v
)
457 var s
= compile_call_to_c
(v
, args
)
458 var r
: nullable String = s
461 if closcns
!= null then
462 var els
= v
.escaped_labels
463 v
.escaped_labels
= old_el
464 # Is there possible escapes?
465 if not els
.is_empty
then
466 # Call in a tmp variable to avoid 'break' overwrite
469 v
.add_assignment
(r
, s
)
474 # What is the escape index (if any?)
475 # It's computed as the union of has_broke
476 var switcha
= new Array[String]
478 switcha
.add
("((int)({cn}->has_broke))")
480 var switch
= switcha
.join
(" | ")
481 # What are the expected escape indexes
482 v
.add_instr
("switch ({switch}) \{")
484 # No escape occured, continue as usual
485 v
.add_instr
("case 0: break;")
486 var lls
= v
.local_labels
487 var iels
= els
.iterator
488 var forward_escape
= false
492 # Local escape occured
493 v
.add_instr
("case {iels.item}: goto {v.lab(seq)};")
495 # Forward escape occured: register the escape label
497 v
.register_escape_label
(seq
)
498 forward_escape
= true
502 # Forward escape occured, just pass to the next one
503 if forward_escape
then
504 v
.add_instr
("default: closctx->has_broke = (val_t*)({switch}); goto {v.lab(v.return_label.as(not null))};")
514 redef fun inner_compile_to_c
(v
) do abort
516 # The single invocation witout fancy stuffs
517 private fun compile_call_to_c
(v
: I2CCompilerVisitor, args
: Array[String]): String is abstract
521 redef fun compile_call_to_c
(v
, args
)
524 if prop
.global
.is_init
then args
.add
("init_table")
525 if prop
.name
== (once
("add".to_symbol
)) and prop
.local_class
.name
== (once
("Array".to_symbol
)) then
526 return "{prop.cname}({args.join(", ")})"
528 return "{prop.global.meth_call}({args[0]})({args.join(", ")})"
534 redef fun compile_call_to_c
(v
, args
)
537 if prop
.global
.is_init
then args
.add
("init_table")
538 return "{prop.super_meth_call}({args[0]})({args.join(", ")})"
543 redef fun compile_call_to_c
(v
, args
)
545 return "NEW_{stype.local_class}_{property.global.intro.cname}({args.join(", ")})"
550 redef fun inner_compile_to_c
(v
)
552 if exprs
.is_empty
then
557 var c
= code
.split_with
("@@@")
560 if i
< exprs
.length
and i
< c
.length-1
then
561 res
.append
(v
.register
(exprs
[i
]))
571 redef fun inner_compile_to_c
(v
)
573 var s
= new Buffer.from
("fprintf(stderr")
575 s
.append
(", \"{t}\
"")
581 s
= new Buffer.from
("fprintf(stderr, \" (%s
")
585 s.append(")\\n\
", LOCATE_{module_location.name}")
587 s
.append
(", {ll.line_start}")
592 v
.add_instr
("nit_exit(1);")
598 redef fun inner_compile_to_c
(v
)
600 return v
.register
(expr
)
604 redef class IAttrRead
605 redef fun inner_compile_to_c
(v
)
607 return "{property.global.attr_access}({v.register(expr)})"
611 redef class IAttrIsset
612 redef fun inner_compile_to_c
(v
)
614 return "TAG_Bool({property.global.attr_access}({v.register(expr)})!=NIT_NULL)"
618 redef class IAttrWrite
619 redef fun inner_compile_to_c
(v
)
621 v
.add_instr
("{property.global.attr_access}({v.register(expr1)}) = {v.register(expr2)};")
626 redef class ITypeCheck
627 redef fun inner_compile_to_c
(v
)
629 # FIXME handle formaltypes
630 var g
= stype
.local_class
.global
631 var recv
= v
.register
(expr
)
633 if expr
.stype
.is_nullable
then
634 if stype
.is_nullable
then
635 s
= "({recv}==NIT_NULL) || "
636 else if stype
.as_nullable
== expr
.stype
then
637 return "TAG_Bool({recv}!=NIT_NULL)"
639 s
= "({recv}!=NIT_NULL) && "
642 return "TAG_Bool({s}VAL_ISA({recv}, {g.color_id}, {g.id_id})) /*cast {stype}*/"
647 redef fun inner_compile_to_c
(v
)
651 if t1
isa MMTypeNone then
652 if t2
isa MMTypeNone then
654 else if t2
.is_nullable
then
655 return "TAG_Bool({v.register(expr2)}==NIT_NULL)"
659 else if t1
.is_nullable
then
660 if t2
isa MMTypeNone then
661 return "TAG_Bool({v.register(expr1)}==NIT_NULL)"
662 else if t2
.is_nullable
then
663 return "TAG_Bool(IS_EQUAL_NN({v.register(expr1)},{v.register(expr2)}))"
665 return "TAG_Bool(IS_EQUAL_ON({v.register(expr2)},{v.register(expr1)}))"
668 if t2
isa MMTypeNone then
670 else if t2
.is_nullable
then
671 return "TAG_Bool(IS_EQUAL_ON({v.register(expr1)},{v.register(expr2)}))"
673 return "TAG_Bool(IS_EQUAL_OO({v.register(expr1)},{v.register(expr2)}))"
680 redef fun inner_compile_to_c
(v
)
682 return "TAG_Bool(!UNTAG_Bool({v.register(expr)}))"
687 redef fun inner_compile_to_c
(v
)
690 var res
= result
.as(not null)
691 if res
.stype
.is_nullable
then
692 v
.add_decl
("static val_t once_value_{i}; static int once_bool_{i}; /* Once value */")
693 v
.add_instr
("if (!once_bool_{i}) \{")
695 # Since the value is not nullable, we use the null value to represent the boolean
696 v
.add_decl
("static val_t once_value_{i}; /* Once value */")
697 v
.add_instr
("if (!once_value_{i}) \{")
701 var e
= v
.register
(result
.as(not null))
702 v
.add_instr
("once_value_{i} = {e};")
703 if res
.stype
.is_nullable
then v
.add_instr
("once_bool_{i} = true;")
705 v
.add_instr
("} else {e} = once_value_{i};")
710 redef class IClosCall
711 redef fun compile_to_c
(v
: I2CCompilerVisitor)
713 v
.add_location
(location
)
716 ivar
= "closctx->closurevariable[{v.closures[closure_decl]}]"
718 ivar
= "CREG[{v.closures[closure_decl]}]"
721 args
.append
(v
.registers
(exprs
))
723 var s
= "(({v.clostypes[closure_decl]})({ivar}->fun))({args.join(", ")})"
726 v
.add_instr
("if ({ivar}->has_broke) \{")
732 v
.add_goto
(v
.iroutine
.body
)
737 redef fun inner_compile_to_c
(v
) do abort
741 redef fun inner_compile_to_c
(v
)
745 ivar
= "closctx->closurevariable[{v.closures[closure_decl]}]"
747 ivar
= "CREG[{v.closures[closure_decl]}]"
749 return "TAG_Bool({ivar} != NULL)"
754 redef class IClosureDef
755 fun compile_closure
(v
: I2CCompilerVisitor): String
757 var cfc_old
= v
.closure
759 var lls_old
= v
.local_labels
760 v
.local_labels
= new HashSet[ISeq]
764 cv
.ctx
= new CContext
765 cv
.out_contexts
.add
(cv
.ctx
)
767 var cname
= "OC_{v.basecname}_{v.new_number}"
768 var args
= compile_signature_to_c
(v
.visitor
, cname
, null, "struct WBT_ *closctx", null)
769 var ctx_old2
= cv
.ctx
770 cv
.ctx
= new CContext
772 var s
= compile_inside_to_c
(v
, args
)
774 v
.add_instr
("return;")
776 v
.add_instr
("return {s};")
779 ctx_old2
.append
(cv
.ctx
)
788 var closcnv
= "wbclos{v.new_number}"
789 v
.add_decl
("struct WBT_ {closcnv};")
790 v
.add_instr
("{closcnv}.fun = (fun_t){cname};")
791 v
.add_instr
("{closcnv}.has_broke = NULL;")
793 v
.add_instr
("{closcnv}.variable = closctx->variable;")
794 v
.add_instr
("{closcnv}.closurevariable = closctx->closurevariable;")
796 v
.add_instr
("{closcnv}.variable = REG;")
797 v
.add_instr
("{closcnv}.closurevariable = CREG;")
800 v
.local_labels
= lls_old
801 return "(&{closcnv})"