Debian Codegraph @

src/Stringification/C.v

raw
1 From Coq Require Import ZArith.
2 From Coq Require Import MSetPositive.
3 From Coq Require Import FMapPositive.
4 From Coq Require Import String.
5 From Coq Require Import Ascii.
6 From Coq Require Import Bool.
7 From Coq Require Import HexString.
8 Require Import Crypto.Util.ListUtil Coq.Lists.List.
9 Require Crypto.Util.Strings.String.
10 Require Import Crypto.Util.Strings.Decimal.
11 Require Import Crypto.Util.Strings.Show.
12 Require Import Crypto.Util.ZRange.
13 Require Import Crypto.Util.ZRange.Operations.
14 Require Import Crypto.Util.ZRange.Show.
15 Require Import Crypto.Util.Option.
16 Require Import Crypto.Util.OptionList.
17 Require Import Rewriter.Language.Language.
18 Require Import Crypto.Language.API.
19 Require Import Crypto.Stringification.Language.
20 Require Import Crypto.Stringification.IR.
21 Require Import Crypto.AbstractInterpretation.ZRange.
22 Require Import Crypto.Util.Bool.Equality.
23 Require Import Crypto.Util.Notations.
24 Import Coq.Lists.List ListNotations. Local Open Scope zrange_scope. Local Open Scope Z_scope.
25
26
27 Module Compilers.
28 Local Set Boolean Equality Schemes.
29 Local Set Decidable Equality Schemes.
30 Export Language.Compilers.
31 Export Language.API.Compilers.
32 Export AbstractInterpretation.ZRange.Compilers.
33 Export Stringification.Language.Compilers.
34 Import invert_expr.
35 Import Compilers.API.
36
37 Module ToString.
38 Import Stringification.Language.Compilers.ToString.
39 Import Stringification.Language.Compilers.ToString.ZRange.
40 Import Compilers.ToString.IR.
41 Local Open Scope string_scope.
42 Local Open Scope Z_scope.
43
44 Local Notation tZ := (base.type.type_base base.type.Z).
45
46 Module C.
47 Definition comment_block := List.map (fun line => "/* " ++ line ++ " */")%string.
48
49 Definition FIAT_INLINE (prefix : string) := (String.to_upper prefix ++ "FIAT_INLINE")%string.
50
51 Module String.
52 Definition stdint_bitwidths : list Z := [8; 16; 32; 64].
53 Definition is_special_bitwidth (bw : Z) := negb (existsb (Z.eqb bw) stdint_bitwidths).
54
55 Module int.
56 Module type.
57 Definition to_string_opt_typedef {language_naming_conventions : language_naming_conventions_opt} {skip_typedefs : skip_typedefs_opt} (prefix : string) (t : int.type) (typedef : option string) : string
58 := int.to_string_gen_opt_typedef stdint_bitwidths "uint" "int" "_t" "" false(*type declarations not static*) false(*typedef declarations are not static*) prefix t typedef.
59 Definition to_string {language_naming_conventions : language_naming_conventions_opt} (prefix : string) (t : int.type) : string
60 := to_string_opt_typedef (skip_typedefs:=true) prefix t None.
61 Definition to_literal_macro_string (t : int.type) : option string
62 := if Z.ltb (int.bitwidth_of t) 8
63 then None
64 else Some ((if int.is_unsigned t then "U" else "")
65 ++ "INT"
66 ++ Decimal.Z.to_string (int.bitwidth_of t)
67 ++ "_C")%string.
68 End type.
69 End int.
70
71 Module type.
72 Module primitive.
73 Definition to_string_opt_typedef {language_naming_conventions : language_naming_conventions_opt} {skip_typedefs : skip_typedefs_opt} (prefix : string) (t : type.primitive) (r : option int.type) (typedef : option string) : string
74 := match r with
75 | Some int_t => int.type.to_string_opt_typedef prefix int_t typedef
76 | None => "ℤ"
77 end ++ match t with
78 | type.Zptr => "*"
79 | type.Z => ""
80 end.
81 Definition to_string {language_naming_conventions : language_naming_conventions_opt} (prefix : string) (t : type.primitive) (r : option int.type) : string
82 := to_string_opt_typedef (skip_typedefs:=true) prefix t r None.
83 End primitive.
84 End type.
85
86 Definition value_barrier_name {language_naming_conventions : language_naming_conventions_opt} (static : bool) (prefix : string) (ty : int.type) : string
87 := format_special_function_name_ty static prefix "value_barrier" ty.
88 Definition value_barrier_func {language_naming_conventions : language_naming_conventions_opt} (static : bool) (prefix : string) (ty : int.type) : list string
89 := [""
90 ; "#if !defined(" ++ String.to_upper prefix ++ "NO_ASM) && (defined(__GNUC__) || defined(__clang__))"
91 ; (if static then "static " else "") ++ "__inline__ " ++ int.type.to_string prefix ty ++ " " ++ value_barrier_name static prefix ty ++ "(" ++ int.type.to_string prefix ty ++ " a) {"
92 ; " __asm__("""" : ""+r""(a) : /* no inputs */);"
93 ; " return a;"
94 ; "}"
95 ; "#else"
96 ; "# define " ++ value_barrier_name static prefix ty ++ "(x) (x)"
97 ; "#endif"].
98
99 Definition make_typedef
100 {language_naming_conventions : language_naming_conventions_opt}
101 {documentation_options : documentation_options_opt}
102 (prefix : string)
103 (typedef : typedef_info)
104 : list string
105 := let '(name, (ty, array_len), description) := name_and_type_and_describe_typedef prefix false(*type declarations not static*) typedef in
106 ((comment_block description)
107 ++ match array_len with
108 | None (* just an integer *)
109 => ["typedef " ++ String.type.primitive.to_string prefix type.Z ty ++ " " ++ name ++ ";"]
110 | Some None (* unknown array length *)
111 => ["typedef " ++ String.type.primitive.to_string prefix type.Zptr ty ++ " " ++ name ++ ";"]
112 | Some (Some len)
113 => ["typedef " ++ String.type.primitive.to_string prefix type.Z ty ++ " " ++ name ++ "[" ++ Decimal.Z.to_string (Z.of_nat len) ++ "];"]
114 end%string)%list.
115
116 Definition header
117 {language_naming_conventions : language_naming_conventions_opt}
118 {documentation_options : documentation_options_opt}
119 {package_namev : package_name_opt}
120 {class_namev : class_name_opt}
121 {output_options : output_options_opt}
122 (machine_wordsize : Z) (internal_static : bool) (static : bool) (prefix : string) (infos : ident_infos)
123 (typedef_map : list typedef_info)
124 : list string
125 := let bitwidths_used := bitwidths_used infos in
126 let value_barrier_bitwidths := value_barrier_bitwidths infos in
127 let FIAT_EXTENSION := (String.to_upper prefix ++ "FIAT_EXTENSION")%string in
128 (["";
129 "#include <stdint.h>"]
130 ++ (if IntSet.mem _Bool bitwidths_used || IntSet.mem (int.signed_counterpart_of _Bool) bitwidths_used
131 then ["typedef unsigned char " ++ int.type.to_string prefix _Bool ++ ";";
132 "typedef signed char " ++ int.type.to_string prefix (int.signed_counterpart_of _Bool) ++ ";"]%string
133 else [])
134 ++ (let gnuc_defines
135 := (if IntSet.mem uint128 bitwidths_used || IntSet.mem int128 bitwidths_used
136 then [(FIAT_EXTENSION, "__extension__")]
137 else [])
138 ++ [(FIAT_INLINE prefix, "__inline__")]
139 in
140 ["#if defined(__GNUC__) || defined(__clang__)"]
141 ++ List.map (fun '(MACRO, primitive) => "# define " ++ MACRO ++ " " ++ primitive)%string gnuc_defines
142 ++ ["#else"]
143 ++ List.map (fun '(MACRO, primitive) => "# define " ++ MACRO)%string gnuc_defines
144 ++ ["#endif"])
145 ++ (if IntSet.mem uint128 bitwidths_used || IntSet.mem int128 bitwidths_used
146 then ["";
147 FIAT_EXTENSION ++ " typedef signed __int128 " ++ int.type.to_string prefix int128 ++ ";";
148 FIAT_EXTENSION ++ " typedef unsigned __int128 " ++ int.type.to_string prefix uint128 ++ ";"]%string
149 else [])
150 ++ (if skip_typedefs
151 then []
152 else List.flat_map
153 (fun td_name =>
154 match List.find (fun '(name, _, _, _) => (td_name =? name)%string) typedef_map with
155 | Some td_info => [""] ++ make_typedef prefix td_info
156 | None => ["#error ""Could not find typedef info for '" ++ td_name ++ "'"";"]%string
157 end%list)
158 (typedefs_used infos))
159 ++ [""
160 ; "#if (-1 & 3) != 3"
161 ; "#error ""This code only works on a two's complement system"""
162 ; "#endif"]
163 ++ (List.flat_map
164 (value_barrier_func internal_static prefix)
165 (IntSet.elements value_barrier_bitwidths))
166 ++ [""])%list.
167 End String.
168
169 Module primitive.
170 Definition to_string (prefix : string) (t : type.primitive) (v : BinInt.Z) : string
171 := match t, String.int.type.to_literal_macro_string (int.of_zrange_relaxed r[v ~> v]) with
172 | type.Z, Some macro
173 => macro ++ "(" ++ HexString.of_Z v ++ ")"
174 | type.Z, None => HexString.of_Z v
175 | type.Zptr, _ => "#error ""literal address " ++ HexString.of_Z v ++ """;"
176 end.
177 End primitive.
178
179 Fixpoint arith_to_string
180 {language_naming_conventions : language_naming_conventions_opt} (internal_static : bool)
181 (prefix : string) {t} (e : arith_expr t) : string
182 := let special_name_ty name ty := format_special_function_name_ty internal_static prefix name ty in
183 let special_name name bw := format_special_function_name internal_static prefix name false(*unsigned*) bw in
184 match e with
185 | (literal v @@@ _) => primitive.to_string prefix type.Z v
186 | (List_nth n @@@ Var _ v)
187 => "(" ++ v ++ "[" ++ Decimal.Z.to_string (Z.of_nat n) ++ "])"
188 | (Addr @@@ Var _ v) => "&" ++ v
189 | (Dereference @@@ e) => "( *" ++ arith_to_string internal_static prefix e ++ " )"
190 | (Z_shiftr offset @@@ e)
191 => "(" ++ arith_to_string internal_static prefix e ++ " >> " ++ Decimal.Z.to_string offset ++ ")"
192 | (Z_shiftl offset @@@ e)
193 => "(" ++ arith_to_string internal_static prefix e ++ " << " ++ Decimal.Z.to_string offset ++ ")"
194 | (Z_land @@@ (e1, e2))
195 => "(" ++ arith_to_string internal_static prefix e1 ++ " & " ++ arith_to_string internal_static prefix e2 ++ ")"
196 | (Z_lor @@@ (e1, e2))
197 => "(" ++ arith_to_string internal_static prefix e1 ++ " | " ++ arith_to_string internal_static prefix e2 ++ ")"
198 | (Z_lxor @@@ (e1, e2))
199 => "(" ++ arith_to_string internal_static prefix e1 ++ " ^ " ++ arith_to_string internal_static prefix e2 ++ ")"
200 | (Z_add @@@ (x1, x2))
201 => "(" ++ arith_to_string internal_static prefix x1 ++ " + " ++ arith_to_string internal_static prefix x2 ++ ")"
202 | (Z_mul @@@ (x1, x2))
203 => "(" ++ arith_to_string internal_static prefix x1 ++ " * " ++ arith_to_string internal_static prefix x2 ++ ")"
204 | (Z_sub @@@ (x1, x2))
205 => "(" ++ arith_to_string internal_static prefix x1 ++ " - " ++ arith_to_string internal_static prefix x2 ++ ")"
206 | (Z_lnot _ @@@ e)
207 => "(~" ++ arith_to_string internal_static prefix e ++ ")"
208 | (Z_bneg @@@ e)
209 => "(!" ++ arith_to_string internal_static prefix e ++ ")"
210 | (Z_value_barrier ty @@@ e)
211 => String.value_barrier_name internal_static prefix ty ++ "(" ++ arith_to_string internal_static prefix e ++ ")"
212 | (Z_mul_split lg2s @@@ args)
213 => special_name "mulx" lg2s ++ "(" ++ arith_to_string internal_static prefix args ++ ")"
214 | (Z_add_with_get_carry lg2s @@@ args)
215 => special_name "addcarryx" lg2s ++ "(" ++ arith_to_string internal_static prefix args ++ ")"
216 | (Z_sub_with_get_borrow lg2s @@@ args)
217 => special_name "subborrowx" lg2s ++ "(" ++ arith_to_string internal_static prefix args ++ ")"
218 | (Z_zselect ty @@@ args)
219 => special_name_ty "cmovznz" ty ++ "(" ++ arith_to_string internal_static prefix args ++ ")"
220 | (Z_add_modulo @@@ (x1, x2, x3)) => "#error addmodulo;"
221 | (Z_static_cast int_t @@@ e)
222 => "(" ++ String.type.primitive.to_string prefix type.Z (Some int_t) ++ ")"
223 ++ arith_to_string internal_static prefix e
224 | Var _ v => v
225 | Pair A B a b
226 => arith_to_string internal_static prefix a ++ ", " ++ arith_to_string internal_static prefix b
227 | (List_nth _ @@@ _)
228 | (Addr @@@ _)
229 | (Z_add @@@ _)
230 | (Z_mul @@@ _)
231 | (Z_sub @@@ _)
232 | (Z_land @@@ _)
233 | (Z_lor @@@ _)
234 | (Z_lxor @@@ _)
235 | (Z_add_modulo @@@ _)
236 => "#error bad_arg;"
237 | TT
238 => "#error tt;"
239 end%core%Cexpr.
240
241 Definition stmt_to_string
242 {language_naming_conventions : language_naming_conventions_opt} (internal_static : bool)
243 (prefix : string)
244 (e : stmt)
245 : string
246 := match e with
247 | Call val
248 => arith_to_string internal_static prefix val ++ ";"
249 | Assign true t sz name val
250 => String.type.primitive.to_string prefix t sz ++ " " ++ name ++ " = " ++ arith_to_string internal_static prefix val ++ ";"
251 | Assign false _ sz name val
252 => name ++ " = " ++ arith_to_string internal_static prefix val ++ ";"
253 | AssignZPtr name sz val
254 => "*" ++ name ++ " = " ++ arith_to_string internal_static prefix val ++ ";"
255 | DeclareVar t sz name
256 => String.type.primitive.to_string prefix t sz ++ " " ++ name ++ ";"
257 | Comment lines _
258 => String.concat String.NewLine (comment_block (ToString.preprocess_comment_block lines))
259 | AssignNth name n val
260 => name ++ "[" ++ Decimal.Z.to_string (Z.of_nat n) ++ "] = " ++ arith_to_string internal_static prefix val ++ ";"
261 end.
262 Definition to_strings
263 {language_naming_conventions : language_naming_conventions_opt} (internal_static : bool)
264 (prefix : string)
265 (e : expr)
266 : list string
267 := List.map (stmt_to_string internal_static prefix) e.
268
269 Import OfPHOAS.
270
271 Fixpoint to_base_arg_list {language_naming_conventions : language_naming_conventions_opt} {skip_typedefs : skip_typedefs_opt} (prefix : string) {t} : base_var_data t -> list string
272 := match t return base_var_data t -> _ with
273 | tZ
274 => fun '(n, is_ptr, r, typedef)
275 => [String.type.primitive.to_string_opt_typedef prefix type.Z r typedef ++ " " ++ n]
276 | base.type.prod A B
277 => fun '(va, vb) => (to_base_arg_list prefix va ++ to_base_arg_list prefix vb)%list
278 | base.type.list tZ
279 => fun '(n, r, len, typedef)
280 => ["const "
281 ++ match (if skip_typedefs then None else typedef) with
282 | Some typedef => format_typedef_name prefix false(*type declarations not static*) typedef ++ " " ++ n
283 | None => String.type.primitive.to_string prefix type.Z r ++ " " ++ n ++ "[" ++ Decimal.Z.to_string (Z.of_nat len) ++ "]"
284 end]
285 | base.type.list _ => fun _ => ["#error ""complex list"";"]
286 | base.type.option _ => fun _ => ["#error option;"]
287 | base.type.unit => fun _ => ["#error unit;"]
288 | base.type.type_base t => fun _ => ["#error " ++ show t ++ ";"]%string
289 end.
290
291 Definition to_arg_list {language_naming_conventions : language_naming_conventions_opt} {skip_typedefs : skip_typedefs_opt} (prefix : string) {t} : var_data t -> list string
292 := match t return var_data t -> _ with
293 | type.base t => to_base_arg_list prefix
294 | type.arrow _ _ => fun _ => ["#error arrow;"]
295 end.
296
297 Fixpoint to_arg_list_for_each_lhs_of_arrow {language_naming_conventions : language_naming_conventions_opt} {skip_typedefs : skip_typedefs_opt} (prefix : string) {t} : type.for_each_lhs_of_arrow var_data t -> list string
298 := match t return type.for_each_lhs_of_arrow var_data t -> _ with
299 | type.base t => fun _ => nil
300 | type.arrow s d
301 => fun '(x, xs)
302 => to_arg_list prefix x ++ to_arg_list_for_each_lhs_of_arrow prefix xs
303 end%list.
304
305 Fixpoint to_base_retarg_list {language_naming_conventions : language_naming_conventions_opt} {skip_typedefs : skip_typedefs_opt} prefix {t} : base_var_data t -> list string
306 := match t return base_var_data t -> _ with
307 | tZ
308 => fun '(n, is_ptr, r, typedef)
309 => [match typedef with
310 | Some typedef => format_typedef_name prefix false(*type declarations not static*) typedef ++ "*"
311 | None => String.type.primitive.to_string prefix type.Zptr r
312 end
313 ++ " " ++ n]
314 | base.type.prod A B
315 => fun '(va, vb) => (to_base_retarg_list prefix va ++ to_base_retarg_list prefix vb)%list
316 | base.type.list tZ
317 => fun '(n, r, len, typedef)
318 => [match (if skip_typedefs then None else typedef) with
319 | Some typedef => format_typedef_name prefix false(*type declarations not static*) typedef ++ " " ++ n
320 | None => String.type.primitive.to_string prefix type.Z r ++ " " ++ n ++ "[" ++ Decimal.Z.to_string (Z.of_nat len) ++ "]"
321 end]
322 | base.type.list _ => fun _ => ["#error ""complex list"";"]
323 | base.type.option _ => fun _ => ["#error option;"]
324 | base.type.unit => fun _ => ["#error unit;"]
325 | base.type.type_base t => fun _ => ["#error " ++ show t ++ ";"]%string
326 end.
327
328 Definition to_retarg_list {language_naming_conventions : language_naming_conventions_opt} {skip_typedefs : skip_typedefs_opt} (prefix : string) {t} : var_data t -> list string
329 := match t return var_data t -> _ with
330 | type.base _ => to_base_retarg_list prefix
331 | type.arrow _ _ => fun _ => ["#error arrow;"]
332 end.
333
334 (** * Language-specific numeric conversions to be passed to the PHOAS -> IR translation *)
335
336 (** Quoting
337 http://en.cppreference.com/w/c/language/conversion:
338
339 ** Integer promotions
340
341 Integer promotion is the implicit conversion of a value of
342 any integer type with rank less or equal to rank of int or
343 of a bit field of type _Bool, int, signed int, unsigned
344 int, to the value of type int or unsigned int
345
346 If int can represent the entire range of values of the
347 original type (or the range of values of the original bit
348 field), the value is converted to type int. Otherwise the
349 value is converted to unsigned int. *)
350 (** We assume a 32-bit [int] type *)
351 Definition integer_promote_type (t : int.type) : int.type
352 := if int.is_tighter_than t int32
353 then int32
354 else t.
355
356
357 (** Quoting
358 http://en.cppreference.com/w/c/language/conversion:
359
360 rank above is a property of every integer type and is
361 defined as follows:
362
363 1) the ranks of all signed integer types are different and
364 increase with their precision: rank of signed char <
365 rank of short < rank of int < rank of long int < rank
366 of long long int
367
368 2) the ranks of all signed integer types equal the ranks
369 of the corresponding unsigned integer types
370
371 3) the rank of any standard integer type is greater than
372 the rank of any extended integer type of the same size
373 (that is, rank of __int64 < rank of long long int, but
374 rank of long long < rank of __int128 due to the rule
375 (1))
376
377 4) rank of char equals rank of signed char and rank of
378 unsigned char
379
380 5) the rank of _Bool is less than the rank of any other
381 standard integer type
382
383 6) the rank of any enumerated type equals the rank of its
384 compatible integer type
385
386 7) ranking is transitive: if rank of T1 < rank of T2 and
387 rank of T2 < rank of T3 then rank of T1 < rank of T3
388
389 8) any aspects of relative ranking of extended integer
390 types not covered above are implementation defined *)
391 (** We define the rank to be the bitwidth, which satisfies
392 (1), (2), (4), (5), and (7). Points (3) and (6) do not
393 apply. *)
394 Definition rank (r : int.type) : BinInt.Z := int.bitwidth_of r.
395 Definition IMPOSSIBLE {T} (v : T) : T. exact v. Qed.
396 (** Quoting
397 http://en.cppreference.com/w/c/language/conversion: *)
398 Definition C_common_type (t1 t2 : int.type) : int.type
399 (** First of all, both operands undergo integer promotions
400 (see below). Then *)
401 := let t1 := integer_promote_type t1 in
402 let t2 := integer_promote_type t2 in
403 (** - If the types after promotion are the same, that
404 type is the common type *)
405 if int.type_beq t1 t2 then
406 t1
407 (** - Otherwise, if both operands after promotion have
408 the same signedness (both signed or both unsigned),
409 the operand with the lesser conversion rank (see
410 below) is implicitly converted to the type of the
411 operand with the greater conversion rank *)
412 else if bool_beq (int.is_signed t1) (int.is_signed t2) then
413 (if rank t1 >=? rank t2 then t1 else t2)
414 (** - Otherwise, the signedness is different: If the
415 operand with the unsigned type has conversion rank
416 greater or equal than the rank of the type of the
417 signed operand, then the operand with the signed
418 type is implicitly converted to the unsigned type
419 *)
420 else if int.is_unsigned t1 && (rank t1 >=? rank t2) then
421 t1
422 else if int.is_unsigned t2 && (rank t2 >=? rank t1) then
423 t2
424 (** - Otherwise, the signedness is different and the
425 signed operand's rank is greater than unsigned
426 operand's rank. In this case, if the signed type
427 can represent all values of the unsigned type, then
428 the operand with the unsigned type is implicitly
429 converted to the type of the signed operand. *)
430 else if int.is_signed t1 && int.is_tighter_than t2 t1 then
431 t1
432 else if int.is_signed t2 && int.is_tighter_than t1 t2 then
433 t2
434 (** - Otherwise, both operands undergo implicit
435 conversion to the unsigned type counterpart of the
436 signed operand's type. *)
437 (** N.B. This case ought to be impossible in our code,
438 where [rank] is the bitwidth. *)
439 else if int.is_signed t1 then
440 int.unsigned_counterpart_of t1
441 else
442 int.unsigned_counterpart_of t2.
443
444 (** Quoting https://en.cppreference.com/w/c/language/conversion: *)
445 (** Usual arithmetic conversions
446
447 The arguments of the following arithmetic operators undergo
448 implicit conversions for the purpose of obtaining the common
449 real type, which is the type in which the calculation is
450 performed:
451
452 - binary arithmetic *, /, %, +, -
453 - relational operators <, >, <=, >=, ==, !=
454 - binary bitwise arithmetic &, ^, |,
455 - the conditional operator ?: *)
456 Inductive binop_kind := use_common_type.
457 Definition kind_of_binop (idc : Z_binop) : binop_kind
458 := match idc with
459 | Z_land
460 | Z_lor
461 | Z_lxor
462 | Z_add
463 | Z_mul
464 | Z_sub
465 => use_common_type
466 end.
467
468 Definition C_bin_op_natural_output
469 : Z_binop -> int.type * int.type -> int.type
470 := fun idc '(t1, t2)
471 => match kind_of_binop idc with
472 | use_common_type => C_common_type t1 t2
473 end.
474
475 Definition C_bin_op_casts
476 : Z_binop -> option int.type -> int.type * int.type -> option int.type * (option int.type * option int.type)
477 := fun idc desired_type '(t1, t2)
478 => match kind_of_binop idc with
479 | use_common_type
480 => match desired_type with
481 | None => (None, (None, None))
482 | Some _
483 => let t1 := integer_promote_type t1 in
484 let t2 := integer_promote_type t2 in
485 let '(t1o, t2o)
486 := if int.is_tighter_than t2 t1
487 then (get_Zcast_up_if_needed desired_type (Some t1), None)
488 else (None, get_Zcast_up_if_needed desired_type (Some t2)) in
489 let ct := C_common_type (Option.value t1o t1) (Option.value t2o t2) in
490 (get_Zcast_down_if_needed desired_type (Some ct), (t1o, t2o))
491 end
492 end.
493
494 Definition C_un_op_casts
495 : Z_unop -> option int.type -> int.type -> option int.type * option int.type
496 := fun idc desired_type t
497 => let t := integer_promote_type t in
498 match idc with
499 | Z_shiftr offset
500 => (** N.B. We must cast the expression up to a large
501 enough type to fit 2^offset (importantly, not
502 just 2^offset-1), because C considers it to be
503 undefined behavior to shift >= width of the
504 type. We should probably figure out how to not
505 generate these things in the first place...
506
507 N.B. We must preserve signedness of the value
508 being shifted, because shift does not commute
509 with mod. *)
510 let t' := int.union_zrange r[0~>2^offset]%zrange t in
511 ((** We cast the result down to the specified type, if needed *)
512 get_Zcast_down_if_needed desired_type (Some t'),
513 (** We cast the argument up to a large enough type *)
514 get_Zcast_up_if_needed (Some t') (Some t))
515 | Z_shiftl offset
516 => (** N.B. We must cast the expression up to a large
517 enough type to fit 2^offset (importantly, not
518 just 2^offset-1), because C considers it to be
519 undefined behavior to shift >= width of the
520 type. We should probably figure out how to not
521 generate these things in the first place...
522
523 N.B. We make sure that we only left-shift
524 unsigned values, since shifting into the sign
525 bit is undefined behavior. *)
526 let rpre_out := match desired_type with
527 | Some rout => Some (int.union_zrange r[0~>2^offset] (int.unsigned_counterpart_of rout))
528 | None => Some (int.of_zrange_relaxed r[0~>2^offset]%zrange)
529 end in
530 ((** We cast the result down to the specified type, if needed *)
531 get_Zcast_down_if_needed desired_type rpre_out,
532 (** We cast the argument up to a large enough type *)
533 get_Zcast_up_if_needed rpre_out (Some t))
534 | Z_lnot ty
535 => ((* if the result is too big, we cast it down; we
536 don't need to upcast it because it'll get
537 picked up by implicit casts if necessary *)
538 get_Zcast_down_if_needed desired_type (Some ty),
539 (** always cast to the width of the type, unless we are already exactly that type (which the machinery in IR handles) *)
540 Some ty)
541 | Z_value_barrier ty
542 => ((* if the result is too big, we cast it down; we
543 don't need to upcast it because it'll get
544 picked up by implicit casts if necessary *)
545 get_Zcast_down_if_needed desired_type (Some ty),
546 (** implicit casts will cast the argument up if needed *)
547 None)
548 | Z_bneg
549 => ((* bneg is !, i.e., takes the argument to 1 if its not zero, and to zero if it is zero; so we don't ever need to cast *)
550 None, None)
551 end.
552
553 Local Instance CLanguageCasts : LanguageCasts :=
554 {| bin_op_natural_output := C_bin_op_natural_output
555 ; bin_op_casts := C_bin_op_casts
556 ; un_op_casts := C_un_op_casts
557 ; upcast_on_assignment := false
558 ; upcast_on_funcall := false
559 ; explicit_pointer_variables := false
560 |}.
561
562 (** Top-level printing functions *)
563
564 Definition to_function_lines
565 {language_naming_conventions : language_naming_conventions_opt}
566 {skip_typedefs : skip_typedefs_opt}
567 (internal_static : bool) (static : bool) (all_static : bool) (inline : bool) (prefix : string) (name : string)
568 {t}
569 (f : type.for_each_lhs_of_arrow var_data t * var_data (type.base (type.final_codomain t)) * expr)
570 : list string
571 := let '(args, rets, body) := f in
572 (((((if static then "static " else "")
573 ++ (if inline then FIAT_INLINE prefix ++ " " else "")
574 ++ "void "
575 ++ name ++ "("
576 ++ (String.concat ", " (to_retarg_list prefix rets ++ to_arg_list_for_each_lhs_of_arrow prefix args))
577 ++ ") {")%string)
578 :: (List.map (fun s => " " ++ s)%string (to_strings internal_static prefix body)))
579 ++ ["}"])%list.
580
581 (** In C, there is no munging of return arguments (they remain
582 passed by pointers), so all variables are live *)
583 Local Instance : consider_retargs_live_opt := fun _ _ _ => true.
584 Local Instance : rename_dead_opt := fun s => s.
585 (** In C we do want to lift declarations to the top, to comply
586 with ISO C90 *)
587 Local Instance : lift_declarations_opt := true.
588
589 Definition ToFunctionLines
590 {absint_opts : AbstractInterpretation.Options}
591 {relax_zrange : relax_zrange_opt}
592 {language_naming_conventions : language_naming_conventions_opt}
593 {documentation_options : documentation_options_opt}
594 {output_options : output_options_opt}
595 (machine_wordsize : Z)
596 (do_bounds_check : bool) (internal_static : bool) (static : bool) (all_static : bool) (inline : bool) (prefix : string) (name : string)
597 {t}
598 (e : @Compilers.expr.Expr base.type ident.ident t)
599 (comment : type.for_each_lhs_of_arrow var_data t -> var_data (type.base (type.final_codomain t)) -> list string)
600 (name_list : option (list string))
601 (inbounds : type.for_each_lhs_of_arrow ZRange.type.option.interp t)
602 (outbounds : ZRange.type.base.option.interp (type.final_codomain t))
603 (intypedefs : type.for_each_lhs_of_arrow var_typedef_data t)
604 (outtypedefs : base_var_typedef_data (type.final_codomain t))
605 : (list string * ident_infos) + string
606 := match ExprOfPHOAS do_bounds_check e name_list inbounds intypedefs outtypedefs with
607 | inl (indata, outdata, f)
608 => inl ((["/*"]
609 ++ (List.map (fun s => if (String.length s =? 0)%nat then " *" else (" * " ++ s))%string (comment indata outdata))
610 ++ match input_bounds_to_string indata inbounds with
611 | nil => nil
612 | ls => [" * Input Bounds:"] ++ List.map (fun v => " * " ++ v)%string ls
613 end
614 ++ match bound_to_string outdata outbounds with
615 | nil => nil
616 | ls => [" * Output Bounds:"] ++ List.map (fun v => " * " ++ v)%string ls
617 end
618 ++ [" */"]
619 ++ to_function_lines internal_static static all_static inline prefix name (indata, outdata, f))%list,
620 ident_infos.collect_all_infos f intypedefs outtypedefs)
621 | inr nil
622 => inr ("Unknown internal error in converting " ++ name ++ " to C")%string
623 | inr [err]
624 => inr ("Error in converting " ++ name ++ " to C:" ++ String.NewLine ++ err)%string
625 | inr errs
626 => inr ("Errors in converting " ++ name ++ " to C:" ++ String.NewLine ++ String.concat String.NewLine errs)%string
627 end.
628
629 Definition ToFunctionString
630 {absint_opts : AbstractInterpretation.Options}
631 {relax_zrange : relax_zrange_opt}
632 {language_naming_conventions : language_naming_conventions_opt}
633 {documentation_options : documentation_options_opt}
634 {output_options : output_options_opt}
635 (machine_wordsize : Z)
636 (do_bounds_check : bool) (internal_static : bool) (static : bool) (all_static : bool) (inline : bool) (prefix : string) (name : string)
637 {t}
638 (e : @Compilers.expr.Expr base.type ident.ident t)
639 (comment : type.for_each_lhs_of_arrow var_data t -> var_data (type.base (type.final_codomain t)) -> list string)
640 (name_list : option (list string))
641 (inbounds : type.for_each_lhs_of_arrow ZRange.type.option.interp t)
642 (outbounds : ZRange.type.option.interp (type.base (type.final_codomain t)))
643 (intypedefs : type.for_each_lhs_of_arrow var_typedef_data t)
644 (outtypedefs : base_var_typedef_data (type.final_codomain t))
645 : (string * ident_infos) + string
646 := match ToFunctionLines machine_wordsize do_bounds_check internal_static static all_static inline prefix name e comment name_list inbounds outbounds intypedefs outtypedefs with
647 | inl (ls, used_types) => inl (LinesToString ls, used_types)
648 | inr err => inr err
649 end.
650
651 Definition OutputCAPI : OutputLanguageAPI :=
652 {|
653 ToString.comment_block := comment_block;
654
655 ToString.comment_file_header_block := comment_block;
656
657 ToString.ToFunctionLines := @ToFunctionLines;
658
659 ToString.header := @String.header;
660
661 ToString.footer := fun _ _ _ _ _ _ _ _ _ => [];
662
663 (** We handle value_barrier specially *)
664 ToString.strip_special_infos machine_wordsize infos
665 := ident_info_with_value_barrier infos IntSet.empty;
666
667 |}.
668 End C.
669 Notation ToFunctionLines := C.ToFunctionLines.
670 Notation ToFunctionString := C.ToFunctionString.
671 Notation OutputCAPI := C.OutputCAPI.
672 End ToString.
673 End Compilers.