1use std::path::Path;
14
15use rucc_diag::{Diagnostic, Severity, Span};
16use rucc_lex::{Convert, Keywords, PpToken, convert};
17use rucc_sema::{Checker, Context as CheckContext};
18use rucc_session::{EmitKind, FileSystem, Options, Session};
19
20use crate::preprocess::render;
21
22#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct Compiled {
25 pub text: String,
27 pub messages: Vec<String>,
29 pub errors: u32,
31}
32
33impl Compiled {
34 #[must_use]
36 pub fn failed(&self) -> bool {
37 self.errors > 0
38 }
39}
40
41#[must_use]
54pub fn compile(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
55 let mut sess = Session::new(opts.clone());
56 let keywords = Keywords::new(&mut sess.interner, opts.std, opts.gnu_extensions);
60 let mut diagnostics: Vec<Diagnostic> = Vec::new();
61
62 let bytes = match fs.read(Path::new(name)) {
63 Ok(bytes) => bytes,
64 Err(e) => return failure(format!("{name}: {e}")),
65 };
66 let Ok(file) = sess.sources.add_shared(name, bytes, None) else {
67 return failure(format!("{name}: the source map has no room left for this file"));
68 };
69
70 let mut pp = rucc_pp::Preprocessor::new();
74 let predef = rucc_pp::Predef::for_options(opts);
75 let expanded: Vec<PpToken> = {
76 let mut cx = rucc_pp::Context::new(&mut sess.interner, &mut sess.sources, fs, &opts.search);
77 cx.lex = rucc_lex::Options::for_dialect(opts.std, opts.gnu_extensions);
78 if pp.predefine(&sess.target, &predef, &mut cx).is_err() {
79 return failure(format!("{name}: the source map has no room for the built in macros"));
80 }
81 pp.run(file, &mut cx).iter().map(|token| token.to_pp()).collect()
82 };
83 diagnostics.extend(pp.take_diagnostics());
84
85 let cx = Convert {
88 keywords: &keywords,
89 interner: &sess.interner,
90 target: &sess.target,
91 std: opts.std,
92 gnu: opts.gnu_extensions,
93 pedantic: opts.pedantic,
94 };
95 let (tokens, complaints) = convert(&expanded, &cx);
96 diagnostics.extend(complaints);
97
98 let parsed = rucc_parse::parse(
99 &tokens,
100 rucc_parse::Context {
101 interner: &sess.interner,
102 std: opts.std,
103 gnu: opts.gnu_extensions,
104 pedantic: opts.pedantic,
105 error_limit: opts.error_limit as usize,
106 },
107 );
108 let parse_failed = parsed.diagnostics.iter().any(|d| d.severity.is_fatal());
109 diagnostics.extend(parsed.diagnostics);
110
111 let mut text = String::new();
112 if !parse_failed {
113 let mut checker = Checker::new(
114 &parsed.ast,
115 CheckContext {
116 names: &sess.interner,
117 target: &sess.target,
118 std: opts.std,
119 gnu: opts.gnu_extensions,
120 pedantic: opts.pedantic,
121 error_limit: opts.error_limit as usize,
122 },
123 );
124 checker.check_unit();
125 let checked = checker.finish();
126 if !checked.failed() {
127 match opts.emit {
128 EmitKind::Tast => {
129 text = rucc_sema::print(&checked.tast, &checked.types, &sess.interner);
130 }
131 EmitKind::Ir => {
132 let lowered = rucc_lower::lower(
133 name,
134 rucc_lower::Context {
135 tast: &checked.tast,
136 types: &checked.types,
137 target: &sess.target,
138 names: &mut sess.interner,
139 },
140 );
141 let failed = lowered.diagnostics.iter().any(|d| d.severity.is_fatal());
145 if !failed {
146 if let Err(errors) = rucc_ir::verify(&lowered.module, &sess.interner) {
151 for error in errors {
152 diagnostics.push(internal(&format!("invalid IR, {error}")));
153 }
154 } else {
155 text = rucc_ir::print(&lowered.module, &sess.interner);
156 }
157 }
158 diagnostics.extend(lowered.diagnostics);
159 }
160 _ => {}
161 }
162 }
163 diagnostics.extend(checked.diagnostics);
164 }
165
166 let mut messages = Vec::with_capacity(diagnostics.len());
167 let mut errors = 0;
168 for diag in &diagnostics {
169 if diag.severity.is_fatal()
170 || (diag.severity == Severity::Warning && opts.warnings_are_errors)
171 {
172 errors += 1;
173 }
174 messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
175 }
176 if errors > 0 {
177 text.clear();
179 }
180 Compiled { text, messages, errors }
181}
182
183#[must_use]
193pub fn compile_ir(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
194 let mut sess = Session::new(opts.clone());
195 if opts.emit != EmitKind::Ir {
196 return failure(format!(
197 "{name}: an input of IR can only be emitted as IR, and `--emit={}` asks for what \
198 the C in front of it became",
199 opts.emit.as_str()
200 ));
201 }
202 let bytes = match fs.read(Path::new(name)) {
203 Ok(bytes) => bytes,
204 Err(e) => return failure(format!("{name}: {e}")),
205 };
206 let Ok(text) = std::str::from_utf8(bytes.as_slice()) else {
207 return failure(format!("{name}: this is not text, so it is not IR"));
208 };
209
210 let module = match rucc_ir::parse(text, &mut sess.interner) {
211 Ok(module) => module,
212 Err(error) => {
213 return failure(format!("{name}:{}: {}", error.line, error.message));
214 }
215 };
216 let mut diagnostics: Vec<Diagnostic> = Vec::new();
217 if let Err(errors) = rucc_ir::verify(&module, &sess.interner) {
218 for error in errors {
219 diagnostics.push(invalid(&format!("invalid IR, {error}")));
220 }
221 }
222 let mut messages = Vec::with_capacity(diagnostics.len());
223 for diag in &diagnostics {
224 messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
225 }
226 let errors = u32::try_from(messages.len()).unwrap_or(u32::MAX);
227 let text = if errors > 0 { String::new() } else { rucc_ir::print(&module, &sess.interner) };
228 Compiled { text, messages, errors }
229}
230
231fn invalid(message: &str) -> Diagnostic {
233 Diagnostic::error(message.to_owned(), Span::DUMMY).with_code("E0661")
234}
235
236fn internal(message: &str) -> Diagnostic {
238 Diagnostic::error(format!("internal error: {message}"), Span::DUMMY)
239 .with_code("E0652")
240 .note("this is a bug in rucc rather than in the program, please report it", Span::DUMMY)
241}
242
243fn failure(message: String) -> Compiled {
246 Compiled { text: String::new(), messages: vec![format!("rucc: error: {message}")], errors: 1 }
247}
248
249#[cfg(test)]
250mod tests {
251 use rucc_session::{MemoryFileSystem, Std};
252 use rucc_target::Triple;
253
254 use super::*;
255
256 fn options() -> Options {
257 let mut opts = Options::new("x86_64-unknown-linux-gnu".parse::<Triple>().unwrap());
258 opts.emit = EmitKind::Tast;
259 opts
260 }
261
262 fn run(opts: &Options, source: &str) -> Compiled {
263 let mut fs = MemoryFileSystem::new();
264 fs.insert("/main.c", source.to_owned().into_bytes());
265 compile(opts, "/main.c", &fs)
266 }
267
268 fn freestanding() -> Options {
272 let mut opts = options();
273 opts.hosted = false;
274 opts.search.push_system(rucc_session::runtime::DIR);
275 opts
276 }
277
278 fn shipped(source: &str) -> String {
280 let result = run(&freestanding(), source);
281 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
282 result.text
283 }
284
285 fn tast(source: &str) -> String {
287 let result = run(&options(), source);
288 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
289 result.text
290 }
291
292 #[test]
293 fn the_shipped_stdarg_declares_a_list_and_the_four_operators() {
294 let text = shipped(concat!(
295 "#include <stdarg.h>\n",
296 "int sum(int n, ...) {\n",
297 " va_list ap, copy;\n",
298 " va_start(ap, n);\n",
299 " va_copy(copy, ap);\n",
300 " int total = va_arg(ap, int) + va_arg(copy, int);\n",
301 " va_end(ap);\n",
302 " va_end(copy);\n",
303 " return total;\n",
304 "}\n",
305 ));
306 assert!(text.contains("va-start"), "{text}");
307 assert!(text.contains("va-copy"), "{text}");
308 assert!(text.contains("va-arg"), "{text}");
309 assert!(text.contains("va-end"), "{text}");
310 }
311
312 #[test]
316 fn stdarg_hands_out_the_type_alone_when_that_is_all_that_was_asked_for() {
317 let text = shipped(concat!(
318 "#define __need___va_list\n",
319 "#include <stdarg.h>\n",
320 "int vprint(const char *f, __gnuc_va_list ap);\n",
321 "#ifdef va_start\n",
322 "#error va_start should not be defined\n",
323 "#endif\n",
324 "#ifdef _VA_LIST_DEFINED\n",
325 "#error va_list should not have been made\n",
326 "#endif\n",
327 ));
328 assert!(text.contains("vprint"), "{text}");
329 }
330
331 #[test]
334 fn stddef_answers_one_piece_at_a_time_and_the_next_request_still_gets_through() {
335 let text = shipped(concat!(
336 "#define __need_size_t\n",
337 "#include <stddef.h>\n",
338 "#ifdef offsetof\n",
339 "#error offsetof should not be defined yet\n",
340 "#endif\n",
341 "#define __need_ptrdiff_t\n",
342 "#include <stddef.h>\n",
343 "#include <stddef.h>\n",
344 "size_t a;\n",
345 "ptrdiff_t b;\n",
346 "wchar_t c;\n",
347 "max_align_t d;\n",
348 "void *e = NULL;\n",
349 "struct P { int x; long y; };\n",
350 "size_t f = offsetof(struct P, y);\n",
351 ));
352 assert!(text.contains("decl #0 a : unsigned long"), "{text}");
353 assert!(text.contains("decl #1 b : long"), "{text}");
354 }
355
356 #[test]
357 fn the_shipped_limits_and_float_are_the_targets_own_answers() {
358 let text = shipped(concat!(
359 "#include <limits.h>\n",
360 "#include <float.h>\n",
361 "int bits = CHAR_BIT;\n",
362 "long big = LONG_MAX;\n",
363 "int low = INT_MIN;\n",
364 "int radix = FLT_RADIX;\n",
365 "int digits = DBL_MANT_DIG;\n",
366 ));
367 assert!(text.contains("const 8 : int"), "{text}");
368 assert!(text.contains("const 9223372036854775807 : long"), "{text}");
369 assert!(text.contains("const 2 : int"), "{text}");
370 assert!(text.contains("const 53 : int"), "{text}");
371 }
372
373 #[test]
377 fn the_shipped_stdint_writes_the_whole_set_when_there_is_no_library_to_defer_to() {
378 let text = shipped(concat!(
379 "#include <stdint.h>\n",
380 "int64_t a = INT64_C(1);\n",
381 "uint_least16_t b;\n",
382 "intptr_t c;\n",
383 "uintmax_t d = UINTMAX_MAX;\n",
384 "int wide = sizeof(int_fast64_t);\n",
385 ));
386 assert!(text.contains("decl #0 a : long"), "{text}");
387 assert!(text.contains("decl #1 b : unsigned short"), "{text}");
388 assert!(text.contains("decl #2 c : long"), "{text}");
389 }
390
391 #[test]
392 fn the_three_formality_headers_still_have_to_work() {
393 let text = shipped(concat!(
394 "#include <stdbool.h>\n",
395 "#include <stdalign.h>\n",
396 "#include <iso646.h>\n",
397 "#include <stdnoreturn.h>\n",
398 "int t = true and not false;\n",
399 "_Alignas(16) char buf[16];\n",
400 "int a = alignof(long);\n",
401 ));
402 assert!(text.contains("decl #0 t : int"), "{text}");
403 assert!(text.contains("const 8 : unsigned long"), "{text}");
404 }
405
406 #[test]
409 fn every_shipped_header_can_be_included_twice() {
410 let mut source = String::new();
411 for _ in 0..2 {
412 for name in rucc_session::runtime::names() {
413 source.push_str(&format!("#include <{name}>\n"));
414 }
415 }
416 source.push_str("int x;\n");
417 let text = shipped(&source);
418 assert!(text.starts_with("decl #0 x : int"), "{text}");
419 }
420
421 #[test]
422 fn a_file_that_is_not_there_says_so_and_produces_nothing() {
423 let fs = MemoryFileSystem::new();
424 let result = compile(&options(), "/nope.c", &fs);
425 assert!(result.failed());
426 assert!(result.messages[0].contains("/nope.c"), "{:?}", result.messages);
427 assert!(result.text.is_empty());
428 }
429
430 #[test]
431 fn an_object_comes_out_with_its_type_its_linkage_and_how_much_of_a_definition_it_is() {
432 let text = tast("int x = 1;\n");
433 let expected = "\
434decl #0 x : int object external static defined
435 init
436 +0
437 const 1 : int
438";
439 assert_eq!(text, expected);
440 }
441
442 #[test]
443 fn the_macros_are_expanded_before_anything_is_parsed() {
444 let text = tast("#define N 2\nint a[N];\n");
448 assert!(text.starts_with("decl #0 a : int[2] object external static tentative"), "{text}");
449 }
450
451 #[test]
457 fn a_pragma_is_not_a_declaration_and_the_parse_walks_past_the_ones_it_does_not_read() {
458 let text = tast(concat!(
459 "#pragma pack(4)\n",
460 "struct s { int a; };\n",
461 "#pragma pack()\n",
462 "int b;\n",
463 "_Pragma(\"GCC visibility push(default)\") int c;\n",
464 ));
465 assert!(text.contains("decl #0 b : int"), "{text}");
466 assert!(text.contains("decl #1 c : int"), "{text}");
467 }
468
469 #[test]
477 fn the_layout_attributes_move_the_members_and_the_record_the_way_gcc_lays_them_out() {
478 tast(concat!(
479 "struct A { char c; int i; } __attribute__((packed));\n",
480 "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
481 "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
482 "struct B { char c; int i; } __attribute__((aligned));\n",
485 "_Static_assert(sizeof(struct B) == 16 && _Alignof(struct B) == 16, \"B\");\n",
486 "struct C { char c; int i __attribute__((packed)); };\n",
487 "_Static_assert(sizeof(struct C) == 5 && _Alignof(struct C) == 1, \"C\");\n",
488 "_Static_assert(__builtin_offsetof(struct C, i) == 1, \"C.i\");\n",
489 "struct D { char c; int i; } __attribute__((packed, aligned(4)));\n",
490 "_Static_assert(sizeof(struct D) == 8 && _Alignof(struct D) == 4, \"D\");\n",
491 "_Static_assert(__builtin_offsetof(struct D, i) == 1, \"D.i\");\n",
492 "struct E { char c; _Alignas(8) int i; };\n",
493 "_Static_assert(sizeof(struct E) == 16 && _Alignof(struct E) == 8, \"E\");\n",
494 "_Static_assert(__builtin_offsetof(struct E, i) == 8, \"E.i\");\n",
495 "struct F { char c; int i __attribute__((aligned(8))); };\n",
496 "_Static_assert(sizeof(struct F) == 16 && _Alignof(struct F) == 8, \"F\");\n",
497 "struct G { char c; short s; } __attribute__((aligned(2)));\n",
500 "_Static_assert(sizeof(struct G) == 4 && _Alignof(struct G) == 2, \"G\");\n",
501 "struct H { char c; int i; } __attribute__((aligned(2)));\n",
502 "_Static_assert(sizeof(struct H) == 8 && _Alignof(struct H) == 4, \"H\");\n",
503 "struct I { [[gnu::packed]] char c; int i; };\n",
506 "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
507 "struct J { char c; [[gnu::packed]] int i; };\n",
508 "_Static_assert(sizeof(struct J) == 5 && _Alignof(struct J) == 1, \"J\");\n",
509 "struct M { char c; int i : 5; int j : 20; } __attribute__((packed));\n",
510 "_Static_assert(sizeof(struct M) == 5 && _Alignof(struct M) == 1, \"M\");\n",
511 "struct N { char c; long long l; } __attribute__((aligned(32)));\n",
512 "_Static_assert(sizeof(struct N) == 32 && _Alignof(struct N) == 32, \"N\");\n",
513 "union L { char c; int i; } __attribute__((packed));\n",
514 "_Static_assert(sizeof(union L) == 4 && _Alignof(union L) == 1, \"L\");\n",
515 ));
516 }
517
518 #[test]
528 fn packing_is_what_decides_whether_a_bit_field_may_straddle_its_own_storage() {
529 assert_eq!(bit_field_byte("struct s { int x : 12; char y : 6; };"), 2);
531 assert_eq!(
532 bit_field_byte("struct s { int x : 12; char y : 6; } __attribute__((packed));"),
533 1
534 );
535 assert_eq!(
536 bit_field_byte("struct s { int x : 12; __attribute__((packed)) char y : 6; };"),
537 1
538 );
539 assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { int x : 12; char y : 6; };"), 1);
540 assert_eq!(bit_field_byte("struct s { char x; int y : 30; };"), 4);
542 assert_eq!(bit_field_byte("struct s { char x; int y : 30; } __attribute__((packed));"), 1);
543 assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { char x; int y : 30; };"), 1);
545 assert_eq!(bit_field_byte("#pragma pack(2)\nstruct s { char x; int y : 30; };"), 1);
546 }
547
548 fn bit_field_byte(record: &str) -> u64 {
550 let source = format!("{record}\nint f(struct s *p) {{ return p->y; }}\n");
551 let body = body(&source);
552 let Some((before, _)) = body.split_once("ptr_add") else { return 0 };
553 let (_, constant) = before.rsplit_once("iconst.i64 ").expect("an offset constant");
554 constant.lines().next().expect("a line").trim().parse().expect("a byte offset")
555 }
556
557 #[test]
563 fn an_attribute_among_the_specifiers_is_kept_beside_the_ones_written_in_front() {
564 tast(concat!(
565 "struct a { char c; __attribute__((aligned(8))) int i; };\n",
566 "_Static_assert(sizeof(struct a) == 16 && _Alignof(struct a) == 8, \"a\");\n",
567 "_Static_assert(__builtin_offsetof(struct a, i) == 8, \"a.i\");\n",
568 "struct b { char c; __attribute__((packed)) int i; };\n",
569 "_Static_assert(sizeof(struct b) == 5 && _Alignof(struct b) == 1, \"b\");\n",
570 "_Static_assert(__builtin_offsetof(struct b, i) == 1, \"b.i\");\n",
571 "typedef struct { char c; int i; } __attribute__((packed)) c;\n",
572 "_Static_assert(sizeof(c) == 5 && _Alignof(c) == 1, \"c\");\n",
573 ));
574 }
575
576 #[test]
582 fn pragma_pack_caps_every_member_and_is_read_where_the_body_closes() {
583 tast(concat!(
584 "#pragma pack(1)\n",
585 "struct A { char c; int i; };\n",
586 "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
587 "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
588 "#pragma pack()\n",
589 "struct B { char c; int i; };\n",
590 "_Static_assert(sizeof(struct B) == 8 && _Alignof(struct B) == 4, \"B\");\n",
591 "#pragma pack(2)\n",
592 "struct C { char c; int i; double d; };\n",
593 "_Static_assert(sizeof(struct C) == 14 && _Alignof(struct C) == 2, \"C\");\n",
594 "_Static_assert(__builtin_offsetof(struct C, d) == 6, \"C.d\");\n",
595 "struct K { char c; int i __attribute__((aligned(8))); };\n",
597 "_Static_assert(sizeof(struct K) == 6 && _Alignof(struct K) == 2, \"K\");\n",
598 "_Static_assert(__builtin_offsetof(struct K, i) == 2, \"K.i\");\n",
599 "struct J { char c; int i; } __attribute__((aligned(8)));\n",
601 "_Static_assert(sizeof(struct J) == 8 && _Alignof(struct J) == 8, \"J\");\n",
602 "#pragma pack()\n",
603 "#pragma pack(push, 1)\n",
604 "struct D { char c; short s; };\n",
605 "_Static_assert(sizeof(struct D) == 3 && _Alignof(struct D) == 1, \"D\");\n",
606 "#pragma pack(pop)\n",
607 "struct E { char c; short s; };\n",
608 "_Static_assert(sizeof(struct E) == 4 && _Alignof(struct E) == 2, \"E\");\n",
609 "struct H { char c;\n",
611 "#pragma pack(1)\n",
612 " int i; };\n",
613 "_Static_assert(sizeof(struct H) == 5 && _Alignof(struct H) == 1, \"H\");\n",
614 "#pragma pack(1)\n",
615 "struct I { char c;\n",
616 "#pragma pack()\n",
617 " int i; };\n",
618 "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
619 "#pragma pack()\n",
620 "#pragma pack(push, 8)\n",
622 "#pragma pack(push, 1)\n",
623 "struct P { char c; int i; };\n",
624 "_Static_assert(sizeof(struct P) == 5 && _Alignof(struct P) == 1, \"P\");\n",
625 "#pragma pack(pop)\n",
626 "struct Q { char c; int i; };\n",
627 "_Static_assert(sizeof(struct Q) == 8 && _Alignof(struct Q) == 4, \"Q\");\n",
628 "#pragma pack(pop)\n",
629 "#pragma pack(16)\n",
631 "struct R { char c; int i; };\n",
632 "_Static_assert(sizeof(struct R) == 8 && _Alignof(struct R) == 4, \"R\");\n",
633 "#pragma pack()\n",
634 "#pragma pack(1)\n",
635 "struct S { char c; int i : 5; int j : 20; };\n",
636 "_Static_assert(sizeof(struct S) == 5 && _Alignof(struct S) == 1, \"S\");\n",
637 "union T { char c; int i; };\n",
638 "_Static_assert(sizeof(union T) == 4 && _Alignof(union T) == 1, \"T\");\n",
639 "#pragma pack()\n",
640 ));
641 }
642
643 #[test]
647 fn a_pack_line_that_is_not_one_is_reported_in_the_words_gcc_uses() {
648 let result = run(
649 &options(),
650 concat!(
651 "#pragma pack 4\n",
652 "#pragma pack(pop)\n",
653 "#pragma pack(3)\n",
654 "#pragma pack(1) junk\n",
655 "#pragma pack(push, 1\n",
656 "#pragma pack(x)\n",
657 "#pragma pack(0)\n",
660 "#pragma pack(push)\n",
661 "struct s { char c; int i; };\n",
662 "#pragma pack(pop)\n",
663 "#pragma pack(pop, foo)\n",
664 ),
665 );
666 let expected = [
667 "missing `(` after `#pragma pack` - ignored",
668 "`#pragma pack (pop)` encountered without matching `#pragma pack (push)`",
669 "alignment must be a small power of two, not 3",
670 "junk at end of `#pragma pack`",
671 "malformed `#pragma pack(push[, id][, <n>])` - ignored",
672 "unknown action `x` for `#pragma pack` - ignored",
673 "`#pragma pack(pop, foo)` encountered without matching `#pragma pack(push, foo)`",
674 ];
675 assert_eq!(result.messages.len(), expected.len(), "{:?}", result.messages);
676 for (message, want) in result.messages.iter().zip(expected) {
677 assert!(message.contains(want), "expected {want:?} in {message:?}");
678 }
679 }
680
681 #[test]
685 fn the_wide_integer_answers_to_all_three_of_its_names() {
686 let text = tast("__uint128_t a; __int128_t b; unsigned __int128 c;\n");
687 assert!(text.contains("decl #0 a : unsigned __int128"), "{text}");
688 assert!(text.contains("decl #1 b : __int128"), "{text}");
689 assert!(text.contains("decl #2 c : unsigned __int128"), "{text}");
690 }
691
692 #[test]
693 fn every_conversion_the_language_performs_is_a_node_in_the_output() {
694 let text = tast("long f(int a, long b) { return a + b; }\n");
698 assert!(text.contains("convert arithmetic"), "{text}");
699 }
700
701 #[test]
702 fn a_mistake_in_each_phase_reaches_the_caller_and_writes_no_tree() {
703 for source in [
704 "#error stop\n",
705 "int f(void) { return 1 + ; }\n",
706 "int f(void) { return undeclared; }\n",
707 ] {
708 let result = run(&options(), source);
709 assert!(result.failed(), "expected this to fail:\n{source}");
710 assert!(result.text.is_empty(), "a file that did not compile wrote a tree:\n{source}");
711 }
712 }
713
714 #[test]
715 fn one_undeclared_name_is_one_message_and_not_one_per_use() {
716 let result = run(&options(), "int f(void) { return nope + nope * nope; }\n");
720 assert_eq!(result.errors, 1, "{:?}", result.messages);
721 }
722
723 #[test]
724 fn a_declaration_the_parser_skipped_does_not_become_an_undeclared_name_as_well() {
725 let result = run(&options(), "int x = ;\nint f(void) { return x; }\n");
729 assert_eq!(result.errors, 1, "{:?}", result.messages);
730 }
731
732 #[test]
733 fn werror_turns_a_warning_into_an_error_in_the_count_and_in_the_word() {
734 let source = "int f(void) { char c = 300; return c; }\n";
735 let plain = run(&options(), source);
736 assert_eq!(plain.errors, 0, "{:?}", plain.messages);
737 assert_eq!(plain.messages.len(), 1, "expected a warning about the narrowed constant");
738 assert!(!plain.text.is_empty(), "a warning is not a reason to write nothing");
739
740 let mut opts = options();
741 opts.warnings_are_errors = true;
742 let strict = run(&opts, source);
743 assert!(strict.failed());
744 assert!(strict.text.is_empty(), "and under -Werror it is a reason to write nothing");
745 for message in &strict.messages {
746 assert!(!message.contains("warning:"), "{message}");
747 }
748 }
749
750 #[test]
751 fn the_dialect_reaches_the_keywords_and_the_checking() {
752 let source = "typeof(1) x;\n";
755 let mut opts = options();
756 opts.std = Std::C23;
757 opts.gnu_extensions = false;
758 assert!(!run(&opts, source).failed(), "{:?}", run(&opts, source).messages);
759
760 opts.std = Std::C17;
761 assert!(run(&opts, source).failed());
762 }
763
764 #[test]
765 fn asking_for_a_kind_that_is_not_written_yet_runs_the_front_end_and_writes_nothing() {
766 let mut opts = options();
767 opts.emit = EmitKind::MirFinal;
768 let result = run(&opts, "int x = 1;\n");
769 assert!(!result.failed(), "{:?}", result.messages);
770 assert!(result.text.is_empty());
771 assert!(run(&opts, "int f(void) { return undeclared; }\n").failed());
774 }
775
776 fn ir(source: &str) -> String {
778 let mut opts = options();
779 opts.emit = EmitKind::Ir;
780 let result = run(&opts, source);
781 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
782 result.text
783 }
784
785 fn body(source: &str) -> String {
787 let text = ir(source);
788 let (_, rest) = text.split_once("{\n").expect("a function definition");
789 let (body, _) = rest.rsplit_once("}\n").expect("a function definition");
790 body.to_owned()
791 }
792
793 #[test]
801 fn builtin_constant_p_is_folded_where_it_is_written_rather_than_called() {
802 let text = ir(concat!(
803 "int g;\n",
804 "int a = __builtin_constant_p(1);\n",
805 "int b = __builtin_constant_p(g);\n",
806 "int c = __builtin_constant_p(\"abc\");\n",
807 "int d = __builtin_constant_p(&g);\n",
808 "int e = __builtin_constant_p(1.5);\n",
809 "int h = __builtin_choose_expr(__builtin_constant_p(3), 11, 22);\n",
810 ));
811 assert!(text.contains("global @a : i32 = 1,"), "{text}");
812 assert!(text.contains("global @b : i32 = 0,"), "{text}");
813 assert!(text.contains("global @c : i32 = 1,"), "{text}");
814 assert!(text.contains("global @d : i32 = 0,"), "{text}");
815 assert!(text.contains("global @e : i32 = 1,"), "{text}");
816 assert!(text.contains("global @h : i32 = 11,"), "{text}");
817 assert!(!text.contains("__builtin_constant_p"), "it is not a call to anything:\n{text}");
818
819 let text = body("int f(void) { int i = 0; __builtin_constant_p(i++); return i; }\n");
823 assert_eq!(text, "block0:\n %0 = iconst.i32 0\n %1 = iconst.i32 0\n return %0\n");
824 }
825
826 #[test]
835 fn a_call_to_a_library_builtin_reaches_the_library_function() {
836 let text = body("void f(void) { __builtin_abort(); }\n");
837 assert_eq!(text, "block0:\n call @abort() : ()\n return\n");
838
839 let text = ir("int f(const char *s) { return __builtin_puts(s) + __builtin_strlen(s); }\n");
842 assert!(text.contains("call @puts(%0) : (ptr) -> i32"), "{text}");
843 assert!(text.contains("call @strlen(%0) : (ptr) -> i64"), "{text}");
844 assert!(!text.contains("__builtin_"), "the prefix is not part of any name here:\n{text}");
845 }
846
847 #[test]
854 fn a_library_builtin_is_diagnosed_under_the_name_the_program_wrote() {
855 let mut opts = options();
856 opts.emit = EmitKind::Ir;
857 let messages = run(&opts, "void f(void) { __builtin_abort(1); }\n").messages;
858 assert!(
859 messages.iter().any(|m| m.contains("__builtin_abort")),
860 "expected the written name in {messages:?}"
861 );
862 }
863
864 #[test]
871 fn a_classification_c_has_an_operator_for_is_that_operator() {
872 for (builtin, operator) in [
873 ("__builtin_isgreater", "binary >"),
874 ("__builtin_isgreaterequal", "binary >="),
875 ("__builtin_isless", "binary <"),
876 ("__builtin_islessequal", "binary <="),
877 ] {
878 let source = format!("int f(double x, double y) {{ return {builtin}(x, y); }}\n");
879 let text = tast(&source);
880 assert!(text.contains(&format!("{operator} : int")), "for {builtin}:\n{text}");
881 }
882 }
883
884 #[test]
893 fn the_classification_builtins_are_comparisons_and_not_calls() {
894 let text = body("int f(double x, double y) { return __builtin_isunordered(x, y); }\n");
895 assert_eq!(
896 text,
897 "block0(%0: f64, %1: f64):\n %2 = fcmp uno %0, %1\n %3 = zext.i32 \
898 %2\n return %3\n"
899 );
900
901 let text = body("int f(double x, double y) { return __builtin_islessgreater(x, y); }\n");
903 assert!(text.contains("fcmp one %0, %1"), "{text}");
904
905 let text = body("int f(double x) { return __builtin_isnan(x); }\n");
906 assert!(text.contains("fcmp uno %0, %0"), "{text}");
907
908 let text = body("int f(double x) { return __builtin_isinf(x); }\n");
909 assert!(text.contains("fconst.f64 0x7ff0000000000000"), "{text}");
910 assert!(text.contains("fconst.f64 0xfff0000000000000"), "{text}");
911 assert!(text.contains("%3 = fcmp oeq %0, %1"), "{text}");
912 assert!(text.contains("%4 = fcmp oeq %0, %2"), "{text}");
913 assert!(text.contains("%5 = or %3, %4"), "{text}");
914
915 let text = body("int f(double x) { return __builtin_isfinite(x); }\n");
918 assert!(text.contains("%3 = fcmp olt %2, %0"), "{text}");
919 assert!(text.contains("%4 = fcmp olt %0, %1"), "{text}");
920 assert!(text.contains("%5 = and %3, %4"), "{text}");
921
922 let text = body("int f(double x) { return __builtin_signbit(x); }\n");
923 assert!(text.contains("%1 = bitcast.i64 %0"), "{text}");
924 assert!(text.contains("icmp slt %1, %2"), "{text}");
925
926 let text = body("int f(long double x) { return __builtin_signbitl(x); }\n");
929 assert!(text.contains("%1 = bitcast.i80 %0"), "{text}");
930
931 let text = body("double g(void);\nint f(void) { return __builtin_isnan(g()); }\n");
934 assert_eq!(text.matches("call @g()").count(), 1, "{text}");
935 }
936
937 #[test]
944 fn a_classification_spelling_that_names_a_width_converts_before_it_asks() {
945 let text = ir(concat!(
946 "int a = __builtin_isinff(1e300);\n",
947 "int b = __builtin_isinf(1e300);\n",
948 "int c = __builtin_isnan(0.0);\n",
952 "int d = __builtin_signbit(-0.0);\n",
953 "int e = __builtin_islessgreater(1.0, 2.0);\n",
954 ));
955 assert!(text.contains("global @a : i32 = 1,"), "{text}");
956 assert!(text.contains("global @b : i32 = 0,"), "{text}");
957 assert!(text.contains("global @c : i32 = 0,"), "{text}");
958 assert!(text.contains("global @d : i32 = 1,"), "{text}");
959 assert!(text.contains("global @e : i32 = 1,"), "{text}");
960 }
961
962 #[test]
964 fn a_classification_builtin_refuses_an_argument_that_is_not_floating_point() {
965 let mut opts = options();
966 opts.emit = EmitKind::Ir;
967 let source = concat!(
968 "int a(int x) { return __builtin_isnan(x); }\n",
969 "int b(int x, int y) { return __builtin_isunordered(x, y); }\n",
970 "int c(double x) { return __builtin_isnan(x, x); }\n",
971 );
972 let messages = run(&opts, source).messages;
973 assert_eq!(
974 messages,
975 [
976 "/main.c:1:23: error: non-floating-point argument in call to function \
977 '__builtin_isnan' [E0685]",
978 "/main.c:2:30: error: non-floating-point arguments in call to function \
979 '__builtin_isunordered' [E0685]",
980 "/main.c:3:26: error: too many arguments to function '__builtin_isnan' [E0511]",
981 ]
982 );
983 }
984
985 #[test]
993 fn a_builtin_whose_answer_is_a_constant_is_one_and_not_a_call() {
994 let text = ir(concat!(
995 "double a = __builtin_inf();\n",
996 "float b = __builtin_huge_valf();\n",
997 "long double c = __builtin_infl();\n",
998 "double d = __builtin_huge_val();\n",
999 ));
1000 assert!(text.contains("global @a : f64 = 0x7ff0000000000000,"), "{text}");
1001 assert!(text.contains("global @b : f32 = 0x7f800000,"), "{text}");
1002 assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
1003 assert!(text.contains("global @d : f64 = 0x7ff0000000000000,"), "{text}");
1004 assert!(!text.contains("call"), "{text}");
1005 }
1006
1007 #[test]
1016 fn a_nan_is_written_with_the_payload_the_program_asked_for() {
1017 let text = ir(concat!(
1018 "double a = __builtin_nan(\"\");\n",
1019 "double b = __builtin_nan(\"0x1\");\n",
1020 "double c = __builtin_nan(\"010\");\n",
1022 "double d = __builtin_nans(\"\");\n",
1023 "double e = __builtin_nans(\"0x1\");\n",
1024 "float f = __builtin_nanf(\"0x1\");\n",
1025 "float g = __builtin_nansf(\"\");\n",
1026 "long double h = __builtin_nansl(\"\");\n",
1027 ));
1028 assert!(text.contains("global @a : f64 = 0x7ff8000000000000,"), "{text}");
1029 assert!(text.contains("global @b : f64 = 0x7ff8000000000001,"), "{text}");
1030 assert!(text.contains("global @c : f64 = 0x7ff8000000000008,"), "{text}");
1031 assert!(text.contains("global @d : f64 = 0x7ff4000000000000,"), "{text}");
1032 assert!(text.contains("global @e : f64 = 0x7ff0000000000001,"), "{text}");
1033 assert!(text.contains("global @f : f32 = 0x7fc00001,"), "{text}");
1034 assert!(text.contains("global @g : f32 = 0x7fa00000,"), "{text}");
1035 assert!(text.contains("f80 0x7fffa000000000000000"), "{text}");
1036
1037 let text = ir(concat!(
1040 "double f(const char *p) { return __builtin_nan(p); }\n",
1041 "double g(void) { return __builtin_nans(\"1x\"); }\n",
1042 ));
1043 assert_eq!(text.matches("call @nan(").count(), 1, "{text}");
1044 assert_eq!(text.matches("call @nans(").count(), 1, "{text}");
1045 }
1046
1047 #[test]
1055 fn the_length_and_the_order_of_a_string_literal_are_known_here() {
1056 let text = ir(concat!(
1057 "unsigned long a = __builtin_strlen(\"hello\");\n",
1058 "unsigned long b = __builtin_strlen(\"a\\0bc\");\n",
1059 "int c = __builtin_strcmp(\"X\", \"X\\376\") < 0;\n",
1060 "int d = __builtin_strcmp(\"abc\", \"abc\");\n",
1061 "int e = __builtin_strcmp(\"abc\", \"ab\") > 0;\n",
1062 ));
1063 assert!(text.contains("global @a : i64 = 5,"), "{text}");
1064 assert!(text.contains("global @b : i64 = 1,"), "{text}");
1065 assert!(text.contains("global @c : i32 = 1,"), "{text}");
1066 assert!(text.contains("global @d : i32 = 0,"), "{text}");
1067 assert!(text.contains("global @e : i32 = 1,"), "{text}");
1068 assert!(!text.contains("call"), "{text}");
1069
1070 let text = ir("unsigned long f(const char *p) { return __builtin_strlen(p); }\n");
1072 assert!(text.contains("call @strlen("), "{text}");
1073 }
1074
1075 #[test]
1082 fn a_sign_builtin_is_a_mask_over_the_bits_and_not_a_call() {
1083 let text = body("double f(double x) { return __builtin_fabs(x); }\n");
1084 assert!(text.contains("bitcast.i64 %0"), "{text}");
1085 assert!(text.contains("iconst.i64 9223372036854775807"), "{text}");
1086 assert!(text.contains("and %1, %2"), "{text}");
1087 assert!(text.contains("bitcast.f64 %3"), "{text}");
1088 assert!(!text.contains("call"), "{text}");
1089
1090 let text = body("double f(double x, double y) { return __builtin_copysign(x, y); }\n");
1091 assert!(text.contains("iconst.i64 -9223372036854775808"), "{text}");
1092 assert!(text.contains("%8 = or %4, %7"), "{text}");
1093 assert!(!text.contains("call"), "{text}");
1094
1095 let text = body("long double f(long double x) { return __builtin_fabsl(x); }\n");
1098 assert!(text.contains("bitcast.i80 %0"), "{text}");
1099 assert!(text.contains("bitcast.f80"), "{text}");
1100
1101 let text = body("double f(float x) { return __builtin_fabs(x); }\n");
1104 assert!(text.contains("fpext.f64 %0"), "{text}");
1105 assert!(text.contains("bitcast.i64 %1"), "{text}");
1106 }
1107
1108 #[test]
1117 fn the_sign_builtins_answer_a_zero_and_a_nan_the_way_the_bits_say() {
1118 let text = ir(concat!(
1119 "double a = __builtin_fabs(-3.5);\n",
1120 "double b = __builtin_copysign(1.0, -0.0);\n",
1121 "double c = __builtin_copysign(0.0, -2.0);\n",
1122 "double d = __builtin_copysign(-__builtin_nan(\"\"), 1.0);\n",
1124 "double e = __builtin_fabs(-__builtin_nan(\"0x1\"));\n",
1125 "float g = __builtin_copysignf(-0.0f, 2.0f);\n",
1126 "long double h = __builtin_copysignl(1.0L, -1.0L);\n",
1127 "long double i = __builtin_fabsl(-__builtin_infl());\n",
1128 ));
1129 assert!(text.contains("global @a : f64 = 0x400c000000000000,"), "{text}");
1130 assert!(text.contains("global @b : f64 = 0xbff0000000000000,"), "{text}");
1131 assert!(text.contains("global @c : f64 = 0x8000000000000000,"), "{text}");
1132 assert!(text.contains("global @d : f64 = 0x7ff8000000000000,"), "{text}");
1133 assert!(text.contains("global @e : f64 = 0x7ff8000000000001,"), "{text}");
1134 assert!(text.contains("global @g : f32 = 0x0,"), "{text}");
1135 assert!(text.contains("f80 0xbfff8000000000000000"), "{text}");
1136 assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
1137 }
1138
1139 #[test]
1146 fn a_constexpr_object_is_a_constant_wherever_one_is_required() {
1147 let text = ir(concat!(
1148 "constexpr int side = 4;\n",
1149 "constexpr int wider = side + 1;\n",
1150 "constexpr double half = 1.5;\n",
1151 "struct point { int x; int y; };\n",
1152 "constexpr struct point origin = { 5, 6 };\n",
1153 "int square[side * side];\n",
1154 "int rectangle[wider];\n",
1155 "int rounded[(int)half * 2];\n",
1156 "int across[origin.y];\n",
1157 "enum named { four = side };\n",
1158 "int e = four;\n",
1159 ));
1160 assert!(text.contains("global @square : bytes 64 ="), "{text}");
1161 assert!(text.contains("global @rectangle : bytes 20 ="), "{text}");
1162 assert!(text.contains("global @rounded : bytes 8 ="), "{text}");
1163 assert!(text.contains("global @across : bytes 24 ="), "{text}");
1164 assert!(text.contains("global @e : i32 = 4,"), "{text}");
1165
1166 let mut opts = options();
1169 opts.emit = EmitKind::Ir;
1170 let konst = "const int n = 1;\nint a[n];\n";
1171 let message = "/main.c:2:5: error: variably modified 'a' at file scope [E0538]";
1172 assert_eq!(run(&opts, konst).messages, [message]);
1173
1174 let subscript = "constexpr int t[3] = { 1, 2, 3 };\nint a[t[1]];\n";
1176 assert_eq!(run(&opts, subscript).messages, [message]);
1177
1178 let address = "constexpr int c = 3;\nint *p = &c;\n";
1180 let warning = "/main.c:2:6: warning: initialization discards 'const' qualifier from \
1181 pointer target type [E0514]";
1182 assert_eq!(run(&opts, address).messages, [warning]);
1183 }
1184
1185 #[test]
1194 fn an_old_style_definition_takes_its_types_from_the_declarations_under_its_list() {
1195 let mut opts = options();
1198 opts.std = Std::C17;
1199 let source = concat!(
1200 "int add(a, b)\n",
1201 "int a;\n",
1202 "int b;\n",
1203 "{ return a + b; }\n",
1204 "int promoted(c)\n",
1205 "char c;\n",
1206 "{ return c; }\n",
1207 "int narrow(char);\n",
1208 "int narrow(c)\n",
1209 "char c;\n",
1210 "{ return c; }\n",
1211 "int first(a)\n",
1212 "int a[4];\n",
1213 "{ return a[0]; }\n",
1214 );
1215 let result = run(&opts, source);
1216 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1217 let text = result.text;
1218 assert!(text.contains("add : int(int, int) function external defined"), "{text}");
1219 assert!(text.contains("promoted : int(int) function external defined"), "{text}");
1220 assert!(text.contains("c : char object automatic defined"), "{text}");
1222 assert!(text.contains("narrow : int(char) function external defined"), "{text}");
1223 assert!(text.contains("first : int(int *) function external defined"), "{text}");
1225 }
1226
1227 #[test]
1234 fn the_two_halves_of_an_old_style_parameter_list_have_to_agree() {
1235 let mut opts = options();
1236 opts.std = Std::C17;
1237 for (source, message) in [
1238 ("int f(a, a)\nint a;\n{ return a; }\n", "1:10: error: multiple parameters named 'a'"),
1239 (
1240 "int f(a)\nint a;\nint b;\n{ return a; }\n",
1241 "3:5: error: declaration for parameter 'b' but no such parameter",
1242 ),
1243 ("int f(a)\nint a;\nint a;\n{ return a; }\n", "3:5: error: redefinition of parameter"),
1244 ("int f(a)\nint a = 1;\n{ return a; }\n", "2:5: error: parameter 'a' is initialized"),
1245 (
1246 "int f(a)\nstatic int a;\n{ return a; }\n",
1247 "2:12: error: storage class specified for parameter 'a'",
1248 ),
1249 (
1250 "int f(char);\nint f(a)\nshort a;\n{ return a; }\n",
1251 "2:7: error: argument 'a' doesn't match prototype",
1252 ),
1253 ] {
1254 let result = run(&opts, source);
1255 assert!(result.failed(), "expected this to fail:\n{source}");
1256 assert!(result.messages[0].contains(message), "{:?}", result.messages);
1257 }
1258
1259 let implicit = "int f(a, b)\nint a;\n{ return a + b; }\n";
1262 let mut older = options();
1263 older.std = Std::C89;
1264 assert!(!run(&older, implicit).failed(), "{:?}", run(&older, implicit).messages);
1265 let result = run(&opts, implicit);
1266 assert!(
1267 result.messages[0].contains("1:10: error: type of 'b' defaults to 'int'"),
1268 "{:?}",
1269 result.messages
1270 );
1271
1272 let mut newer = options();
1276 newer.std = Std::C23;
1277 let plain = "int f(a)\nint a;\n{ return a; }\n";
1278 let result = run(&newer, plain);
1279 assert!(!result.failed(), "{:?}", result.messages);
1280 assert_eq!(
1281 result.messages,
1282 ["/main.c:1:5: warning: old-style function definition [E0412]"]
1283 );
1284 assert!(run(&opts, plain).messages.is_empty(), "and nothing to say in the dialects before");
1285 }
1286
1287 #[test]
1294 fn a_type_is_refused_when_it_passes_the_largest_object_and_not_before() {
1295 let text = ir(concat!(
1296 "struct huge_struct { short buf[(1L << 62) - 256]; int a, b, c, d; };\n",
1297 "struct brim { char buf[9223372036854775807L]; };\n",
1298 "struct bitty { char buf[9223372036854775800L]; int x : 1; };\n",
1299 "unsigned long h = sizeof(struct huge_struct);\n",
1300 "unsigned long b = sizeof(struct brim);\n",
1301 "unsigned long y = sizeof(struct bitty);\n",
1302 ));
1303 assert!(text.contains("global @h : i64 = 9223372036854775312,"), "{text}");
1304 assert!(text.contains("global @b : i64 = 9223372036854775807,"), "{text}");
1305 assert!(text.contains("global @y : i64 = 9223372036854775804,"), "{text}");
1306
1307 let mut opts = options();
1308 opts.emit = EmitKind::Ir;
1309 let over = "struct over { char buf[9223372036854775800L]; char x[8]; };\n";
1310 let message = "/main.c:1:1: error: type 'struct over' is too large [E0560]";
1311 assert_eq!(run(&opts, over).messages, [message]);
1312 let array = "struct wide { short buf[1L << 62]; };\n";
1313 let message = "/main.c:1:25: error: size of array 'buf' exceeds \
1314 maximum object size '9223372036854775807' [E0537]";
1315 assert_eq!(run(&opts, array).messages[0], message);
1316 }
1317
1318 fn compile_bytes(source: &[u8]) -> Compiled {
1323 let mut opts = options();
1324 opts.emit = EmitKind::Ir;
1325 let mut fs = MemoryFileSystem::new();
1326 fs.insert("/main.c", source.to_vec());
1327 compile(&opts, "/main.c", &fs)
1328 }
1329
1330 #[test]
1337 fn a_byte_that_is_not_a_character_is_kept_in_a_literal_and_refused_outside_one() {
1338 let mut source = b"char s[] = \"a".to_vec();
1339 source.push(0xff);
1340 source.extend_from_slice(b"b\";\nchar c = '");
1341 source.push(0xff);
1342 source.extend_from_slice(b"';\n");
1343 let result = compile_bytes(&source);
1344 assert_eq!(result.messages, Vec::<String>::new(), "a raw byte in a literal is that byte");
1345 assert!(result.text.contains(r#"bytes "a\ffb\00""#), "{}", result.text);
1346 assert!(result.text.contains("global @c : i8 = -1,"), "{}", result.text);
1348
1349 let mut stray = b"int a".to_vec();
1350 stray.push(0xff);
1351 stray.extend_from_slice(b" = 1;\n");
1352 let result = compile_bytes(&stray);
1353 assert!(
1354 result.messages.iter().any(|m| m.contains("source is not valid UTF-8 here")),
1355 "{:?}",
1356 result.messages
1357 );
1358 }
1359
1360 #[test]
1361 fn an_object_becomes_a_global_with_an_image_and_a_function_becomes_a_func() {
1362 let text = ir("int x = 7;\nint add(int a, int b) { return a + b; }\n");
1363 assert!(text.contains("global @x : i32 = 7, align 4, linkage(external)\n"), "{text}");
1364 let expected = "\
1365func @add(i32, i32) -> i32, linkage(external) {
1366block0(%0: i32, %1: i32):
1367 %2 = add.nsw %0, %1
1368 return %2
1369}
1370";
1371 assert!(text.contains(expected), "{text}");
1372 }
1373
1374 #[test]
1375 fn a_local_nothing_takes_the_address_of_is_a_value_and_never_a_stack_slot() {
1376 let text = body("int f(int n) { int a = n + 1; int b = a * 2; return a + b; }\n");
1377 assert!(!text.contains("alloca"), "{text}");
1378 assert!(!text.contains("load"), "{text}");
1379 assert!(!text.contains("store"), "{text}");
1380 }
1381
1382 #[test]
1383 fn a_local_whose_address_is_taken_gets_a_slot_in_the_entry_block() {
1384 let text = body("int g(int *);\nint f(void) { int a = 1; return g(&a); }\n");
1385 let expected = "\
1386block0:
1387 %0 = alloca, size 4, align 4
1388 %1 = iconst.i32 1
1389 store %1 -> %0, align 4
1390 %2 = call @g(%0) : (ptr) -> i32
1391 return %2
1392";
1393 assert_eq!(text, expected);
1394 }
1395
1396 #[test]
1397 fn a_loop_carries_what_it_changes_as_block_parameters() {
1398 let text = body(
1401 "int f(int n) {\n int total = 0;\n for (int i = 0; i < n; i++) total += i;\n \
1402 return total;\n}\n",
1403 );
1404 assert!(!text.contains("alloca"), "{text}");
1405 assert!(text.contains("block1(%3: i32, %4: i32):"), "{text}");
1406 assert!(text.contains("jump block1("), "{text}");
1407 }
1408
1409 #[test]
1410 fn a_comparison_used_as_a_condition_is_not_widened_and_narrowed_again() {
1411 let text = body("int f(int a, int b) { if (a < b) return 1; return 0; }\n");
1412 assert!(text.contains("icmp slt %0, %1"), "{text}");
1413 assert!(!text.contains("zext"), "{text}");
1414 }
1415
1416 #[test]
1417 fn the_right_side_of_a_short_circuit_is_in_a_block_of_its_own() {
1418 let text = body("int f(int a, int b) { return a && b; }\n");
1419 let expected = "\
1420block0(%0: i32, %1: i32):
1421 %2 = iconst.i32 0
1422 %3 = icmp ne %0, %2
1423 %4 = iconst.i1 0
1424 br_if %3, block1, block2(%4)
1425
1426block1:
1427 %5 = iconst.i32 0
1428 %6 = icmp ne %1, %5
1429 jump block2(%6)
1430
1431block2(%7: i1):
1432 %8 = zext.i32 %7
1433 return %8
1434";
1435 assert_eq!(text, expected);
1436 }
1437
1438 #[test]
1439 fn code_after_a_return_is_not_built_and_does_not_leave_an_empty_block_behind() {
1440 let text = body("int f(int a) { if (a) return 1; else return 2; return 3; }\n");
1441 assert!(!text.contains("block3"), "{text}");
1444 assert!(!text.contains("iconst.i32 3"), "{text}");
1445 }
1446
1447 #[test]
1448 fn falling_off_the_end_returns_zero_from_main_and_nothing_from_a_void_function() {
1449 assert!(body("int main(void) { }\n").contains("iconst.i32 0\n return"));
1450 assert_eq!(body("void f(void) { }\n"), "block0:\n return\n");
1451 assert!(body("int f(void) { }\n").contains("unreachable"));
1452 }
1453
1454 #[test]
1455 fn a_structure_is_copied_rather_than_held_in_a_value() {
1456 let text = body(
1457 "struct point { int x, y; };\n\
1458 int f(void) { struct point p = { 1, 2 }; struct point q = p; return q.x; }\n",
1459 );
1460 assert!(text.contains("memcpy"), "{text}");
1461 }
1462
1463 #[test]
1464 fn an_initializer_that_leaves_part_of_an_object_unwritten_zeroes_it_first() {
1465 let text = body("int f(void) { int a[4] = { 1 }; return a[3]; }\n");
1466 assert!(text.contains("memset"), "{text}");
1467 }
1468
1469 #[test]
1470 fn a_switch_is_one_branch_and_a_case_that_falls_through_carries_what_it_wrote() {
1471 let text = body(
1472 "int f(int x) { int r = 0; switch (x) { case 1: r = 1; case 2: r += 2; break; \
1473 default: r = 4; } return r; }\n",
1474 );
1475 let expected = "\
1476block0(%0: i32):
1477 %1 = iconst.i32 0
1478 switch %0, block1, [1 => block2, 2 => block3(%1)]
1479
1480block1:
1481 %2 = iconst.i32 4
1482 jump block4(%2)
1483
1484block2:
1485 %3 = iconst.i32 1
1486 jump block3(%3)
1487
1488block3(%4: i32):
1489 %5 = iconst.i32 2
1490 %6 = add.nsw %4, %5
1491 jump block4(%6)
1492
1493block4(%7: i32):
1494 return %7
1495";
1496 assert_eq!(text, expected);
1497 }
1498
1499 #[test]
1500 fn a_case_range_is_tested_for_rather_than_put_in_the_table() {
1501 let text = body("int f(int x) { switch (x) { case 1 ... 9: return 1; } return 0; }\n");
1504 assert!(text.contains("%2 = sub %0, %1"), "{text}");
1505 assert!(text.contains("icmp ule"), "{text}");
1506 assert!(!text.contains("switch"), "{text}");
1507 }
1508
1509 #[test]
1510 fn break_leaves_the_switch_and_continue_leaves_the_loop_around_it() {
1511 let text = body(
1512 "int f(int n) { int t = 0; for (int i = 0; i < n; i++) { switch (i) { \
1513 case 0: continue; case 1: break; default: t += i; } t++; } return t; }\n",
1514 );
1515 assert!(text.contains("switch %3, block4, [0 => block5, 1 => block6]"), "{text}");
1518 assert!(text.contains("block5:\n jump block7("), "{text}");
1519 assert!(text.contains("block6:\n jump block8("), "{text}");
1520 }
1521
1522 #[test]
1523 fn a_switch_with_nothing_to_branch_on_still_runs_what_comes_after_it() {
1524 assert_eq!(body("void f(int x) { switch (x) { } }\n"), "block0(%0: i32):\n return\n");
1525 }
1526
1527 #[test]
1528 fn a_label_a_loop_is_only_entered_through_builds_the_loop_around_it() {
1529 let text = body(
1534 "int f(int x, int n) { switch (x) { case 1: break; while (n) { case 2: n--; } } \
1535 return n; }\n",
1536 );
1537 assert!(text.contains("switch %0, block1(%1), [1 => block2, 2 => block3(%1)]"), "{text}");
1540 assert!(text.contains("block3(%3: i32):\n %4 = iconst.i32 1"), "{text}");
1541 assert!(text.contains("block5:\n jump block3("), "{text}");
1542 }
1543
1544 #[test]
1545 fn a_goto_into_a_loop_body_enters_it_without_the_test() {
1546 let text = body("int f(int x, int n) { goto in; while (n) { in: n--; } return n; }\n");
1549 assert!(text.starts_with("block0(%0: i32, %1: i32):\n jump block1(%1)"), "{text}");
1550 assert!(text.contains("block1(%2: i32):\n %3 = iconst.i32 1"), "{text}");
1551 assert!(text.contains("br_if %7, block3, block4"), "{text}");
1552 }
1553
1554 #[test]
1555 fn a_goto_is_a_jump_to_the_block_the_label_starts() {
1556 let text = body("int f(int x) { int r = 0; if (x) goto out; r = 1; out: return r; }\n");
1557 assert!(!text.contains("alloca"), "{text}");
1559 assert!(text.contains("block3(%4: i32):\n return %4"), "{text}");
1560 assert_eq!(text.matches("jump block3(").count(), 2, "{text}");
1561 }
1562
1563 #[test]
1564 fn a_backward_goto_is_a_loop_and_carries_what_it_changes() {
1565 let text =
1566 body("int f(int n) { int i = 0; again: if (i < n) { i++; goto again; } return i; }\n");
1567 assert!(!text.contains("alloca"), "{text}");
1568 assert!(text.contains("block1(%2: i32):"), "{text}");
1569 assert!(text.contains("jump block1(%5)"), "{text}");
1570 }
1571
1572 #[test]
1573 fn a_label_nothing_reaches_is_taken_out_rather_than_left_for_the_verifier() {
1574 assert_eq!(
1577 body("int f(int x) { return x; spare: return 0; }\n"),
1578 "block0(%0: i32):\n return %0\n"
1579 );
1580 }
1581
1582 #[test]
1583 fn a_bit_field_is_read_by_loading_the_bytes_it_lies_in_and_shifting() {
1584 let text = body(
1585 "struct s { unsigned a : 3; signed b : 5; };\nint f(struct s *p) { return p->b; }\n",
1586 );
1587 assert_eq!(
1590 text,
1591 "\
1592block0(%0: ptr):
1593 %1 = load.i8 %0, align 1
1594 %2 = iconst.i8 3
1595 %3 = ashr %1, %2
1596 %4 = sext.i32 %3
1597 return %4
1598"
1599 );
1600 }
1601
1602 #[test]
1603 fn a_store_to_a_bit_field_does_not_write_a_byte_it_has_no_bit_in() {
1604 let text =
1608 body("struct s { int a : 24; char c; };\nvoid f(struct s *p, int v) { p->a = v; }\n");
1609 assert_eq!(
1610 text,
1611 "\
1612block0(%0: ptr, %1: i32):
1613 %2 = iconst.i32 16777215
1614 %3 = and %1, %2
1615 %4 = trunc.i16 %3
1616 store %4 -> %0, align 2
1617 %5 = iconst.i32 16
1618 %6 = lshr %3, %5
1619 %7 = trunc.i8 %6
1620 %8 = iconst.i64 2
1621 %9 = ptr_add %0, %8
1622 store %7 -> %9, align 1
1623 return
1624"
1625 );
1626 }
1627
1628 #[test]
1629 fn what_an_assignment_to_a_bit_field_is_worth_is_what_fits_in_it() {
1630 let text =
1631 body("struct s { unsigned b : 5; };\nunsigned f(struct s *p) { return p->b = 33; }\n");
1632 assert!(text.contains("%3 = iconst.i8 31\n %4 = and %2, %3"), "{text}");
1635 assert!(text.ends_with("%9 = zext.i32 %4\n return %9\n"), "{text}");
1636 }
1637
1638 #[test]
1639 fn an_assignment_a_statement_throws_away_builds_none_of_what_it_is_worth() {
1640 let text = body("struct s { signed b : 5; };\nvoid f(struct s *p) { p->b = 3; }\n");
1643 assert_eq!(text.matches("ashr").count(), 0, "{text}");
1644 assert!(text.ends_with("store %8 -> %0, align 1\n return\n"), "{text}");
1645 }
1646
1647 #[test]
1648 fn a_bit_field_in_an_initializer_goes_in_over_bytes_that_were_zeroed_first() {
1649 let text = body(
1653 "struct s { int a : 3; int b; };\nint f(void) { struct s v = { 1 }; return v.b; }\n",
1654 );
1655 assert!(text.contains("memset %0, %1, size 8, align 4"), "{text}");
1656 }
1657
1658 #[test]
1659 fn the_image_of_a_static_bit_field_is_the_bytes_the_fields_share() {
1660 let text = ir("struct s { unsigned a : 3; unsigned b : 5; } g = { 1, 2 };\n");
1663 assert!(
1664 text.contains("global @g : bytes 4 = { bytes \"\\11\", zero 3 }, align 4"),
1665 "{text}"
1666 );
1667 }
1668
1669 #[test]
1670 fn an_initialized_flexible_array_member_makes_the_object_larger_than_its_type() {
1671 let text = ir(concat!(
1676 "struct a { int i; int j[]; } x = { 1, { 2, 0, 2, 3 } };\n",
1677 "struct b { char c; char p[]; } y = { 'o', \"wx\" };\n",
1678 "struct c { char c; char p[]; } z = { '9', { 'e', 'b' } };\n",
1679 "char s[2] = \"hi\";\n",
1680 ));
1681 assert!(
1682 text.contains("global @x : bytes 20 = { i32 1, i32 2, i32 0, i32 2, i32 3 }"),
1683 "{text}"
1684 );
1685 assert!(text.contains("global @y : bytes 4 = { i8 111, bytes \"wx\\00\" }"), "{text}");
1686 assert!(text.contains("global @z : bytes 3 = { i8 57, i8 101, i8 98 }"), "{text}");
1687 assert!(text.contains("global @s : bytes 2 = { bytes \"hi\" }"), "{text}");
1690 }
1691
1692 #[test]
1693 fn a_definition_takes_a_parameter_it_left_unnamed() {
1694 let text = ir("int f(int a, int) { return a; }\n");
1698 assert!(text.contains("func @f(i32, i32) -> i32"), "{text}");
1699 assert!(text.contains("block0(%0: i32, %1: i32):"), "{text}");
1700
1701 let text = ir("int g(int, int n) { return n; }\n");
1704 assert!(text.contains("block0(%0: i32, %1: i32):\n return %1\n"), "{text}");
1705 }
1706
1707 #[test]
1708 fn an_assignment_of_a_structure_is_the_object_it_wrote() {
1709 let text = body(concat!(
1714 "struct s { int f; int g; };\n",
1715 "void h(struct s *a, struct s *c, struct s *d, struct s *e)\n",
1716 "{ *d = *e = a[0] = *c; }\n",
1717 ));
1718 assert_eq!(text.matches("memcpy").count(), 3, "{text}");
1719 assert!(text.contains("memcpy %8, %1, size 8, align 4\n"), "{text}");
1720 assert!(text.contains("memcpy %3, %8, size 8, align 4\n"), "{text}");
1721 assert!(text.contains("memcpy %2, %3, size 8, align 4\n"), "{text}");
1722 }
1723
1724 #[test]
1725 fn a_string_literal_stops_at_the_end_of_the_array_it_is_filling() {
1726 let mut opts = options();
1731 opts.emit = EmitKind::Ir;
1732 let result = run(
1733 &opts,
1734 concat!(
1735 "const char a[2][3] = { \"1234\", \"xyz\" };\n",
1736 "static const char b[3][5] = { \"12345\", \"678\", \"9\" };\n",
1737 "union u { struct { char x[4]; char y[4]; }; struct { char z[8]; }; };\n",
1738 "const union u c = { { \"1234\", \"567\" } };\n",
1739 ),
1740 );
1741 let text = result.text;
1742 assert_eq!(
1743 result.messages,
1744 ["/main.c:1:24: warning: initializer-string for array of 'const char' is too long \
1745 (5 chars into 3 available) [E0637]"]
1746 );
1747 assert!(text.contains("global @a : bytes 6 = { bytes \"123\", bytes \"xyz\" }"), "{text}");
1748 assert!(
1749 text.contains(
1750 "global @b : bytes 15 = { bytes \"12345\", bytes \"678\\00\", zero 1, \
1751 bytes \"9\\00\", zero 3 }"
1752 ),
1753 "{text}"
1754 );
1755 assert!(
1758 text.contains("global @c : bytes 8 = { bytes \"1234\", bytes \"567\\00\" }"),
1759 "{text}"
1760 );
1761 }
1762
1763 #[test]
1764 fn a_cast_of_a_record_to_its_own_type_is_the_object_that_was_cast() {
1765 let text = body(concat!(
1769 "struct s { int a, b; };\nstruct v { struct s s; int t; };\n",
1770 "void g(struct v *);\n",
1771 "void f(struct s *p) { struct v w = { (struct s)*p, 5 }; g(&w); }\n",
1772 ));
1773 assert_eq!(text.matches("memcpy").count(), 1, "{text}");
1774 }
1775
1776 #[test]
1777 fn a_compound_literal_read_in_a_static_initializer_lays_its_bytes_into_the_image() {
1778 let text = ir(concat!(
1783 "struct s { int x; };\n",
1784 "struct t { struct s s; int o; } a = { (struct s){ 2 }, 3 };\n",
1785 "int n = (int){ 7 };\n",
1786 "struct u { struct s p; struct s q; } b = { (struct s){ 1 }, (struct s){ } };\n",
1787 ));
1788 assert!(text.contains("global @a : bytes 8 = { i32 2, i32 3 }"), "{text}");
1789 assert!(text.contains("global @n : i32 = 7,"), "{text}");
1790 assert!(text.contains("global @b : bytes 8 = { i32 1, zero 4 }"), "{text}");
1793 }
1794
1795 #[test]
1796 fn the_address_of_a_compound_literal_asks_for_the_object_it_points_at() {
1797 let text = ir("struct s { int x; };\nstruct s *q = &(struct s){ 9 };\n");
1801 assert!(text.contains("global @.Lanon.0 : i32 = 9, align 4, linkage(internal)"), "{text}");
1802 assert!(text.contains("global @q : bytes 8 = { addr.8 @.Lanon.0 }"), "{text}");
1803 }
1804
1805 #[test]
1806 fn an_object_of_no_size_at_all_has_an_image_with_nothing_in_it() {
1807 let text = ir("unsigned char foo[1][0];\n");
1811 assert!(text.contains("global @foo : bytes 0 = {}, align 1"), "{text}");
1812 }
1813
1814 #[test]
1815 fn a_null_pointer_in_an_image_is_the_bits_an_address_has_room_for() {
1816 let text = ir("void *p = 0;\nchar *q = (char *) 4096;\n");
1819 assert!(text.contains("global @p : i64 = 0, align 8"), "{text}");
1820 assert!(text.contains("global @q : i64 = 4096, align 8"), "{text}");
1821 }
1822
1823 #[test]
1824 fn an_object_another_module_defines_may_be_one_that_cannot_be_written_through() {
1825 let text = ir("extern const int limit;\nint f(void) { return limit; }\n");
1829 assert!(
1830 text.contains("global @limit : bytes 4, align 4, linkage(external), constant"),
1831 "{text}"
1832 );
1833 }
1834
1835 #[test]
1836 fn a_conditional_whose_value_is_an_object_answers_where_the_object_is() {
1837 let text = body(
1842 "\
1843struct s { int a, b; };
1844struct s pick(int c, struct s x, struct s y) { return c ? x : y; }
1845",
1846 );
1847 assert!(text.contains("block3(%7: ptr)"), "{text}");
1849 assert!(text.contains("jump block3(%3)") && text.contains("jump block3(%4)"), "{text}");
1850 assert!(!text.contains("memcpy"), "the arms are joined rather than copied: {text}");
1851 }
1852
1853 #[test]
1854 fn a_structure_that_fits_in_registers_travels_as_the_registers_it_fits_in() {
1855 let text = ir("\
1859struct pair { int a, b; };
1860struct pair make(int a, int b);
1861struct pair twice(struct pair p) { return make(p.a, p.b); }
1862");
1863 assert!(text.contains("func @make(i32, i32) -> i64"), "{text}");
1864 assert!(text.contains("func @twice(i64) -> i64"), "{text}");
1865 }
1866
1867 #[test]
1868 fn a_structure_too_large_for_the_registers_travels_as_where_its_bytes_are() {
1869 let text = ir("\
1873struct big { double v[8]; };
1874struct big grow(struct big b);
1875struct big twice(struct big b) { return grow(grow(b)); }
1876");
1877 assert!(
1878 text.contains("func @grow(ptr sret(64, align 8), ptr byval(64, align 8))"),
1879 "{text}"
1880 );
1881 assert!(text.contains("block0(%0: ptr, %1: ptr):"), "{text}");
1882 assert_eq!(text.matches("call @grow").count(), 2, "{text}");
1885 }
1886
1887 #[test]
1888 fn a_structure_passed_to_a_variadic_function_says_so_at_the_call() {
1889 let text = ir("\
1894struct big { double v[8]; };
1895struct pair { int a, b; };
1896int p(const char *, ...);
1897int f(struct big b, struct pair q) { return p(\"\", 1, b, q); }
1898");
1899 assert!(
1900 text.contains("call @p(%4, %5, %2 byval(64, align 8), %6) : (ptr, ...) -> i32"),
1901 "{text}"
1902 );
1903 }
1904
1905 #[test]
1906 fn what_a_call_produced_is_somewhere_before_anything_is_read_out_of_it() {
1907 let body = body(
1910 "\
1911struct pair { int a, b; };
1912struct pair make(int a, int b);
1913int second(void) { return make(1, 2).b; }
1914",
1915 );
1916 assert!(body.starts_with("block0:\n %0 = alloca, size 8, align 4\n"), "{body}");
1917 assert!(body.contains("store %3 -> %0, align 4\n"), "{body}");
1918 }
1919
1920 #[test]
1921 fn a_structure_of_floats_travels_in_floating_point_registers_on_aarch64() {
1922 let source = "\
1926struct hfa { float x, y, z; };
1927int take(struct hfa h);
1928int give(struct hfa h) { return take(h); }
1929";
1930 assert!(ir(source).contains("func @take(f64, f32) -> i32"), "{}", ir(source));
1931 let mut opts = options();
1932 opts.emit = EmitKind::Ir;
1933 opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
1934 let result = run(&opts, source);
1935 assert_eq!(result.messages, Vec::<String>::new());
1936 assert!(result.text.contains("func @take(f32, f32, f32) -> i32"), "{}", result.text);
1937 }
1938
1939 #[test]
1940 fn an_array_whose_length_is_not_a_constant_is_a_slot_made_where_its_declaration_is() {
1941 let source = "\
1944int use(int *);
1945void f(int n) {
1946 {
1947 int a[n];
1948 use(a);
1949 }
1950 use(0);
1951}
1952";
1953 let body = body(source);
1954 assert!(body.contains("mul.nsw"), "{body}");
1955 assert!(body.contains("stacksave"), "{body}");
1956 assert!(body.contains("alloca %"), "{body}");
1957 assert!(body.contains("stackrestore"), "{body}");
1958 }
1959
1960 #[test]
1961 fn a_goto_out_of_the_scope_of_one_gives_its_stack_back_on_the_way() {
1962 let source = "\
1967int use(int *);
1968int f(int n) {
1969 {
1970 int a[n];
1971 if (use(a)) goto out;
1972 use(0);
1973 }
1974out:
1975 return 0;
1976}
1977";
1978 let body = body(source);
1979 assert_eq!(body.matches("stackrestore").count(), 2, "{body}");
1981 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
1982 assert!(after.starts_with(" %4\n jump block"), "{body}");
1983 }
1984
1985 #[test]
1986 fn a_goto_to_a_label_the_array_is_still_alive_at_leaves_the_stack_alone() {
1987 let source = "\
1991int use(int *);
1992int f(int n) {
1993 int a[n];
1994again:
1995 if (use(a)) goto again;
1996 return 0;
1997}
1998";
1999 let body = body(source);
2000 assert!(body.contains("stacksave"), "{body}");
2001 assert!(!body.contains("stackrestore"), "{body}");
2002 }
2003
2004 #[test]
2005 fn a_goto_back_to_a_label_in_front_of_one_gives_it_back_every_time_round() {
2006 let source = "\
2011int use(int *);
2012int f(int n) {
2013again:
2014 {
2015 int a[n];
2016 if (use(a)) goto again;
2017 }
2018 return 0;
2019}
2020";
2021 let body = body(source);
2022 assert_eq!(body.matches("stacksave").count(), 1, "{body}");
2023 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
2024 assert!(after.starts_with(" %4\n jump block1\n"), "{body}");
2025 }
2026
2027 #[test]
2028 fn the_head_of_a_for_loop_is_a_scope_that_closes_where_the_loop_is_left() {
2029 let source = "\
2035int f(void);
2036void t(void) {
2037 int count = 10;
2038 for (; count--;) {
2039 int b[f()];
2040 int i;
2041 for (i = 0; i < f(); i++) {
2042 b[i] = count;
2043 }
2044 }
2045}
2046";
2047 let body = body(source);
2048 assert_eq!(body.matches("stacksave").count(), 1, "{body}");
2052 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
2053 let (next, _) = after.split_once("\n\n").expect("a block after the restore");
2054 assert!(next.contains("jump block1("), "{body}");
2055 }
2056
2057 #[test]
2058 fn how_long_one_of_those_is_was_decided_where_it_was_declared_and_not_where_it_is_asked() {
2059 let source = "\
2062unsigned long f(int n) {
2063 int a[n];
2064 n = 0;
2065 return sizeof a;
2066}
2067";
2068 let body = body(source);
2069 assert_eq!(body.matches("sext.i64 %0").count(), 2, "{body}");
2071 }
2072
2073 #[test]
2074 fn a_block_in_the_middle_of_an_expression_is_walked_where_the_expression_is() {
2075 let source = "\
2078int use(int);
2079int f(int x) {
2080 return ({
2081 int t = use(x);
2082 t * t;
2083 });
2084}
2085";
2086 let expected = "\
2087block0(%0: i32):
2088 %1 = call @use(%0) : (i32) -> i32
2089 %2 = mul.nsw %1, %1
2090 return %2
2091";
2092 assert_eq!(body(source), expected);
2093 }
2094
2095 #[test]
2096 fn one_of_those_that_control_never_leaves_is_lowered_and_what_follows_it_is_dropped() {
2097 let source = "int f(int x) { return ({ return x; 0; }); }\n";
2101 assert_eq!(body(source), "block0(%0: i32):\n return %0\n");
2102 }
2103
2104 #[test]
2105 fn one_argument_off_a_variable_argument_list_stays_an_intrinsic() {
2106 let source = "double f(__builtin_va_list ap) { return __builtin_va_arg(ap, double) + __builtin_va_arg(ap, double); }\n";
2110 let expected = "\
2111block0(%0: ptr):
2112 %1 = va_arg.f64 %0
2113 %2 = va_arg.f64 %0
2114 %3 = fadd %1, %2
2115 return %3
2116";
2117 assert_eq!(body(source), expected);
2118 }
2119
2120 #[test]
2121 fn one_that_reads_a_structure_answers_where_the_object_is() {
2122 let source = "\
2129struct s { int a; long b; };
2130long f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.b; }
2131";
2132 let expected = "\
2133block0(%0: ptr):
2134 %1 = alloca, size 16, align 8
2135 %2 = va_object %0, size 16, align 8
2136 memcpy %1, %2, size 16, align 8
2137 %3 = iconst.i64 8
2138 %4 = ptr_add %1, %3
2139 %5 = load.i64 %4, align 8
2140 return %5
2141";
2142 assert_eq!(body(source), expected);
2143 }
2144
2145 #[test]
2146 fn a_jump_to_an_address_branches_to_every_label_the_function_takes_the_address_of() {
2147 let source = "\
2151int f(int c) {
2152 void *p = c ? &&one : &&two;
2153 goto *p;
2154one:
2155 return 1;
2156two:
2157 return 2;
2158}
2159";
2160 let expected = "\
2161block0(%0: i32):
2162 %1 = iconst.i32 0
2163 %2 = icmp ne %0, %1
2164 br_if %2, block1, block2
2165
2166block1:
2167 %3 = block_addr block3
2168 jump block4(%3)
2169
2170block2:
2171 %4 = block_addr block5
2172 jump block4(%4)
2173
2174block3:
2175 %5 = iconst.i32 1
2176 return %5
2177
2178block4(%6: ptr):
2179 indirect_br %6, block3, block5
2180
2181block5:
2182 %7 = iconst.i32 2
2183 return %7
2184";
2185 assert_eq!(body(source), expected);
2186 }
2187
2188 #[test]
2189 fn a_jump_to_an_address_no_label_in_the_function_has_arrives_nowhere() {
2190 let source = "void **next(void);
2193void f(void) { goto *next(); }
2194";
2195 let expected = "\
2196block0:
2197 %0 = call @next() : () -> ptr
2198 unreachable
2199";
2200 assert_eq!(body(source), expected);
2201 }
2202
2203 #[test]
2204 fn an_asm_with_no_operands_is_volatile_and_the_clobbers_are_the_whole_of_what_it_says() {
2205 let source = "void f(void) { __asm__(\"mfence\" ::: \"memory\"); }\n";
2208 let expected = "\
2209block0:
2210 inline_asm.volatile \"mfence\", \"\", \"memory\"()
2211 return
2212";
2213 assert_eq!(body(source), expected);
2214 }
2215
2216 #[test]
2217 fn the_constraints_are_one_list_in_the_order_the_template_counts_the_operands() {
2218 let source = "\
2221int f(int x, int y) {
2222 int r;
2223 __asm__(\"addl %2, %0\" : \"=r\"(r), \"+r\"(y) : \"r\"(x));
2224 return r + y;
2225}
2226";
2227 let expected = "\
2228block0(%0: i32, %1: i32):
2229 %2, %3 = inline_asm.(i32, i32) \"addl %2, %0\", \"=r,+r,r\", \"\"(%1, %0)
2230 %4 = add.nsw %2, %3
2231 return %4
2232";
2233 assert_eq!(body(source), expected);
2234 }
2235
2236 #[test]
2237 fn a_memory_operand_travels_as_the_address_of_an_object_that_is_given_a_slot() {
2238 let source = "\
2243struct pair { int a, b; };
2244int f(int x) {
2245 int slot = x;
2246 struct pair p = { x, x };
2247 __asm__(\"incl %0\" : \"+m\"(slot), \"=m\"(p));
2248 return slot + p.a;
2249}
2250";
2251 let text = body(source);
2252 assert!(text.contains("inline_asm \"incl %0\", \"+m,=m\", \"\"(%1, %2)\n"), "{text}");
2253 assert!(text.contains("%1 = alloca, size 4, align 4\n"), "{text}");
2254 assert!(text.contains("%2 = alloca, size 8, align 4\n"), "{text}");
2255 }
2256
2257 #[test]
2258 fn an_asm_goto_falls_through_to_its_first_target_and_writes_its_outputs_there() {
2259 let source = "\
2264int f(int x) {
2265 int r = 7;
2266 __asm__ goto(\"cbnz %0, %l1\" : \"=r\"(r) : \"r\"(x) :: away);
2267 return r;
2268away:
2269 return r;
2270}
2271";
2272 let expected = "\
2273block0(%0: i32):
2274 %1 = iconst.i32 7
2275 %2 = inline_asm.volatile \"cbnz %0, %l1\", \"=r,r\", \"\"(%0), labels [block1, block2]
2276
2277block1:
2278 return %2
2279
2280block2:
2281 return %1
2282";
2283 assert_eq!(body(source), expected);
2284 }
2285
2286 #[test]
2287 fn an_asm_statement_that_is_not_well_formed_is_reported_in_the_words_gcc_uses() {
2288 let mut opts = options();
2292 opts.emit = EmitKind::Ir;
2293 for (source, expected) in [
2294 (
2295 "void f(int x) { __asm__(\"\" : \"r\"(x)); }\n",
2296 "output operand constraint lacks '='",
2297 ),
2298 (
2299 "void f(int x) { __asm__(\"\" : \"=r\"(x + 1)); }\n",
2300 "lvalue required in 'asm' statement",
2301 ),
2302 (
2303 "const int g = 1;\nvoid f(void) { __asm__(\"\" : \"=r\"(g)); }\n",
2304 "read-only variable 'g' used as 'asm' output",
2305 ),
2306 (
2307 "void f(int x) { __asm__(\"\" : : \"=r\"(x)); }\n",
2308 "input operand constraint contains '='",
2309 ),
2310 (
2311 "void f(void) { __asm__(\"\" : : \"m\"(1)); }\n",
2312 "memory input 0 is not directly addressable",
2313 ),
2314 ("void f(void) { __asm__(L\"\"); }\n", "wide string literal in 'asm'"),
2315 (
2316 "void f(int x, int y) { __asm__(\"\" : [a] \"=r\"(x) : [a] \"r\"(y)); }\n",
2317 "duplicate asm operand name 'a'",
2318 ),
2319 ("void f(int x) { __asm__(\"%[in]\" : \"=r\"(x)); }\n", "undefined named operand 'in'"),
2320 ] {
2321 let result = run(&opts, source);
2322 assert!(result.failed(), "expected this to be reported:\n{source}");
2323 assert!(
2324 result.messages.iter().any(|m| m.contains(expected)),
2325 "{expected}\n{:?}",
2326 result.messages
2327 );
2328 }
2329 }
2330
2331 #[test]
2332 fn what_the_walk_cannot_build_yet_is_reported_rather_than_mislowered() {
2333 let mut opts = options();
2334 opts.emit = EmitKind::Ir;
2335 for source in [
2336 "int f(int n) { void *p = &&out; if (n) goto *p; { int a[n]; out: return 1; } }\n",
2337 "int f(int n) { int a[n]; __asm__ goto(\"\" ::::out); out: return a[0]; }\n",
2338 ] {
2339 let result = run(&opts, source);
2340 assert!(result.failed(), "expected this to be reported:\n{source}");
2341 assert!(
2342 result.messages.iter().any(|m| m.contains("not supported yet")),
2343 "{:?}",
2344 result.messages
2345 );
2346 }
2347 }
2348
2349 fn round_trip(source: &str) -> (String, String) {
2351 let printed = ir(source);
2352 let mut opts = options();
2353 opts.emit = EmitKind::Ir;
2354 let mut fs = MemoryFileSystem::new();
2355 fs.insert("/main.ir", printed.clone().into_bytes());
2356 let result = compile_ir(&opts, "/main.ir", &fs);
2357 assert_eq!(result.messages, Vec::<String>::new(), "expected this to read back:\n{printed}");
2358 (printed, result.text)
2359 }
2360
2361 #[test]
2362 fn ir_that_arrives_as_an_input_is_read_back_and_written_out_the_same() {
2363 let (printed, again) = round_trip(
2367 "struct point { int x, y; };\n static const char greeting[] = \"hi\";\n int puts(const char *);\n int f(int n) { struct point p = { n, 1 }; puts(greeting); return p.x; }\n",
2368 );
2369 assert_eq!(printed, again);
2370 }
2371
2372 #[test]
2373 fn ir_that_is_not_ir_says_which_line_stopped_it() {
2374 let mut opts = options();
2375 opts.emit = EmitKind::Ir;
2376 let mut fs = MemoryFileSystem::new();
2377 let text = "\
2378; ModuleID = 'a.c'
2379; format 0
2380target triple = \"x86_64-unknown-linux-gnu\"
2381target datalayout = \"e-p:64:64-i64:64-S128\"
2382
2383func @f(), linkage(external) {
2384block0:
2385 frobnicate
2386}
2387";
2388 fs.insert("/main.ir", text.as_bytes().to_vec());
2389 let result = compile_ir(&opts, "/main.ir", &fs);
2390 assert!(result.failed());
2391 assert!(result.messages[0].contains("/main.ir:8"), "{:?}", result.messages);
2392 }
2393
2394 #[test]
2395 fn ir_that_reads_but_does_not_hold_together_is_reported_by_the_verifier() {
2396 let mut opts = options();
2399 opts.emit = EmitKind::Ir;
2400 let mut fs = MemoryFileSystem::new();
2401 let text = "\
2402; ModuleID = 'a.c'
2403; format 0
2404target triple = \"x86_64-unknown-linux-gnu\"
2405target datalayout = \"e-p:64:64-i64:64-S128\"
2406
2407func @f(), linkage(external) {
2408block0:
2409 %0 = iconst.i32 1
2410 return %0
2411}
2412";
2413 fs.insert("/main.ir", text.as_bytes().to_vec());
2414 let result = compile_ir(&opts, "/main.ir", &fs);
2415 assert!(result.failed());
2416 assert!(result.messages[0].contains("invalid IR"), "{:?}", result.messages);
2417 }
2418
2419 #[test]
2420 fn a_typed_tree_is_not_something_an_input_of_ir_can_produce() {
2421 let mut fs = MemoryFileSystem::new();
2423 fs.insert("/main.ir", Vec::new());
2424 let result = compile_ir(&options(), "/main.ir", &fs);
2425 assert!(result.failed());
2426 assert!(result.messages[0].contains("can only be emitted as IR"), "{:?}", result.messages);
2427 }
2428
2429 #[test]
2430 fn the_printed_ir_reads_back_as_the_same_module() {
2431 let text = ir("\
2434struct point { int x, y; };
2435static const char greeting[] = \"hi\";
2436int table[4] = { 1, 2, 3 };
2437int puts(const char *);
2438double half(double x) { return x / 2.0; }
2439int f(int n) {
2440 int total = 0;
2441 for (int i = 0; i < n; i++) {
2442 if (i == 3) continue;
2443 total += table[i];
2444 }
2445 switch (n) {
2446 case 0: total = 1;
2447 case 1: total++; break;
2448 default: total = -total;
2449 }
2450 struct point p = { total, 1 };
2451 int *q = &p.y;
2452 puts(greeting);
2453 return p.x + *q;
2454}
2455int dispatch(int c) {
2456 void *p = c ? &&one : &&two;
2457 goto *p;
2458one:
2459 return 1;
2460two:
2461 return 2;
2462}
2463int assembly(int x, int *p) {
2464 int r;
2465 __asm__ volatile(\"xadd %0, %2\" : \"=r\"(r), \"+m\"(*p) : \"0\"(x) : \"cc\");
2466 __asm__ goto(\"cbnz %0, %l1\" : : \"r\"(r) : : away);
2467 return r;
2468away:
2469 return 0;
2470}
2471");
2472 let mut names = rucc_base::Interner::new();
2473 let module = rucc_ir::parse(&text, &mut names).expect("the printer writes what it reads");
2474 assert_eq!(rucc_ir::print(&module, &names), text);
2475 }
2476}