1use std::path::Path;
14
15use rucc_base::Interner;
16use rucc_codegen::coverage::Fired;
17use rucc_codegen::pipeline::{self, Machine};
18use rucc_diag::{Diagnostic, Severity, Span};
19use rucc_lex::{Convert, Keywords, PpToken, convert};
20use rucc_sema::{Checker, Context as CheckContext};
21use rucc_session::{EmitKind, FileSystem, Options, Session};
22use rucc_target::TargetInfo;
23
24use crate::preprocess::render;
25
26#[derive(Debug, Clone, PartialEq, Eq, Default)]
33pub enum Artifact {
34 #[default]
37 Nothing,
38 Text(String),
40 Object(Vec<u8>),
42}
43
44impl Artifact {
45 #[must_use]
47 pub fn bytes(&self) -> &[u8] {
48 match self {
49 Artifact::Nothing => &[],
50 Artifact::Text(text) => text.as_bytes(),
51 Artifact::Object(bytes) => bytes,
52 }
53 }
54}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct Compiled {
59 pub artifact: Artifact,
61 pub messages: Vec<String>,
63 pub errors: u32,
65 pub fired: Fired,
71}
72
73impl Compiled {
74 #[must_use]
76 pub fn failed(&self) -> bool {
77 self.errors > 0
78 }
79
80 #[must_use]
85 pub fn text(&self) -> &str {
86 match &self.artifact {
87 Artifact::Text(text) => text,
88 _ => "",
89 }
90 }
91}
92
93#[must_use]
106pub fn compile(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
107 let mut sess = Session::new(opts.clone());
108 let keywords = Keywords::new(&mut sess.interner, opts.std, opts.gnu_extensions);
112 let mut diagnostics: Vec<Diagnostic> = Vec::new();
113 let mut fired = Fired::new();
115
116 let bytes = match fs.read(Path::new(name)) {
117 Ok(bytes) => bytes,
118 Err(e) => return failure(format!("{name}: {e}")),
119 };
120 let Ok(file) = sess.sources.add_shared(name, bytes, None) else {
121 return failure(format!("{name}: the source map has no room left for this file"));
122 };
123
124 let mut pp = rucc_pp::Preprocessor::new();
128 let predef = rucc_pp::Predef::for_options(opts);
129 let expanded: Vec<PpToken> = {
130 let mut cx = rucc_pp::Context::new(&mut sess.interner, &mut sess.sources, fs, &opts.search);
131 cx.lex = rucc_lex::Options::for_dialect(opts.std, opts.gnu_extensions);
132 if pp.predefine(&sess.target, &predef, &mut cx).is_err() {
133 return failure(format!("{name}: the source map has no room for the built in macros"));
134 }
135 pp.run(file, &mut cx).iter().map(|token| token.to_pp()).collect()
136 };
137 diagnostics.extend(pp.take_diagnostics());
138
139 let cx = Convert {
142 keywords: &keywords,
143 interner: &sess.interner,
144 target: &sess.target,
145 std: opts.std,
146 gnu: opts.gnu_extensions,
147 pedantic: opts.pedantic,
148 };
149 let (tokens, complaints) = convert(&expanded, &cx);
150 diagnostics.extend(complaints);
151
152 let parsed = rucc_parse::parse(
153 &tokens,
154 rucc_parse::Context {
155 interner: &sess.interner,
156 std: opts.std,
157 gnu: opts.gnu_extensions,
158 pedantic: opts.pedantic,
159 error_limit: opts.error_limit as usize,
160 },
161 );
162 let parse_failed = parsed.diagnostics.iter().any(|d| d.severity.is_fatal());
163 diagnostics.extend(parsed.diagnostics);
164
165 let mut artifact = Artifact::Nothing;
166 if !parse_failed {
167 let mut checker = Checker::new(
168 &parsed.ast,
169 CheckContext {
170 names: &sess.interner,
171 target: &sess.target,
172 std: opts.std,
173 gnu: opts.gnu_extensions,
174 pedantic: opts.pedantic,
175 error_limit: opts.error_limit as usize,
176 },
177 );
178 checker.check_unit();
179 let checked = checker.finish();
180 if !checked.failed() {
181 match opts.emit {
182 EmitKind::Tast => {
183 artifact = Artifact::Text(rucc_sema::print(
184 &checked.tast,
185 &checked.types,
186 &sess.interner,
187 ));
188 }
189 EmitKind::Ir
190 | EmitKind::MirFinal
191 | EmitKind::Asm
192 | EmitKind::Object
193 | EmitKind::Executable => {
194 let mut lowered = rucc_lower::lower(
195 name,
196 rucc_lower::Context {
197 tast: &checked.tast,
198 types: &checked.types,
199 target: &sess.target,
200 names: &mut sess.interner,
201 },
202 );
203 let failed = lowered.diagnostics.iter().any(|d| d.severity.is_fatal());
207 if !failed {
208 if let Err(errors) = rucc_ir::verify(&lowered.module, &sess.interner) {
213 for error in errors {
214 diagnostics.push(internal(&format!("invalid IR, {error}")));
215 }
216 } else if opts.emit == EmitKind::Ir {
217 artifact =
218 Artifact::Text(rucc_ir::print(&lowered.module, &sess.interner));
219 } else {
220 match generate(
223 &mut lowered.module,
224 &mut sess.interner,
225 &sess.target,
226 opts,
227 &mut fired,
228 ) {
229 Ok(made) => artifact = made,
230 Err(complaints) => diagnostics.extend(complaints),
231 }
232 }
233 }
234 diagnostics.extend(lowered.diagnostics);
235 }
236 _ => {}
237 }
238 }
239 diagnostics.extend(checked.diagnostics);
240 }
241
242 let mut messages = Vec::with_capacity(diagnostics.len());
243 let mut errors = 0;
244 for diag in &diagnostics {
245 if diag.severity.is_fatal()
246 || (diag.severity == Severity::Warning && opts.warnings_are_errors)
247 {
248 errors += 1;
249 }
250 messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
251 }
252 if errors > 0 {
253 artifact = Artifact::Nothing;
255 }
256 Compiled { artifact, messages, errors, fired }
259}
260
261#[must_use]
271pub fn compile_ir(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
272 let mut sess = Session::new(opts.clone());
273 if opts.emit != EmitKind::Ir {
274 return failure(format!(
275 "{name}: an input of IR can only be emitted as IR, and `--emit={}` asks for what \
276 the C in front of it became",
277 opts.emit.as_str()
278 ));
279 }
280 let bytes = match fs.read(Path::new(name)) {
281 Ok(bytes) => bytes,
282 Err(e) => return failure(format!("{name}: {e}")),
283 };
284 let Ok(text) = std::str::from_utf8(bytes.as_slice()) else {
285 return failure(format!("{name}: this is not text, so it is not IR"));
286 };
287
288 let module = match rucc_ir::parse(text, &mut sess.interner) {
289 Ok(module) => module,
290 Err(error) => {
291 return failure(format!("{name}:{}: {}", error.line, error.message));
292 }
293 };
294 let mut diagnostics: Vec<Diagnostic> = Vec::new();
295 if let Err(errors) = rucc_ir::verify(&module, &sess.interner) {
296 for error in errors {
297 diagnostics.push(invalid(&format!("invalid IR, {error}")));
298 }
299 }
300 let mut messages = Vec::with_capacity(diagnostics.len());
301 for diag in &diagnostics {
302 messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
303 }
304 let errors = u32::try_from(messages.len()).unwrap_or(u32::MAX);
305 let artifact = if errors > 0 {
306 Artifact::Nothing
307 } else {
308 Artifact::Text(rucc_ir::print(&module, &sess.interner))
309 };
310 Compiled { artifact, messages, errors, fired: Fired::new() }
312}
313
314fn generate(
333 module: &mut rucc_ir::Module,
334 names: &mut Interner,
335 target: &TargetInfo,
336 opts: &Options,
337 fired: &mut Fired,
338) -> Result<Artifact, Vec<Diagnostic>> {
339 let Some(machine) = Machine::for_target(target) else {
340 return Err(vec![unsupported(&format!(
341 "there is no back end for {} in this compiler yet, so there is nothing to generate",
342 target.triple
343 ))]);
344 };
345 let flags = pipeline::Flags { frame_pointer: opts.frame_pointer, red_zone: opts.red_zone };
346
347 let mut funcs = Vec::new();
348 let mut complaints = Vec::new();
349 for id in module.funcs() {
350 if module[id].is_declaration() {
351 continue;
352 }
353 match pipeline::compile_recording(&mut module[id], names, &machine, flags, fired) {
354 Ok(func) => funcs.push(func),
355 Err(why) => {
356 let name = names.resolve(module[id].name).to_owned();
357 let span = why.inst().map_or(Span::DUMMY, |inst| module[id].span(inst));
360 let said = format!("cannot generate code for '{name}': {why}");
361 complaints.push(unsupported_at(&said, span));
362 }
363 }
364 }
365 if !complaints.is_empty() {
366 return Err(complaints);
367 }
368 let globals = match opts.emit {
372 EmitKind::Asm | EmitKind::Object | EmitKind::Executable => {
373 rucc_asm::globals(module, names).map_err(refused)?
374 }
375 _ => rucc_asm::Globals::default(),
376 };
377 match opts.emit {
381 EmitKind::Asm => {
382 rucc_asm::print(&funcs, &globals, names, target).map(Artifact::Text).map_err(refused)
383 }
384 EmitKind::Object | EmitKind::Executable => {
387 let text = rucc_asm::assemble(&funcs, names, target).map_err(refused)?;
388 let data = globals.image();
389 rucc_object::write(&text, &data, target).map(Artifact::Object).map_err(
392 |why| match why {
393 rucc_object::Error::Format { .. } => vec![unsupported(&why.to_string())],
394 rucc_object::Error::Refused { .. } => vec![internal(&why.to_string())],
395 },
396 )
397 }
398 _ => Ok(Artifact::Text(rucc_mir::print(&funcs, names, target.regs))),
399 }
400}
401
402fn refused(why: rucc_asm::Error) -> Vec<Diagnostic> {
408 match why {
409 rucc_asm::Error::Thread { .. } => vec![unsupported(&why.to_string())],
410 _ => vec![internal(&why.to_string())],
411 }
412}
413
414fn unsupported(message: &str) -> Diagnostic {
420 unsupported_at(message, Span::DUMMY)
421}
422
423fn unsupported_at(message: &str, span: Span) -> Diagnostic {
429 Diagnostic::error(message.to_owned(), span)
430 .with_code("E0653")
431 .note("this construct is not lowered yet, see https://github.com/tamnd/rucc/issues", span)
432}
433
434fn invalid(message: &str) -> Diagnostic {
436 Diagnostic::error(message.to_owned(), Span::DUMMY).with_code("E0661")
437}
438
439fn internal(message: &str) -> Diagnostic {
441 Diagnostic::error(format!("internal error: {message}"), Span::DUMMY)
442 .with_code("E0652")
443 .note("this is a bug in rucc rather than in the program, please report it", Span::DUMMY)
444}
445
446fn failure(message: String) -> Compiled {
449 Compiled {
450 artifact: Artifact::Nothing,
451 messages: vec![format!("rucc: error: {message}")],
452 errors: 1,
453 fired: Fired::new(),
454 }
455}
456
457#[cfg(test)]
458mod tests {
459 use rucc_session::{MemoryFileSystem, Std};
460 use rucc_target::Triple;
461
462 use super::*;
463
464 fn options() -> Options {
465 let mut opts = Options::new("x86_64-unknown-linux-gnu".parse::<Triple>().unwrap());
466 opts.emit = EmitKind::Tast;
467 opts
468 }
469
470 fn run(opts: &Options, source: &str) -> Compiled {
471 let mut fs = MemoryFileSystem::new();
472 fs.insert("/main.c", source.to_owned().into_bytes());
473 compile(opts, "/main.c", &fs)
474 }
475
476 fn freestanding() -> Options {
480 let mut opts = options();
481 opts.hosted = false;
482 opts.search.push_system(rucc_session::runtime::DIR);
483 opts
484 }
485
486 fn shipped(source: &str) -> String {
488 let result = run(&freestanding(), source);
489 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
490 result.text().to_owned()
491 }
492
493 fn tast(source: &str) -> String {
495 let result = run(&options(), source);
496 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
497 result.text().to_owned()
498 }
499
500 #[test]
501 fn the_shipped_stdarg_declares_a_list_and_the_four_operators() {
502 let text = shipped(concat!(
503 "#include <stdarg.h>\n",
504 "int sum(int n, ...) {\n",
505 " va_list ap, copy;\n",
506 " va_start(ap, n);\n",
507 " va_copy(copy, ap);\n",
508 " int total = va_arg(ap, int) + va_arg(copy, int);\n",
509 " va_end(ap);\n",
510 " va_end(copy);\n",
511 " return total;\n",
512 "}\n",
513 ));
514 assert!(text.contains("va-start"), "{text}");
515 assert!(text.contains("va-copy"), "{text}");
516 assert!(text.contains("va-arg"), "{text}");
517 assert!(text.contains("va-end"), "{text}");
518 }
519
520 #[test]
524 fn stdarg_hands_out_the_type_alone_when_that_is_all_that_was_asked_for() {
525 let text = shipped(concat!(
526 "#define __need___va_list\n",
527 "#include <stdarg.h>\n",
528 "int vprint(const char *f, __gnuc_va_list ap);\n",
529 "#ifdef va_start\n",
530 "#error va_start should not be defined\n",
531 "#endif\n",
532 "#ifdef _VA_LIST_DEFINED\n",
533 "#error va_list should not have been made\n",
534 "#endif\n",
535 ));
536 assert!(text.contains("vprint"), "{text}");
537 }
538
539 #[test]
542 fn stddef_answers_one_piece_at_a_time_and_the_next_request_still_gets_through() {
543 let text = shipped(concat!(
544 "#define __need_size_t\n",
545 "#include <stddef.h>\n",
546 "#ifdef offsetof\n",
547 "#error offsetof should not be defined yet\n",
548 "#endif\n",
549 "#define __need_ptrdiff_t\n",
550 "#include <stddef.h>\n",
551 "#include <stddef.h>\n",
552 "size_t a;\n",
553 "ptrdiff_t b;\n",
554 "wchar_t c;\n",
555 "max_align_t d;\n",
556 "void *e = NULL;\n",
557 "struct P { int x; long y; };\n",
558 "size_t f = offsetof(struct P, y);\n",
559 ));
560 assert!(text.contains("decl #0 a : unsigned long"), "{text}");
561 assert!(text.contains("decl #1 b : long"), "{text}");
562 }
563
564 #[test]
565 fn the_shipped_limits_and_float_are_the_targets_own_answers() {
566 let text = shipped(concat!(
567 "#include <limits.h>\n",
568 "#include <float.h>\n",
569 "int bits = CHAR_BIT;\n",
570 "long big = LONG_MAX;\n",
571 "int low = INT_MIN;\n",
572 "int radix = FLT_RADIX;\n",
573 "int digits = DBL_MANT_DIG;\n",
574 ));
575 assert!(text.contains("const 8 : int"), "{text}");
576 assert!(text.contains("const 9223372036854775807 : long"), "{text}");
577 assert!(text.contains("const 2 : int"), "{text}");
578 assert!(text.contains("const 53 : int"), "{text}");
579 }
580
581 #[test]
585 fn the_shipped_stdint_writes_the_whole_set_when_there_is_no_library_to_defer_to() {
586 let text = shipped(concat!(
587 "#include <stdint.h>\n",
588 "int64_t a = INT64_C(1);\n",
589 "uint_least16_t b;\n",
590 "intptr_t c;\n",
591 "uintmax_t d = UINTMAX_MAX;\n",
592 "int wide = sizeof(int_fast64_t);\n",
593 ));
594 assert!(text.contains("decl #0 a : long"), "{text}");
595 assert!(text.contains("decl #1 b : unsigned short"), "{text}");
596 assert!(text.contains("decl #2 c : long"), "{text}");
597 }
598
599 #[test]
600 fn the_three_formality_headers_still_have_to_work() {
601 let text = shipped(concat!(
602 "#include <stdbool.h>\n",
603 "#include <stdalign.h>\n",
604 "#include <iso646.h>\n",
605 "#include <stdnoreturn.h>\n",
606 "int t = true and not false;\n",
607 "_Alignas(16) char buf[16];\n",
608 "int a = alignof(long);\n",
609 ));
610 assert!(text.contains("decl #0 t : int"), "{text}");
611 assert!(text.contains("const 8 : unsigned long"), "{text}");
612 }
613
614 #[test]
617 fn every_shipped_header_can_be_included_twice() {
618 let mut source = String::new();
619 for _ in 0..2 {
620 for name in rucc_session::runtime::names() {
621 source.push_str(&format!("#include <{name}>\n"));
622 }
623 }
624 source.push_str("int x;\n");
625 let text = shipped(&source);
626 assert!(text.starts_with("decl #0 x : int"), "{text}");
627 }
628
629 #[test]
630 fn a_file_that_is_not_there_says_so_and_produces_nothing() {
631 let fs = MemoryFileSystem::new();
632 let result = compile(&options(), "/nope.c", &fs);
633 assert!(result.failed());
634 assert!(result.messages[0].contains("/nope.c"), "{:?}", result.messages);
635 assert!(result.text().is_empty());
636 }
637
638 #[test]
639 fn an_object_comes_out_with_its_type_its_linkage_and_how_much_of_a_definition_it_is() {
640 let text = tast("int x = 1;\n");
641 let expected = "\
642decl #0 x : int object external static defined
643 init
644 +0
645 const 1 : int
646";
647 assert_eq!(text, expected);
648 }
649
650 #[test]
651 fn the_macros_are_expanded_before_anything_is_parsed() {
652 let text = tast("#define N 2\nint a[N];\n");
656 assert!(text.starts_with("decl #0 a : int[2] object external static tentative"), "{text}");
657 }
658
659 #[test]
665 fn a_pragma_is_not_a_declaration_and_the_parse_walks_past_the_ones_it_does_not_read() {
666 let text = tast(concat!(
667 "#pragma pack(4)\n",
668 "struct s { int a; };\n",
669 "#pragma pack()\n",
670 "int b;\n",
671 "_Pragma(\"GCC visibility push(default)\") int c;\n",
672 ));
673 assert!(text.contains("decl #0 b : int"), "{text}");
674 assert!(text.contains("decl #1 c : int"), "{text}");
675 }
676
677 #[test]
685 fn the_layout_attributes_move_the_members_and_the_record_the_way_gcc_lays_them_out() {
686 tast(concat!(
687 "struct A { char c; int i; } __attribute__((packed));\n",
688 "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
689 "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
690 "struct B { char c; int i; } __attribute__((aligned));\n",
693 "_Static_assert(sizeof(struct B) == 16 && _Alignof(struct B) == 16, \"B\");\n",
694 "struct C { char c; int i __attribute__((packed)); };\n",
695 "_Static_assert(sizeof(struct C) == 5 && _Alignof(struct C) == 1, \"C\");\n",
696 "_Static_assert(__builtin_offsetof(struct C, i) == 1, \"C.i\");\n",
697 "struct D { char c; int i; } __attribute__((packed, aligned(4)));\n",
698 "_Static_assert(sizeof(struct D) == 8 && _Alignof(struct D) == 4, \"D\");\n",
699 "_Static_assert(__builtin_offsetof(struct D, i) == 1, \"D.i\");\n",
700 "struct E { char c; _Alignas(8) int i; };\n",
701 "_Static_assert(sizeof(struct E) == 16 && _Alignof(struct E) == 8, \"E\");\n",
702 "_Static_assert(__builtin_offsetof(struct E, i) == 8, \"E.i\");\n",
703 "struct F { char c; int i __attribute__((aligned(8))); };\n",
704 "_Static_assert(sizeof(struct F) == 16 && _Alignof(struct F) == 8, \"F\");\n",
705 "struct G { char c; short s; } __attribute__((aligned(2)));\n",
708 "_Static_assert(sizeof(struct G) == 4 && _Alignof(struct G) == 2, \"G\");\n",
709 "struct H { char c; int i; } __attribute__((aligned(2)));\n",
710 "_Static_assert(sizeof(struct H) == 8 && _Alignof(struct H) == 4, \"H\");\n",
711 "struct I { [[gnu::packed]] char c; int i; };\n",
714 "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
715 "struct J { char c; [[gnu::packed]] int i; };\n",
716 "_Static_assert(sizeof(struct J) == 5 && _Alignof(struct J) == 1, \"J\");\n",
717 "struct M { char c; int i : 5; int j : 20; } __attribute__((packed));\n",
718 "_Static_assert(sizeof(struct M) == 5 && _Alignof(struct M) == 1, \"M\");\n",
719 "struct N { char c; long long l; } __attribute__((aligned(32)));\n",
720 "_Static_assert(sizeof(struct N) == 32 && _Alignof(struct N) == 32, \"N\");\n",
721 "union L { char c; int i; } __attribute__((packed));\n",
722 "_Static_assert(sizeof(union L) == 4 && _Alignof(union L) == 1, \"L\");\n",
723 "struct O { char c; int i; } __attribute__((__packed__));\n",
727 "_Static_assert(sizeof(struct O) == 5 && _Alignof(struct O) == 1, \"O\");\n",
728 "struct P { char c; int i; } __attribute__((__aligned__(8)));\n",
729 "_Static_assert(sizeof(struct P) == 8 && _Alignof(struct P) == 8, \"P\");\n",
730 ));
731 }
732
733 #[test]
743 fn packing_is_what_decides_whether_a_bit_field_may_straddle_its_own_storage() {
744 assert_eq!(bit_field_byte("struct s { int x : 12; char y : 6; };"), 2);
746 assert_eq!(
747 bit_field_byte("struct s { int x : 12; char y : 6; } __attribute__((packed));"),
748 1
749 );
750 assert_eq!(
751 bit_field_byte("struct s { int x : 12; __attribute__((packed)) char y : 6; };"),
752 1
753 );
754 assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { int x : 12; char y : 6; };"), 1);
755 assert_eq!(bit_field_byte("struct s { char x; int y : 30; };"), 4);
757 assert_eq!(bit_field_byte("struct s { char x; int y : 30; } __attribute__((packed));"), 1);
758 assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { char x; int y : 30; };"), 1);
760 assert_eq!(bit_field_byte("#pragma pack(2)\nstruct s { char x; int y : 30; };"), 1);
761 }
762
763 fn bit_field_byte(record: &str) -> u64 {
765 let source = format!("{record}\nint f(struct s *p) {{ return p->y; }}\n");
766 let body = body(&source);
767 let Some((before, _)) = body.split_once("ptr_add") else { return 0 };
768 let (_, constant) = before.rsplit_once("iconst.i64 ").expect("an offset constant");
769 constant.lines().next().expect("a line").trim().parse().expect("a byte offset")
770 }
771
772 #[test]
778 fn an_attribute_among_the_specifiers_is_kept_beside_the_ones_written_in_front() {
779 tast(concat!(
780 "struct a { char c; __attribute__((aligned(8))) int i; };\n",
781 "_Static_assert(sizeof(struct a) == 16 && _Alignof(struct a) == 8, \"a\");\n",
782 "_Static_assert(__builtin_offsetof(struct a, i) == 8, \"a.i\");\n",
783 "struct b { char c; __attribute__((packed)) int i; };\n",
784 "_Static_assert(sizeof(struct b) == 5 && _Alignof(struct b) == 1, \"b\");\n",
785 "_Static_assert(__builtin_offsetof(struct b, i) == 1, \"b.i\");\n",
786 "typedef struct { char c; int i; } __attribute__((packed)) c;\n",
787 "_Static_assert(sizeof(c) == 5 && _Alignof(c) == 1, \"c\");\n",
788 ));
789 }
790
791 #[test]
797 fn pragma_pack_caps_every_member_and_is_read_where_the_body_closes() {
798 tast(concat!(
799 "#pragma pack(1)\n",
800 "struct A { char c; int i; };\n",
801 "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
802 "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
803 "#pragma pack()\n",
804 "struct B { char c; int i; };\n",
805 "_Static_assert(sizeof(struct B) == 8 && _Alignof(struct B) == 4, \"B\");\n",
806 "#pragma pack(2)\n",
807 "struct C { char c; int i; double d; };\n",
808 "_Static_assert(sizeof(struct C) == 14 && _Alignof(struct C) == 2, \"C\");\n",
809 "_Static_assert(__builtin_offsetof(struct C, d) == 6, \"C.d\");\n",
810 "struct K { char c; int i __attribute__((aligned(8))); };\n",
812 "_Static_assert(sizeof(struct K) == 6 && _Alignof(struct K) == 2, \"K\");\n",
813 "_Static_assert(__builtin_offsetof(struct K, i) == 2, \"K.i\");\n",
814 "struct J { char c; int i; } __attribute__((aligned(8)));\n",
816 "_Static_assert(sizeof(struct J) == 8 && _Alignof(struct J) == 8, \"J\");\n",
817 "#pragma pack()\n",
818 "#pragma pack(push, 1)\n",
819 "struct D { char c; short s; };\n",
820 "_Static_assert(sizeof(struct D) == 3 && _Alignof(struct D) == 1, \"D\");\n",
821 "#pragma pack(pop)\n",
822 "struct E { char c; short s; };\n",
823 "_Static_assert(sizeof(struct E) == 4 && _Alignof(struct E) == 2, \"E\");\n",
824 "struct H { char c;\n",
826 "#pragma pack(1)\n",
827 " int i; };\n",
828 "_Static_assert(sizeof(struct H) == 5 && _Alignof(struct H) == 1, \"H\");\n",
829 "#pragma pack(1)\n",
830 "struct I { char c;\n",
831 "#pragma pack()\n",
832 " int i; };\n",
833 "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
834 "#pragma pack()\n",
835 "#pragma pack(push, 8)\n",
837 "#pragma pack(push, 1)\n",
838 "struct P { char c; int i; };\n",
839 "_Static_assert(sizeof(struct P) == 5 && _Alignof(struct P) == 1, \"P\");\n",
840 "#pragma pack(pop)\n",
841 "struct Q { char c; int i; };\n",
842 "_Static_assert(sizeof(struct Q) == 8 && _Alignof(struct Q) == 4, \"Q\");\n",
843 "#pragma pack(pop)\n",
844 "#pragma pack(16)\n",
846 "struct R { char c; int i; };\n",
847 "_Static_assert(sizeof(struct R) == 8 && _Alignof(struct R) == 4, \"R\");\n",
848 "#pragma pack()\n",
849 "#pragma pack(1)\n",
850 "struct S { char c; int i : 5; int j : 20; };\n",
851 "_Static_assert(sizeof(struct S) == 5 && _Alignof(struct S) == 1, \"S\");\n",
852 "union T { char c; int i; };\n",
853 "_Static_assert(sizeof(union T) == 4 && _Alignof(union T) == 1, \"T\");\n",
854 "#pragma pack()\n",
855 ));
856 }
857
858 #[test]
862 fn a_pack_line_that_is_not_one_is_reported_in_the_words_gcc_uses() {
863 let result = run(
864 &options(),
865 concat!(
866 "#pragma pack 4\n",
867 "#pragma pack(pop)\n",
868 "#pragma pack(3)\n",
869 "#pragma pack(1) junk\n",
870 "#pragma pack(push, 1\n",
871 "#pragma pack(x)\n",
872 "#pragma pack(0)\n",
875 "#pragma pack(push)\n",
876 "struct s { char c; int i; };\n",
877 "#pragma pack(pop)\n",
878 "#pragma pack(pop, foo)\n",
879 ),
880 );
881 let expected = [
882 "missing `(` after `#pragma pack` - ignored",
883 "`#pragma pack (pop)` encountered without matching `#pragma pack (push)`",
884 "alignment must be a small power of two, not 3",
885 "junk at end of `#pragma pack`",
886 "malformed `#pragma pack(push[, id][, <n>])` - ignored",
887 "unknown action `x` for `#pragma pack` - ignored",
888 "`#pragma pack(pop, foo)` encountered without matching `#pragma pack(push, foo)`",
889 ];
890 assert_eq!(result.messages.len(), expected.len(), "{:?}", result.messages);
891 for (message, want) in result.messages.iter().zip(expected) {
892 assert!(message.contains(want), "expected {want:?} in {message:?}");
893 }
894 }
895
896 #[test]
900 fn the_wide_integer_answers_to_all_three_of_its_names() {
901 let text = tast("__uint128_t a; __int128_t b; unsigned __int128 c;\n");
902 assert!(text.contains("decl #0 a : unsigned __int128"), "{text}");
903 assert!(text.contains("decl #1 b : __int128"), "{text}");
904 assert!(text.contains("decl #2 c : unsigned __int128"), "{text}");
905 }
906
907 #[test]
908 fn every_conversion_the_language_performs_is_a_node_in_the_output() {
909 let text = tast("long f(int a, long b) { return a + b; }\n");
913 assert!(text.contains("convert arithmetic"), "{text}");
914 }
915
916 #[test]
917 fn a_mistake_in_each_phase_reaches_the_caller_and_writes_no_tree() {
918 for source in [
919 "#error stop\n",
920 "int f(void) { return 1 + ; }\n",
921 "int f(void) { return undeclared; }\n",
922 ] {
923 let result = run(&options(), source);
924 assert!(result.failed(), "expected this to fail:\n{source}");
925 assert!(
926 result.text().is_empty(),
927 "a file that did not compile wrote a tree:\n{source}"
928 );
929 }
930 }
931
932 #[test]
933 fn one_undeclared_name_is_one_message_and_not_one_per_use() {
934 let result = run(&options(), "int f(void) { return nope + nope * nope; }\n");
938 assert_eq!(result.errors, 1, "{:?}", result.messages);
939 }
940
941 #[test]
942 fn a_declaration_the_parser_skipped_does_not_become_an_undeclared_name_as_well() {
943 let result = run(&options(), "int x = ;\nint f(void) { return x; }\n");
947 assert_eq!(result.errors, 1, "{:?}", result.messages);
948 }
949
950 #[test]
951 fn werror_turns_a_warning_into_an_error_in_the_count_and_in_the_word() {
952 let source = "int f(void) { char c = 300; return c; }\n";
953 let plain = run(&options(), source);
954 assert_eq!(plain.errors, 0, "{:?}", plain.messages);
955 assert_eq!(plain.messages.len(), 1, "expected a warning about the narrowed constant");
956 assert!(!plain.text().is_empty(), "a warning is not a reason to write nothing");
957
958 let mut opts = options();
959 opts.warnings_are_errors = true;
960 let strict = run(&opts, source);
961 assert!(strict.failed());
962 assert!(strict.text().is_empty(), "and under -Werror it is a reason to write nothing");
963 for message in &strict.messages {
964 assert!(!message.contains("warning:"), "{message}");
965 }
966 }
967
968 #[test]
969 fn the_dialect_reaches_the_keywords_and_the_checking() {
970 let source = "typeof(1) x;\n";
973 let mut opts = options();
974 opts.std = Std::C23;
975 opts.gnu_extensions = false;
976 assert!(!run(&opts, source).failed(), "{:?}", run(&opts, source).messages);
977
978 opts.std = Std::C17;
979 assert!(run(&opts, source).failed());
980 }
981
982 #[test]
983 fn asking_for_a_kind_that_is_not_written_yet_runs_the_front_end_and_writes_nothing() {
984 let mut opts = options();
985 opts.emit = EmitKind::Object;
986 let result = run(&opts, "int x = 1;\n");
987 assert!(!result.failed(), "{:?}", result.messages);
988 assert!(result.text().is_empty());
989 assert!(run(&opts, "int f(void) { return undeclared; }\n").failed());
992 }
993
994 fn mir(source: &str) -> String {
996 let mut opts = options();
997 opts.emit = EmitKind::MirFinal;
998 let result = run(&opts, source);
999 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1000 result.text().to_owned()
1001 }
1002
1003 #[test]
1009 fn a_function_goes_from_c_to_instructions_with_real_registers_in_them() {
1010 let text = mir("int add(int a, int b) { return a + b; }\n");
1011 assert!(text.starts_with("mfunc @add {"), "{text}");
1012 assert!(text.contains("x64.add_rr_32"), "{text}");
1013 assert!(text.contains("x64.ret"), "{text}");
1014 assert!(!text.contains('%'), "{text}");
1017 }
1018
1019 #[test]
1021 fn a_function_with_no_body_produces_no_machine_function() {
1022 let text = mir("int g(int);\nint f(int a) { return g(a); }\n");
1023 assert_eq!(text.matches("mfunc @").count(), 1, "{text}");
1024 assert!(text.contains("mfunc @f {"), "{text}");
1025 assert!(text.contains("x64.call"), "{text}");
1026 }
1027
1028 #[test]
1030 fn every_definition_in_the_file_is_generated_and_they_keep_their_order() {
1031 let text = mir("int a(int x) { return x; }\nint b(int x) { return x; }\n");
1032 let first = text.find("mfunc @a").expect("the first function");
1033 let second = text.find("mfunc @b").expect("the second function");
1034 assert!(first < second, "{text}");
1035 }
1036
1037 #[test]
1039 fn the_target_decides_which_convention_the_generated_code_follows() {
1040 let mut opts = options();
1041 opts.emit = EmitKind::MirFinal;
1042 let linux = run(&opts, "int f(int a) { return a; }\n").text().to_owned();
1043 assert!(linux.contains("$rdi"), "{linux}");
1044
1045 opts.target = "x86_64-pc-windows-msvc".parse::<Triple>().unwrap();
1046 let windows = run(&opts, "int f(int a) { return a; }\n").text().to_owned();
1047 assert!(windows.contains("$rcx"), "{windows}");
1048 assert!(!windows.contains("$rdi"), "{windows}");
1049 }
1050
1051 #[test]
1053 fn a_target_this_has_no_back_end_for_is_reported_rather_than_generated() {
1054 let mut opts = options();
1055 opts.emit = EmitKind::MirFinal;
1056 opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
1057 let result = run(&opts, "int f(int a) { return a; }\n");
1058 assert!(result.failed());
1059 assert!(result.messages[0].contains("no back end for aarch64"), "{:?}", result.messages);
1060 assert!(result.text().is_empty());
1061 }
1062
1063 #[test]
1070 fn a_construct_the_back_end_cannot_reach_yet_is_reported_against_its_function() {
1071 let mut opts = options();
1072 opts.emit = EmitKind::MirFinal;
1073 let source = "long double a(long double x) { return x; }\n\
1074 long double b(long double x) { return x; }\n";
1075 let result = run(&opts, source);
1076 assert!(result.failed());
1077 assert_eq!(result.messages.len(), 2, "{:?}", result.messages);
1078 assert!(result.messages[0].contains("cannot generate code for 'a'"), "{:?}", result);
1079 assert!(result.messages[0].contains("x87 stack"), "{:?}", result);
1080 assert!(result.messages[1].contains("cannot generate code for 'b'"), "{:?}", result);
1081 assert!(result.text().is_empty());
1082 }
1083
1084 #[test]
1091 fn an_opcode_with_no_name_in_the_rule_language_is_named_by_its_own_spelling() {
1092 let mut opts = options();
1093 opts.emit = EmitKind::MirFinal;
1094 let result = run(&opts, "int f(int a) {\n __int128 wide = a;\n return (int) wide;\n}\n");
1095 assert!(result.failed());
1096 assert!(
1097 result.messages[0].contains("no rule lowers a `sext` producing a `i128`"),
1098 "{result:?}"
1099 );
1100 assert!(result.messages[0].contains(":2:"), "the line the widening is on: {result:?}");
1101 assert!(!result.messages[0].contains("this instruction"), "{result:?}");
1102 }
1103
1104 #[test]
1106 fn the_note_on_unfinished_work_points_at_the_issues_rather_than_at_the_plan() {
1107 let mut opts = options();
1108 opts.emit = EmitKind::MirFinal;
1109 let result = run(&opts, "int f(int a) { __int128 wide = a; return (int) wide; }\n");
1110 assert!(result.failed());
1111 let note = result.messages.iter().find(|line| line.contains("note:")).expect("a note");
1112 assert!(note.contains("https://github.com/tamnd/rucc/issues"), "{note}");
1113 assert!(!note.contains("spec/17-milestones.md"), "{note}");
1114 }
1115
1116 #[test]
1118 fn the_frame_flags_on_the_command_line_reach_the_generated_frame() {
1119 let source = "int f(int a) { return a; }\n";
1120 assert!(!mir(source).contains("$rbp"), "a leaf needs no frame pointer by default");
1121
1122 let mut opts = options();
1123 opts.emit = EmitKind::MirFinal;
1124 opts.frame_pointer = true;
1125 let kept = run(&opts, source).text().to_owned();
1126 assert!(kept.contains("x64.push_64 $rbp"), "{kept}");
1127 }
1128
1129 fn asm(source: &str) -> String {
1131 let mut opts = options();
1132 opts.emit = EmitKind::Asm;
1133 let result = run(&opts, source);
1134 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1135 result.text().to_owned()
1136 }
1137
1138 #[test]
1145 fn a_function_goes_from_c_to_assembly_an_assembler_would_take() {
1146 let text = asm("int add(int a, int b) { return a + b; }\n");
1147 assert!(text.contains("\t.globl\tadd\n"), "{text}");
1148 assert!(text.contains("\t.type\tadd, @function\n"), "{text}");
1149 assert!(text.contains("\nadd:\n"), "{text}");
1150 assert!(text.contains("\taddl\t"), "{text}");
1151 assert!(text.contains("\tret\n"), "{text}");
1152 assert!(text.contains("\t.size\tadd, .-add\n"), "{text}");
1153 assert!(text.contains(".note.GNU-stack"), "{text}");
1156 }
1157
1158 #[test]
1164 fn a_call_through_a_function_pointer_goes_through_the_register_it_is_in() {
1165 let text = asm("int g(int);\nint f(int (*p)(int), int a) { return p(a) + g(a); }\n");
1166 assert!(text.contains("\tcall\t*%"), "{text}");
1167 assert!(text.contains("\tcall\tg\n"), "{text}");
1168 assert!(text.contains("%rdi"), "{text}");
1172 }
1173
1174 #[test]
1176 fn the_address_of_a_global_is_read_from_the_instruction_pointer() {
1177 let text = asm("extern int counter;\nint f(void) { return counter; }\n");
1178 assert!(text.contains("\tleaq\tcounter(%rip), "), "{text}");
1179 }
1180
1181 #[test]
1183 fn a_cast_between_a_pointer_and_an_integer_leaves_the_value_where_it_is() {
1184 let text = asm("long f(void *p) { return (long)p; }\n");
1185 for line in text.lines().filter(|line| line.starts_with('\t') && !line.contains('.')) {
1190 let mnemonic = line.split_whitespace().next().unwrap_or("");
1191 assert!(matches!(mnemonic, "movq" | "ret"), "{line} in\n{text}");
1192 }
1193 }
1194
1195 #[test]
1199 fn an_argument_past_the_last_register_is_read_out_of_the_caller_s_stack() {
1200 let six = "long a, long b, long c, long d, long e, long f";
1201 let text = asm(&format!("long f({six}, long g, long h) {{ return g + h; }}\n"));
1202
1203 assert!(text.contains("\tmovq\t8(%rsp), "), "{text}");
1207 assert!(text.contains("\tmovq\t16(%rsp), "), "{text}");
1208
1209 let narrow = asm(&format!("int f({six}, int g) {{ return g; }}\n"));
1213 assert!(narrow.contains("\tmovl\t8(%rsp), "), "{narrow}");
1214 let eight =
1215 "double a, double b, double c, double d, double e, double f, double g, double h";
1216 let float = asm(&format!("double f({eight}, double i) {{ return i; }}\n"));
1217 assert!(float.contains("\tmovsd\t8(%rsp), "), "{float}");
1218 }
1219
1220 #[test]
1223 fn a_call_writes_the_arguments_with_no_register_left_at_the_stack_pointer() {
1224 let six = "1, 2, 3, 4, 5, 6";
1225 let decl = "long g(long, long, long, long, long, long, long, long);\n";
1226 let text = asm(&format!("{decl}long f(void) {{ return g({six}, 7, 8); }}\n"));
1227
1228 assert!(text.contains("\tmovq\t%"), "{text}");
1229 assert!(text.contains(", (%rsp)\n"), "{text}");
1230 assert!(text.contains(", 8(%rsp)\n"), "{text}");
1231 assert!(text.contains("\tsubq\t$"), "{text}");
1233
1234 let narrow = "int g(int, int, int, int, int, int, int);\n";
1236 let text = asm(&format!("{narrow}int f(void) {{ return g({six}, 7); }}\n"));
1237 assert!(text.contains("\tmovl\t%"), "{text}");
1238 assert!(text.contains(", (%rsp)\n"), "{text}");
1239 }
1240
1241 #[test]
1244 fn a_variadic_call_counts_registers_and_not_arguments() {
1245 let nine = "1., 2., 3., 4., 5., 6., 7., 8., 9.";
1246 let decl = "int g(int, ...);\n";
1247 let text = asm(&format!("{decl}int f(void) {{ return g(0, {nine}); }}\n"));
1248
1249 assert!(text.contains("\tmovl\t$8, "), "eight registers, not nine: {text}");
1250 assert!(text.contains("\tmovsd\t%"), "{text}");
1251 assert!(text.contains(", (%rsp)\n"), "{text}");
1252 }
1253
1254 #[test]
1259 fn a_variadic_function_writes_the_argument_registers_it_was_handed_into_its_frame() {
1260 let body =
1261 "__builtin_va_list ap; __builtin_va_start(ap, n); __builtin_va_end(ap); return n;";
1262 let text = asm(&format!("int f(int n, ...) {{ {body} }}\n"));
1263
1264 let stores = |mnemonic: &str| text.matches(&format!("\t{mnemonic}\t%")).count();
1267 assert!(text.contains(", 8(%r"), "the second slot, not the first: {text}");
1268 assert!(!text.contains(", 0(%r"), "{text}");
1269 assert_eq!(stores("movsd"), 8, "every vector register: {text}");
1270
1271 assert!(text.contains("\tsubq\t$"), "{text}");
1273 }
1274
1275 #[test]
1278 fn va_start_writes_the_four_fields_the_psabi_describes() {
1279 let start = "__builtin_va_list ap; __builtin_va_start(ap, d);";
1280 let params = "int a, int b, int c, double d";
1281 let text = asm(&format!("int f({params}, ...) {{ {start} return a; }}\n"));
1282
1283 assert!(text.contains(" movl $24, "), "{text}");
1287 assert!(text.contains(" movl $64, "), "{text}");
1288 assert!(text.contains(", 8(%r"), "{text}");
1292 assert!(text.contains(", 16(%r"), "{text}");
1293 let frame: u32 = text
1294 .lines()
1295 .find_map(|line| line.trim().strip_prefix("subq $")?.split(',').next()?.parse().ok())
1296 .expect("a variadic function takes a frame for the save area");
1297 let above = |line: &str| {
1298 let at: u32 = line.trim().strip_prefix("leaq ")?.split('(').next()?.parse().ok()?;
1299 Some(at > frame)
1300 };
1301 assert!(text.lines().filter_map(above).any(|it| it), "{frame}: {text}");
1302 }
1303
1304 #[test]
1307 fn va_arg_branches_on_whether_the_argument_is_still_in_the_save_area() {
1308 let read = "__builtin_va_list ap; __builtin_va_start(ap, n);";
1309 let ints = format!("int f(int n, ...) {{ {read} return __builtin_va_arg(ap, int); }}\n");
1310 let text = asm(&ints);
1311
1312 assert!(text.contains("$40, "), "{text}");
1315 assert!(text.contains(" cmpl "), "{text}");
1316 assert!(text.contains(" setbe "), "unsigned, since an offset is a count of bytes: {text}");
1317
1318 let arg = "__builtin_va_arg(ap, double)";
1319 let text = asm(&format!("double f(int n, ...) {{ {read} return {arg}; }}\n"));
1320 assert!(text.contains("$160, "), "the last vector slot: {text}");
1321 }
1322
1323 #[test]
1326 fn a_structure_assignment_is_a_move_for_each_word_of_it() {
1327 let decl = "struct pair { long a, b; };\n";
1328 let body = "struct pair p = *q; return p.a + p.b;";
1329 let text = asm(&format!("{decl}long f(struct pair *q) {{ {body} }}\n"));
1330
1331 assert!(!text.contains("memcpy"), "nothing calls the library: {text}");
1332 assert!(!text.contains("\tcall"), "{text}");
1333 assert!(text.matches("\tmovq\t").count() >= 4, "two words each way: {text}");
1335 }
1336
1337 #[test]
1340 fn how_wide_a_word_of_a_copy_is_follows_the_alignment() {
1341 let decl = "struct bytes { char a[8]; };\n";
1342 let body = "struct bytes p = *q; return p.a[0];";
1343 let text = asm(&format!("{decl}int f(struct bytes *q) {{ {body} }}\n"));
1344
1345 assert!(text.matches("\tmovb\t").count() >= 16, "a byte at a time: {text}");
1347 }
1348
1349 #[test]
1352 fn the_part_of_an_initialiser_that_names_nothing_is_stored_as_zero() {
1353 let decl = "struct wide { long a, b, c; };\n";
1354 let text = asm(&format!("{decl}long f(void) {{ struct wide w = {{ 7 }}; return w.c; }}\n"));
1355
1356 assert!(!text.contains("memset"), "nothing calls the library: {text}");
1357 assert!(text.contains("\tmovq\t$0, ") || text.contains("$0, %"), "the zero: {text}");
1358 }
1359
1360 #[test]
1363 fn a_copy_too_large_to_unroll_calls_the_runtime() {
1364 let decl = "struct huge { char a[4096]; };\n";
1365 let mut opts = options();
1366 opts.emit = EmitKind::Asm;
1367 let source = format!("{decl}void f(struct huge *p, struct huge *q) {{ *p = *q; }}\n");
1368 let result = run(&opts, &source);
1369 assert!(!result.failed(), "{:?}", result.messages);
1370 let text = result.text();
1371 assert!(text.contains("call") && text.contains("memcpy"), "{text}");
1372 assert!(text.contains("4096"), "the size travels: {text}");
1375 }
1376
1377 #[test]
1380 fn a_realigned_frame_reads_them_through_the_frame_pointer() {
1381 let six = "long a, long b, long c, long d, long e, long f";
1382 let body = "_Alignas(32) long wide[4]; wide[0] = g; return wide[0];";
1383 let text = asm(&format!("long f({six}, long g) {{ {body} }}\n"));
1384
1385 assert!(text.contains("\tandq\t$-32, %rsp"), "{text}");
1389 assert!(text.contains("\tmovq\t16(%rbp), "), "{text}");
1390 assert!(!text.contains("\tmovq\t16(%rsp), "), "{text}");
1391 }
1392
1393 #[test]
1395 fn the_target_decides_how_the_assembly_is_spelled() {
1396 let mut opts = options();
1397 opts.emit = EmitKind::Asm;
1398 opts.target = "x86_64-apple-darwin".parse::<Triple>().unwrap();
1399 let text = run(&opts, "int f(void) { return 0; }\n").text().to_owned();
1400 assert!(text.contains("__TEXT,__text"), "{text}");
1401 assert!(text.contains("\n_f:\n"), "{text}");
1402 assert!(!text.contains(".note.GNU-stack"), "{text}");
1403 }
1404
1405 fn obj(source: &str) -> Vec<u8> {
1407 let mut opts = options();
1408 opts.emit = EmitKind::Object;
1409 let result = run(&opts, source);
1410 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1411 match result.artifact {
1412 Artifact::Object(bytes) => bytes,
1413 other => panic!("expected an object, got {other:?}"),
1414 }
1415 }
1416
1417 #[test]
1423 fn a_function_goes_from_c_to_an_object_a_linker_would_take() {
1424 let bytes = obj("int add(int a, int b) { return a + b; }\n");
1425 assert_eq!(&bytes[..4], b"\x7fELF", "an object file starts by saying it is one");
1426 let text = asm("int add(int a, int b) { return a + b; }\n");
1427 assert!(
1428 text.contains("\taddl\t"),
1429 "and the listing of it is the same instructions:\n{text}"
1430 );
1431 }
1432
1433 #[test]
1435 fn a_variable_goes_from_c_to_the_section_it_belongs_in() {
1436 let text = asm("int counter = 42;\nstatic int hidden;\nconst int fixed = 7;\n");
1437 assert!(text.contains("\t.data\n\t.globl\tcounter\n"), "{text}");
1438 assert!(text.contains("\ncounter:\n\t.long\t42\n"), "{text}");
1439 assert!(text.contains("\t.size\tcounter, .-counter\n"), "{text}");
1440 assert!(text.contains("\t.bss\n\t.p2align\t2\n"), "{text}");
1443 assert!(text.contains("\nhidden:\n\t.space\t4\n"), "{text}");
1444 assert!(!text.contains(".globl\thidden"), "{text}");
1445 assert!(text.contains("\t.section\t.rodata\n"), "{text}");
1448 }
1449
1450 #[test]
1452 fn a_string_literal_is_a_variable_with_a_name_no_program_could_write() {
1453 let text = asm("const char *f(void) { return \"hi\"; }\n");
1454 assert!(text.contains("\t.ascii\t\"hi\\000\"\n"), "{text}");
1455 assert!(text.contains("\t.section\t.rodata\n"), "{text}");
1456 let label = text
1457 .lines()
1458 .find(|line| line.starts_with(".Lstr"))
1459 .unwrap_or_else(|| panic!("a label for the literal in\n{text}"));
1460 assert!(!text.contains(&format!(".globl\t{}", label.trim_end_matches(':'))), "{text}");
1461 }
1462
1463 #[test]
1465 fn an_address_in_an_initializer_is_left_to_the_linker() {
1466 let source = "int counter;\nint *p = &counter;\n";
1467 let text = asm(source);
1468 assert!(text.contains("\np:\n\t.quad\tcounter\n"), "{text}");
1469 let bytes = obj(source);
1472 assert!(bytes.windows(8).any(|w| w == b"counter\0"), "the object has to name it");
1473 }
1474
1475 #[test]
1477 fn a_thread_local_variable_is_reported_as_work_that_is_not_done() {
1478 let mut opts = options();
1479 opts.emit = EmitKind::Asm;
1480 let result = run(&opts, "_Thread_local int x = 1;\n");
1481 assert!(result.failed(), "every thread sharing one variable is worse than a message");
1482 assert!(result.messages.iter().any(|m| m.contains("thread-local")), "{:?}", result);
1483 assert!(!result.messages.iter().any(|m| m.contains("internal")), "{:?}", result);
1485 }
1486
1487 #[test]
1489 fn the_object_and_the_listing_are_two_spellings_of_one_compilation() {
1490 let source = "int callee(void); int g(void) { return callee(); }\n";
1494 let bytes = obj(source);
1495 assert!(
1496 bytes.windows(7).any(|w| w == b"callee\0"),
1497 "the object has to name the callee for the linker to find it"
1498 );
1499 let text = asm(source);
1500 assert!(text.contains("\tcall\tcallee\n"), "{text}");
1501 }
1502
1503 #[test]
1509 fn compiling_for_an_executable_produces_an_object_and_not_a_dump() {
1510 let mut opts = options();
1511 opts.emit = EmitKind::Executable;
1513 let result = run(&opts, "int main(void) { return 0; }\n");
1514 assert_eq!(result.messages, Vec::<String>::new());
1515 match result.artifact {
1516 Artifact::Object(bytes) => assert_eq!(&bytes[..4], b"\x7fELF"),
1517 other => panic!("expected an object, got {other:?}"),
1518 }
1519 }
1520
1521 #[test]
1523 fn a_platform_with_no_object_writer_is_said_so_rather_than_written_as_elf() {
1524 let mut opts = options();
1525 opts.emit = EmitKind::Object;
1526 opts.target = "x86_64-apple-darwin".parse::<Triple>().unwrap();
1527 let result = run(&opts, "int f(void) { return 0; }\n");
1528 assert!(result.failed(), "an object nobody can read is worse than a message");
1529 assert!(
1530 result.messages.iter().any(|m| m.contains("no object writer")),
1531 "{:?}",
1532 result.messages
1533 );
1534 }
1535
1536 fn ir(source: &str) -> String {
1538 let mut opts = options();
1539 opts.emit = EmitKind::Ir;
1540 let result = run(&opts, source);
1541 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1542 result.text().to_owned()
1543 }
1544
1545 fn body(source: &str) -> String {
1547 let text = ir(source);
1548 let (_, rest) = text.split_once("{\n").expect("a function definition");
1549 let (body, _) = rest.rsplit_once("}\n").expect("a function definition");
1550 body.to_owned()
1551 }
1552
1553 #[test]
1561 fn builtin_constant_p_is_folded_where_it_is_written_rather_than_called() {
1562 let text = ir(concat!(
1563 "int g;\n",
1564 "int a = __builtin_constant_p(1);\n",
1565 "int b = __builtin_constant_p(g);\n",
1566 "int c = __builtin_constant_p(\"abc\");\n",
1567 "int d = __builtin_constant_p(&g);\n",
1568 "int e = __builtin_constant_p(1.5);\n",
1569 "int h = __builtin_choose_expr(__builtin_constant_p(3), 11, 22);\n",
1570 ));
1571 assert!(text.contains("global @a : i32 = 1,"), "{text}");
1572 assert!(text.contains("global @b : i32 = 0,"), "{text}");
1573 assert!(text.contains("global @c : i32 = 1,"), "{text}");
1574 assert!(text.contains("global @d : i32 = 0,"), "{text}");
1575 assert!(text.contains("global @e : i32 = 1,"), "{text}");
1576 assert!(text.contains("global @h : i32 = 11,"), "{text}");
1577 assert!(!text.contains("__builtin_constant_p"), "it is not a call to anything:\n{text}");
1578
1579 let text = body("int f(void) { int i = 0; __builtin_constant_p(i++); return i; }\n");
1583 assert_eq!(text, "block0:\n %0 = iconst.i32 0\n %1 = iconst.i32 0\n return %0\n");
1584 }
1585
1586 #[test]
1595 fn a_call_to_a_library_builtin_reaches_the_library_function() {
1596 let text = body("void f(void) { __builtin_abort(); }\n");
1597 assert_eq!(text, "block0:\n call @abort() : ()\n return\n");
1598
1599 let text = ir("int f(const char *s) { return __builtin_puts(s) + __builtin_strlen(s); }\n");
1602 assert!(text.contains("call @puts(%0) : (ptr) -> i32"), "{text}");
1603 assert!(text.contains("call @strlen(%0) : (ptr) -> i64"), "{text}");
1604 assert!(!text.contains("__builtin_"), "the prefix is not part of any name here:\n{text}");
1605 }
1606
1607 #[test]
1619 fn the_hint_builtins_are_their_first_argument_and_the_hint_leaves_no_trace() {
1620 let text = ir(concat!(
1621 "long a = __builtin_expect(7, 1);\n",
1622 "long b = __builtin_expect_with_probability(9, 1, 0.9);\n",
1623 "unsigned long c = sizeof(__builtin_expect((char)1, 1));\n",
1624 ));
1625 assert!(text.contains("global @a : i64 = 7,"), "{text}");
1626 assert!(text.contains("global @b : i64 = 9,"), "{text}");
1627 assert!(text.contains("global @c : i64 = 8,"), "{text}");
1628 assert!(!text.contains("__builtin_expect"), "it is not a call to anything:\n{text}");
1629
1630 let text = body("long f(char c) { return __builtin_expect(c, 1); }\n");
1633 assert!(text.contains("sext"), "{text}");
1634
1635 let one = "block0:\n %0 = iconst.i32 0\n %1 = iconst.i32 1\n %2 = sext.i64 %1\n return %0\n";
1639 assert_eq!(body("int f(void) { int i = 0; __builtin_expect(1, i++); return i; }\n"), one);
1640 let source = "int g(void) { int i = 0; __builtin_expect_with_probability(1, i++, 0.5); return i; }\n";
1641 assert_eq!(body(source), one);
1642 }
1643
1644 #[test]
1656 fn a_promise_that_control_does_not_arrive_writes_no_instruction() {
1657 let promised = "int f(int x) { if (x) return 1; __builtin_unreachable(); }\n";
1658 let text = ir(promised);
1659 assert!(text.contains(" unreachable_hint\n"), "{text}");
1660 assert!(!text.contains("call"), "it is not a call to anything:\n{text}");
1661
1662 let after = body("int g(int x) { __builtin_unreachable(); return x; }\n");
1666 assert!(after.contains("return"), "{after}");
1667
1668 let text = asm(promised);
1671 let mine = text.split_once("\nf:\n").expect("a definition").1;
1672 let mine = mine.split_once("\t.size").expect("a definition").0;
1673 let plain = asm("int f(int x) { if (x) return 1; }\n");
1674 let plain = plain.split_once("\nf:\n").expect("a definition").1;
1675 let plain = plain.split_once("\t.size").expect("a definition").0;
1676 assert_eq!(mine, plain);
1677 assert!(mine.trim_end().ends_with("ret"), "{mine}");
1678 assert!(!mine.contains("ud2"), "{mine}");
1679 }
1680
1681 #[test]
1688 fn a_library_builtin_is_diagnosed_under_the_name_the_program_wrote() {
1689 let mut opts = options();
1690 opts.emit = EmitKind::Ir;
1691 let messages = run(&opts, "void f(void) { __builtin_abort(1); }\n").messages;
1692 assert!(
1693 messages.iter().any(|m| m.contains("__builtin_abort")),
1694 "expected the written name in {messages:?}"
1695 );
1696 }
1697
1698 #[test]
1706 fn a_builtin_nothing_lowers_is_refused_by_name() {
1707 let mut opts = options();
1708 opts.emit = EmitKind::Ir;
1709 for (builtin, call) in [
1710 ("__builtin_clz", "__builtin_clz(1u)"),
1711 ("__builtin_alloca", "(int)(long)__builtin_alloca(8)"),
1712 ("__atomic_load_n", "__atomic_load_n(&counter, 0)"),
1713 ("__sync_fetch_and_add", "(int)__sync_fetch_and_add(&counter, 1)"),
1714 ] {
1715 let source = format!("int counter;\nint f(void) {{ return {call}; }}\n");
1716 let messages = run(&opts, &source).messages;
1717 let named = messages.iter().any(|m| m.contains(builtin) && m.contains("E0686"));
1718 assert!(named, "expected {builtin} to be refused by name in {messages:?}");
1719 }
1720 }
1721
1722 #[test]
1730 fn what_is_refused_is_the_call_and_not_the_name() {
1731 let text = ir("unsigned long n = sizeof(__builtin_clz(1u));\n");
1732 assert!(text.contains("global @n : i64 = 4,"), "{text}");
1733
1734 let text = ir(
1735 "int __builtin_clz(unsigned x) { return 1; }\nint f(void) { return __builtin_clz(2u); }\n",
1736 );
1737 assert!(text.contains("call @__builtin_clz"), "{text}");
1738 }
1739
1740 #[test]
1745 fn a_static_function_nothing_refers_to_is_not_emitted() {
1746 let text = ir("static int dropped(void) { return 1; }\n\
1747 static int kept(void) { return 2; }\n\
1748 int main(void) { return kept(); }\n");
1749 assert!(text.contains("func @kept"), "{text}");
1750 assert!(!text.contains("dropped"), "{text}");
1751 }
1752
1753 #[test]
1759 fn two_static_functions_that_only_call_each_other_are_both_dropped() {
1760 let text = ir("static int ping(void);\n\
1761 static int pong(void) { return ping(); }\n\
1762 static int ping(void) { return pong(); }\n\
1763 int main(void) { return 0; }\n");
1764 assert!(!text.contains("ping"), "{text}");
1765 assert!(!text.contains("pong"), "{text}");
1766 }
1767
1768 #[test]
1774 fn naming_a_static_function_anywhere_keeps_it() {
1775 let text = ir("static int by_address(void) { return 1; }\n\
1776 static int in_an_image(void) { return 2; }\n\
1777 static int deeper(void) { return 3; }\n\
1778 static int reaches_deeper(void) { return deeper(); }\n\
1779 static int (*table[1])(void) = {in_an_image};\n\
1780 int main(void) {\n\
1781 int (*p)(void) = by_address;\n\
1782 return p() + table[0]() + reaches_deeper();\n\
1783 }\n");
1784 for kept in ["by_address", "in_an_image", "deeper", "reaches_deeper"] {
1785 assert!(text.contains(&format!("func @{kept}")), "expected {kept} in:\n{text}");
1786 }
1787 }
1788
1789 #[test]
1795 fn an_attribute_keeps_a_static_function_nothing_refers_to() {
1796 for attribute in ["used", "retain", "constructor", "destructor", "__used__"] {
1797 let source = format!(
1798 "__attribute__(({attribute})) static int kept(void) {{ return 1; }}\n\
1799 int main(void) {{ return 0; }}\n"
1800 );
1801 let text = ir(&source);
1802 assert!(text.contains("func @kept"), "for {attribute}:\n{text}");
1803 }
1804 }
1805
1806 #[test]
1809 fn a_function_anything_could_call_is_emitted_without_being_called() {
1810 let text =
1811 ir("int nobody_here_calls_it(void) { return 1; }\nint main(void) { return 0; }\n");
1812 assert!(text.contains("func @nobody_here_calls_it"), "{text}");
1813 }
1814
1815 #[test]
1822 fn a_classification_c_has_an_operator_for_is_that_operator() {
1823 for (builtin, operator) in [
1824 ("__builtin_isgreater", "binary >"),
1825 ("__builtin_isgreaterequal", "binary >="),
1826 ("__builtin_isless", "binary <"),
1827 ("__builtin_islessequal", "binary <="),
1828 ] {
1829 let source = format!("int f(double x, double y) {{ return {builtin}(x, y); }}\n");
1830 let text = tast(&source);
1831 assert!(text.contains(&format!("{operator} : int")), "for {builtin}:\n{text}");
1832 }
1833 }
1834
1835 #[test]
1844 fn the_classification_builtins_are_comparisons_and_not_calls() {
1845 let text = body("int f(double x, double y) { return __builtin_isunordered(x, y); }\n");
1846 assert_eq!(
1847 text,
1848 "block0(%0: f64, %1: f64):\n %2 = fcmp uno %0, %1\n %3 = zext.i32 \
1849 %2\n return %3\n"
1850 );
1851
1852 let text = body("int f(double x, double y) { return __builtin_islessgreater(x, y); }\n");
1854 assert!(text.contains("fcmp one %0, %1"), "{text}");
1855
1856 let text = body("int f(double x) { return __builtin_isnan(x); }\n");
1857 assert!(text.contains("fcmp uno %0, %0"), "{text}");
1858
1859 let text = body("int f(double x) { return __builtin_isinf(x); }\n");
1860 assert!(text.contains("fconst.f64 0x7ff0000000000000"), "{text}");
1861 assert!(text.contains("fconst.f64 0xfff0000000000000"), "{text}");
1862 assert!(text.contains("%3 = fcmp oeq %0, %1"), "{text}");
1863 assert!(text.contains("%4 = fcmp oeq %0, %2"), "{text}");
1864 assert!(text.contains("%5 = or %3, %4"), "{text}");
1865
1866 let text = body("int f(double x) { return __builtin_isfinite(x); }\n");
1869 assert!(text.contains("%3 = fcmp olt %2, %0"), "{text}");
1870 assert!(text.contains("%4 = fcmp olt %0, %1"), "{text}");
1871 assert!(text.contains("%5 = and %3, %4"), "{text}");
1872
1873 let text = body("int f(double x) { return __builtin_signbit(x); }\n");
1874 assert!(text.contains("%1 = bitcast.i64 %0"), "{text}");
1875 assert!(text.contains("icmp slt %1, %2"), "{text}");
1876
1877 let text = body("int f(long double x) { return __builtin_signbitl(x); }\n");
1880 assert!(text.contains("%1 = bitcast.i80 %0"), "{text}");
1881
1882 let text = body("double g(void);\nint f(void) { return __builtin_isnan(g()); }\n");
1885 assert_eq!(text.matches("call @g()").count(), 1, "{text}");
1886 }
1887
1888 #[test]
1895 fn a_classification_spelling_that_names_a_width_converts_before_it_asks() {
1896 let text = ir(concat!(
1897 "int a = __builtin_isinff(1e300);\n",
1898 "int b = __builtin_isinf(1e300);\n",
1899 "int c = __builtin_isnan(0.0);\n",
1903 "int d = __builtin_signbit(-0.0);\n",
1904 "int e = __builtin_islessgreater(1.0, 2.0);\n",
1905 ));
1906 assert!(text.contains("global @a : i32 = 1,"), "{text}");
1907 assert!(text.contains("global @b : i32 = 0,"), "{text}");
1908 assert!(text.contains("global @c : i32 = 0,"), "{text}");
1909 assert!(text.contains("global @d : i32 = 1,"), "{text}");
1910 assert!(text.contains("global @e : i32 = 1,"), "{text}");
1911 }
1912
1913 #[test]
1915 fn a_classification_builtin_refuses_an_argument_that_is_not_floating_point() {
1916 let mut opts = options();
1917 opts.emit = EmitKind::Ir;
1918 let source = concat!(
1919 "int a(int x) { return __builtin_isnan(x); }\n",
1920 "int b(int x, int y) { return __builtin_isunordered(x, y); }\n",
1921 "int c(double x) { return __builtin_isnan(x, x); }\n",
1922 );
1923 let messages = run(&opts, source).messages;
1924 assert_eq!(
1925 messages,
1926 [
1927 "/main.c:1:23: error: non-floating-point argument in call to function \
1928 '__builtin_isnan' [E0685]",
1929 "/main.c:2:30: error: non-floating-point arguments in call to function \
1930 '__builtin_isunordered' [E0685]",
1931 "/main.c:3:26: error: too many arguments to function '__builtin_isnan' [E0511]",
1932 ]
1933 );
1934 }
1935
1936 #[test]
1944 fn a_builtin_whose_answer_is_a_constant_is_one_and_not_a_call() {
1945 let text = ir(concat!(
1946 "double a = __builtin_inf();\n",
1947 "float b = __builtin_huge_valf();\n",
1948 "long double c = __builtin_infl();\n",
1949 "double d = __builtin_huge_val();\n",
1950 ));
1951 assert!(text.contains("global @a : f64 = 0x7ff0000000000000,"), "{text}");
1952 assert!(text.contains("global @b : f32 = 0x7f800000,"), "{text}");
1953 assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
1954 assert!(text.contains("global @d : f64 = 0x7ff0000000000000,"), "{text}");
1955 assert!(!text.contains("call"), "{text}");
1956 }
1957
1958 #[test]
1967 fn a_nan_is_written_with_the_payload_the_program_asked_for() {
1968 let text = ir(concat!(
1969 "double a = __builtin_nan(\"\");\n",
1970 "double b = __builtin_nan(\"0x1\");\n",
1971 "double c = __builtin_nan(\"010\");\n",
1973 "double d = __builtin_nans(\"\");\n",
1974 "double e = __builtin_nans(\"0x1\");\n",
1975 "float f = __builtin_nanf(\"0x1\");\n",
1976 "float g = __builtin_nansf(\"\");\n",
1977 "long double h = __builtin_nansl(\"\");\n",
1978 ));
1979 assert!(text.contains("global @a : f64 = 0x7ff8000000000000,"), "{text}");
1980 assert!(text.contains("global @b : f64 = 0x7ff8000000000001,"), "{text}");
1981 assert!(text.contains("global @c : f64 = 0x7ff8000000000008,"), "{text}");
1982 assert!(text.contains("global @d : f64 = 0x7ff4000000000000,"), "{text}");
1983 assert!(text.contains("global @e : f64 = 0x7ff0000000000001,"), "{text}");
1984 assert!(text.contains("global @f : f32 = 0x7fc00001,"), "{text}");
1985 assert!(text.contains("global @g : f32 = 0x7fa00000,"), "{text}");
1986 assert!(text.contains("f80 0x7fffa000000000000000"), "{text}");
1987
1988 let text = ir(concat!(
1991 "double f(const char *p) { return __builtin_nan(p); }\n",
1992 "double g(void) { return __builtin_nans(\"1x\"); }\n",
1993 ));
1994 assert_eq!(text.matches("call @nan(").count(), 1, "{text}");
1995 assert_eq!(text.matches("call @nans(").count(), 1, "{text}");
1996 }
1997
1998 #[test]
2006 fn the_length_and_the_order_of_a_string_literal_are_known_here() {
2007 let text = ir(concat!(
2008 "unsigned long a = __builtin_strlen(\"hello\");\n",
2009 "unsigned long b = __builtin_strlen(\"a\\0bc\");\n",
2010 "int c = __builtin_strcmp(\"X\", \"X\\376\") < 0;\n",
2011 "int d = __builtin_strcmp(\"abc\", \"abc\");\n",
2012 "int e = __builtin_strcmp(\"abc\", \"ab\") > 0;\n",
2013 ));
2014 assert!(text.contains("global @a : i64 = 5,"), "{text}");
2015 assert!(text.contains("global @b : i64 = 1,"), "{text}");
2016 assert!(text.contains("global @c : i32 = 1,"), "{text}");
2017 assert!(text.contains("global @d : i32 = 0,"), "{text}");
2018 assert!(text.contains("global @e : i32 = 1,"), "{text}");
2019 assert!(!text.contains("call"), "{text}");
2020
2021 let text = ir("unsigned long f(const char *p) { return __builtin_strlen(p); }\n");
2023 assert!(text.contains("call @strlen("), "{text}");
2024 }
2025
2026 #[test]
2033 fn a_sign_builtin_is_a_mask_over_the_bits_and_not_a_call() {
2034 let text = body("double f(double x) { return __builtin_fabs(x); }\n");
2035 assert!(text.contains("bitcast.i64 %0"), "{text}");
2036 assert!(text.contains("iconst.i64 9223372036854775807"), "{text}");
2037 assert!(text.contains("and %1, %2"), "{text}");
2038 assert!(text.contains("bitcast.f64 %3"), "{text}");
2039 assert!(!text.contains("call"), "{text}");
2040
2041 let text = body("double f(double x, double y) { return __builtin_copysign(x, y); }\n");
2042 assert!(text.contains("iconst.i64 -9223372036854775808"), "{text}");
2043 assert!(text.contains("%8 = or %4, %7"), "{text}");
2044 assert!(!text.contains("call"), "{text}");
2045
2046 let text = body("long double f(long double x) { return __builtin_fabsl(x); }\n");
2049 assert!(text.contains("bitcast.i80 %0"), "{text}");
2050 assert!(text.contains("bitcast.f80"), "{text}");
2051
2052 let text = body("double f(float x) { return __builtin_fabs(x); }\n");
2055 assert!(text.contains("fpext.f64 %0"), "{text}");
2056 assert!(text.contains("bitcast.i64 %1"), "{text}");
2057 }
2058
2059 #[test]
2068 fn the_sign_builtins_answer_a_zero_and_a_nan_the_way_the_bits_say() {
2069 let text = ir(concat!(
2070 "double a = __builtin_fabs(-3.5);\n",
2071 "double b = __builtin_copysign(1.0, -0.0);\n",
2072 "double c = __builtin_copysign(0.0, -2.0);\n",
2073 "double d = __builtin_copysign(-__builtin_nan(\"\"), 1.0);\n",
2075 "double e = __builtin_fabs(-__builtin_nan(\"0x1\"));\n",
2076 "float g = __builtin_copysignf(-0.0f, 2.0f);\n",
2077 "long double h = __builtin_copysignl(1.0L, -1.0L);\n",
2078 "long double i = __builtin_fabsl(-__builtin_infl());\n",
2079 ));
2080 assert!(text.contains("global @a : f64 = 0x400c000000000000,"), "{text}");
2081 assert!(text.contains("global @b : f64 = 0xbff0000000000000,"), "{text}");
2082 assert!(text.contains("global @c : f64 = 0x8000000000000000,"), "{text}");
2083 assert!(text.contains("global @d : f64 = 0x7ff8000000000000,"), "{text}");
2084 assert!(text.contains("global @e : f64 = 0x7ff8000000000001,"), "{text}");
2085 assert!(text.contains("global @g : f32 = 0x0,"), "{text}");
2086 assert!(text.contains("f80 0xbfff8000000000000000"), "{text}");
2087 assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
2088 }
2089
2090 #[test]
2097 fn a_constexpr_object_is_a_constant_wherever_one_is_required() {
2098 let text = ir(concat!(
2099 "constexpr int side = 4;\n",
2100 "constexpr int wider = side + 1;\n",
2101 "constexpr double half = 1.5;\n",
2102 "struct point { int x; int y; };\n",
2103 "constexpr struct point origin = { 5, 6 };\n",
2104 "int square[side * side];\n",
2105 "int rectangle[wider];\n",
2106 "int rounded[(int)half * 2];\n",
2107 "int across[origin.y];\n",
2108 "enum named { four = side };\n",
2109 "int e = four;\n",
2110 ));
2111 assert!(text.contains("global @square : bytes 64 ="), "{text}");
2112 assert!(text.contains("global @rectangle : bytes 20 ="), "{text}");
2113 assert!(text.contains("global @rounded : bytes 8 ="), "{text}");
2114 assert!(text.contains("global @across : bytes 24 ="), "{text}");
2115 assert!(text.contains("global @e : i32 = 4,"), "{text}");
2116
2117 let mut opts = options();
2120 opts.emit = EmitKind::Ir;
2121 let konst = "const int n = 1;\nint a[n];\n";
2122 let message = "/main.c:2:5: error: variably modified 'a' at file scope [E0538]";
2123 assert_eq!(run(&opts, konst).messages, [message]);
2124
2125 let subscript = "constexpr int t[3] = { 1, 2, 3 };\nint a[t[1]];\n";
2127 assert_eq!(run(&opts, subscript).messages, [message]);
2128
2129 let address = "constexpr int c = 3;\nint *p = &c;\n";
2131 let warning = "/main.c:2:6: warning: initialization discards 'const' qualifier from \
2132 pointer target type [E0514]";
2133 assert_eq!(run(&opts, address).messages, [warning]);
2134 }
2135
2136 #[test]
2145 fn an_old_style_definition_takes_its_types_from_the_declarations_under_its_list() {
2146 let mut opts = options();
2149 opts.std = Std::C17;
2150 let source = concat!(
2151 "int add(a, b)\n",
2152 "int a;\n",
2153 "int b;\n",
2154 "{ return a + b; }\n",
2155 "int promoted(c)\n",
2156 "char c;\n",
2157 "{ return c; }\n",
2158 "int narrow(char);\n",
2159 "int narrow(c)\n",
2160 "char c;\n",
2161 "{ return c; }\n",
2162 "int first(a)\n",
2163 "int a[4];\n",
2164 "{ return a[0]; }\n",
2165 );
2166 let result = run(&opts, source);
2167 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
2168 let text = result.text();
2169 assert!(text.contains("add : int(int, int) function external defined"), "{text}");
2170 assert!(text.contains("promoted : int(int) function external defined"), "{text}");
2171 assert!(text.contains("c : char object automatic defined"), "{text}");
2173 assert!(text.contains("narrow : int(char) function external defined"), "{text}");
2174 assert!(text.contains("first : int(int *) function external defined"), "{text}");
2176 }
2177
2178 #[test]
2185 fn the_two_halves_of_an_old_style_parameter_list_have_to_agree() {
2186 let mut opts = options();
2187 opts.std = Std::C17;
2188 for (source, message) in [
2189 ("int f(a, a)\nint a;\n{ return a; }\n", "1:10: error: multiple parameters named 'a'"),
2190 (
2191 "int f(a)\nint a;\nint b;\n{ return a; }\n",
2192 "3:5: error: declaration for parameter 'b' but no such parameter",
2193 ),
2194 ("int f(a)\nint a;\nint a;\n{ return a; }\n", "3:5: error: redefinition of parameter"),
2195 ("int f(a)\nint a = 1;\n{ return a; }\n", "2:5: error: parameter 'a' is initialized"),
2196 (
2197 "int f(a)\nstatic int a;\n{ return a; }\n",
2198 "2:12: error: storage class specified for parameter 'a'",
2199 ),
2200 (
2201 "int f(char);\nint f(a)\nshort a;\n{ return a; }\n",
2202 "2:7: error: argument 'a' doesn't match prototype",
2203 ),
2204 ] {
2205 let result = run(&opts, source);
2206 assert!(result.failed(), "expected this to fail:\n{source}");
2207 assert!(result.messages[0].contains(message), "{:?}", result.messages);
2208 }
2209
2210 let implicit = "int f(a, b)\nint a;\n{ return a + b; }\n";
2213 let mut older = options();
2214 older.std = Std::C89;
2215 assert!(!run(&older, implicit).failed(), "{:?}", run(&older, implicit).messages);
2216 let result = run(&opts, implicit);
2217 assert!(
2218 result.messages[0].contains("1:10: error: type of 'b' defaults to 'int'"),
2219 "{:?}",
2220 result.messages
2221 );
2222
2223 let mut newer = options();
2227 newer.std = Std::C23;
2228 let plain = "int f(a)\nint a;\n{ return a; }\n";
2229 let result = run(&newer, plain);
2230 assert!(!result.failed(), "{:?}", result.messages);
2231 assert_eq!(
2232 result.messages,
2233 ["/main.c:1:5: warning: old-style function definition [E0412]"]
2234 );
2235 assert!(run(&opts, plain).messages.is_empty(), "and nothing to say in the dialects before");
2236 }
2237
2238 #[test]
2245 fn a_type_is_refused_when_it_passes_the_largest_object_and_not_before() {
2246 let text = ir(concat!(
2247 "struct huge_struct { short buf[(1L << 62) - 256]; int a, b, c, d; };\n",
2248 "struct brim { char buf[9223372036854775807L]; };\n",
2249 "struct bitty { char buf[9223372036854775800L]; int x : 1; };\n",
2250 "unsigned long h = sizeof(struct huge_struct);\n",
2251 "unsigned long b = sizeof(struct brim);\n",
2252 "unsigned long y = sizeof(struct bitty);\n",
2253 ));
2254 assert!(text.contains("global @h : i64 = 9223372036854775312,"), "{text}");
2255 assert!(text.contains("global @b : i64 = 9223372036854775807,"), "{text}");
2256 assert!(text.contains("global @y : i64 = 9223372036854775804,"), "{text}");
2257
2258 let mut opts = options();
2259 opts.emit = EmitKind::Ir;
2260 let over = "struct over { char buf[9223372036854775800L]; char x[8]; };\n";
2261 let message = "/main.c:1:1: error: type 'struct over' is too large [E0560]";
2262 assert_eq!(run(&opts, over).messages, [message]);
2263 let array = "struct wide { short buf[1L << 62]; };\n";
2264 let message = "/main.c:1:25: error: size of array 'buf' exceeds \
2265 maximum object size '9223372036854775807' [E0537]";
2266 assert_eq!(run(&opts, array).messages[0], message);
2267 }
2268
2269 fn compile_bytes(source: &[u8]) -> Compiled {
2274 let mut opts = options();
2275 opts.emit = EmitKind::Ir;
2276 let mut fs = MemoryFileSystem::new();
2277 fs.insert("/main.c", source.to_vec());
2278 compile(&opts, "/main.c", &fs)
2279 }
2280
2281 #[test]
2288 fn a_byte_that_is_not_a_character_is_kept_in_a_literal_and_refused_outside_one() {
2289 let mut source = b"char s[] = \"a".to_vec();
2290 source.push(0xff);
2291 source.extend_from_slice(b"b\";\nchar c = '");
2292 source.push(0xff);
2293 source.extend_from_slice(b"';\n");
2294 let result = compile_bytes(&source);
2295 assert_eq!(result.messages, Vec::<String>::new(), "a raw byte in a literal is that byte");
2296 assert!(result.text().contains(r#"bytes "a\ffb\00""#), "{}", result.text());
2297 assert!(result.text().contains("global @c : i8 = -1,"), "{}", result.text());
2299
2300 let mut stray = b"int a".to_vec();
2301 stray.push(0xff);
2302 stray.extend_from_slice(b" = 1;\n");
2303 let result = compile_bytes(&stray);
2304 assert!(
2305 result.messages.iter().any(|m| m.contains("source is not valid UTF-8 here")),
2306 "{:?}",
2307 result.messages
2308 );
2309 }
2310
2311 #[test]
2312 fn an_object_becomes_a_global_with_an_image_and_a_function_becomes_a_func() {
2313 let text = ir("int x = 7;\nint add(int a, int b) { return a + b; }\n");
2314 assert!(text.contains("global @x : i32 = 7, align 4, linkage(external)\n"), "{text}");
2315 let expected = "\
2316func @add(i32, i32) -> i32, linkage(external) {
2317block0(%0: i32, %1: i32):
2318 %2 = add.nsw %0, %1
2319 return %2
2320}
2321";
2322 assert!(text.contains(expected), "{text}");
2323 }
2324
2325 #[test]
2326 fn a_local_nothing_takes_the_address_of_is_a_value_and_never_a_stack_slot() {
2327 let text = body("int f(int n) { int a = n + 1; int b = a * 2; return a + b; }\n");
2328 assert!(!text.contains("alloca"), "{text}");
2329 assert!(!text.contains("load"), "{text}");
2330 assert!(!text.contains("store"), "{text}");
2331 }
2332
2333 #[test]
2334 fn a_local_whose_address_is_taken_gets_a_slot_in_the_entry_block() {
2335 let text = body("int g(int *);\nint f(void) { int a = 1; return g(&a); }\n");
2336 let expected = "\
2337block0:
2338 %0 = alloca, size 4, align 4
2339 %1 = iconst.i32 1
2340 store %1 -> %0, align 4
2341 %2 = call @g(%0) : (ptr) -> i32
2342 return %2
2343";
2344 assert_eq!(text, expected);
2345 }
2346
2347 #[test]
2348 fn a_loop_carries_what_it_changes_as_block_parameters() {
2349 let text = body(
2352 "int f(int n) {\n int total = 0;\n for (int i = 0; i < n; i++) total += i;\n \
2353 return total;\n}\n",
2354 );
2355 assert!(!text.contains("alloca"), "{text}");
2356 assert!(text.contains("block1(%3: i32, %4: i32):"), "{text}");
2357 assert!(text.contains("jump block1("), "{text}");
2358 }
2359
2360 #[test]
2361 fn a_comparison_used_as_a_condition_is_not_widened_and_narrowed_again() {
2362 let text = body("int f(int a, int b) { if (a < b) return 1; return 0; }\n");
2363 assert!(text.contains("icmp slt %0, %1"), "{text}");
2364 assert!(!text.contains("zext"), "{text}");
2365 }
2366
2367 #[test]
2368 fn the_right_side_of_a_short_circuit_is_in_a_block_of_its_own() {
2369 let text = body("int f(int a, int b) { return a && b; }\n");
2370 let expected = "\
2371block0(%0: i32, %1: i32):
2372 %2 = iconst.i32 0
2373 %3 = icmp ne %0, %2
2374 %4 = iconst.i1 0
2375 br_if %3, block1, block2(%4)
2376
2377block1:
2378 %5 = iconst.i32 0
2379 %6 = icmp ne %1, %5
2380 jump block2(%6)
2381
2382block2(%7: i1):
2383 %8 = zext.i32 %7
2384 return %8
2385";
2386 assert_eq!(text, expected);
2387 }
2388
2389 #[test]
2390 fn code_after_a_return_is_not_built_and_does_not_leave_an_empty_block_behind() {
2391 let text = body("int f(int a) { if (a) return 1; else return 2; return 3; }\n");
2392 assert!(!text.contains("block3"), "{text}");
2395 assert!(!text.contains("iconst.i32 3"), "{text}");
2396 }
2397
2398 #[test]
2399 fn falling_off_the_end_returns_zero_from_main_and_nothing_from_a_void_function() {
2400 assert!(body("int main(void) { }\n").contains("iconst.i32 0\n return"));
2401 assert_eq!(body("void f(void) { }\n"), "block0:\n return\n");
2402 assert!(body("int f(void) { }\n").contains("unreachable"));
2403 }
2404
2405 #[test]
2406 fn a_structure_is_copied_rather_than_held_in_a_value() {
2407 let text = body(
2408 "struct point { int x, y; };\n\
2409 int f(void) { struct point p = { 1, 2 }; struct point q = p; return q.x; }\n",
2410 );
2411 assert!(text.contains("memcpy"), "{text}");
2412 }
2413
2414 #[test]
2415 fn an_initializer_that_leaves_part_of_an_object_unwritten_zeroes_it_first() {
2416 let text = body("int f(void) { int a[4] = { 1 }; return a[3]; }\n");
2417 assert!(text.contains("memset"), "{text}");
2418 }
2419
2420 #[test]
2421 fn a_switch_is_one_branch_and_a_case_that_falls_through_carries_what_it_wrote() {
2422 let text = body(
2423 "int f(int x) { int r = 0; switch (x) { case 1: r = 1; case 2: r += 2; break; \
2424 default: r = 4; } return r; }\n",
2425 );
2426 let expected = "\
2427block0(%0: i32):
2428 %1 = iconst.i32 0
2429 switch %0, block1, [1 => block2, 2 => block3(%1)]
2430
2431block1:
2432 %2 = iconst.i32 4
2433 jump block4(%2)
2434
2435block2:
2436 %3 = iconst.i32 1
2437 jump block3(%3)
2438
2439block3(%4: i32):
2440 %5 = iconst.i32 2
2441 %6 = add.nsw %4, %5
2442 jump block4(%6)
2443
2444block4(%7: i32):
2445 return %7
2446";
2447 assert_eq!(text, expected);
2448 }
2449
2450 #[test]
2451 fn a_case_range_is_tested_for_rather_than_put_in_the_table() {
2452 let text = body("int f(int x) { switch (x) { case 1 ... 9: return 1; } return 0; }\n");
2455 assert!(text.contains("%2 = sub %0, %1"), "{text}");
2456 assert!(text.contains("icmp ule"), "{text}");
2457 assert!(!text.contains("switch"), "{text}");
2458 }
2459
2460 #[test]
2461 fn break_leaves_the_switch_and_continue_leaves_the_loop_around_it() {
2462 let text = body(
2463 "int f(int n) { int t = 0; for (int i = 0; i < n; i++) { switch (i) { \
2464 case 0: continue; case 1: break; default: t += i; } t++; } return t; }\n",
2465 );
2466 assert!(text.contains("switch %3, block4, [0 => block5, 1 => block6]"), "{text}");
2469 assert!(text.contains("block5:\n jump block7("), "{text}");
2470 assert!(text.contains("block6:\n jump block8("), "{text}");
2471 }
2472
2473 #[test]
2474 fn a_switch_with_nothing_to_branch_on_still_runs_what_comes_after_it() {
2475 assert_eq!(body("void f(int x) { switch (x) { } }\n"), "block0(%0: i32):\n return\n");
2476 }
2477
2478 #[test]
2479 fn a_label_a_loop_is_only_entered_through_builds_the_loop_around_it() {
2480 let text = body(
2485 "int f(int x, int n) { switch (x) { case 1: break; while (n) { case 2: n--; } } \
2486 return n; }\n",
2487 );
2488 assert!(text.contains("switch %0, block1(%1), [1 => block2, 2 => block3(%1)]"), "{text}");
2491 assert!(text.contains("block3(%3: i32):\n %4 = iconst.i32 1"), "{text}");
2492 assert!(text.contains("block5:\n jump block3("), "{text}");
2493 }
2494
2495 #[test]
2496 fn a_goto_into_a_loop_body_enters_it_without_the_test() {
2497 let text = body("int f(int x, int n) { goto in; while (n) { in: n--; } return n; }\n");
2500 assert!(text.starts_with("block0(%0: i32, %1: i32):\n jump block1(%1)"), "{text}");
2501 assert!(text.contains("block1(%2: i32):\n %3 = iconst.i32 1"), "{text}");
2502 assert!(text.contains("br_if %7, block3, block4"), "{text}");
2503 }
2504
2505 #[test]
2506 fn a_goto_is_a_jump_to_the_block_the_label_starts() {
2507 let text = body("int f(int x) { int r = 0; if (x) goto out; r = 1; out: return r; }\n");
2508 assert!(!text.contains("alloca"), "{text}");
2510 assert!(text.contains("block3(%4: i32):\n return %4"), "{text}");
2511 assert_eq!(text.matches("jump block3(").count(), 2, "{text}");
2512 }
2513
2514 #[test]
2515 fn a_backward_goto_is_a_loop_and_carries_what_it_changes() {
2516 let text =
2517 body("int f(int n) { int i = 0; again: if (i < n) { i++; goto again; } return i; }\n");
2518 assert!(!text.contains("alloca"), "{text}");
2519 assert!(text.contains("block1(%2: i32):"), "{text}");
2520 assert!(text.contains("jump block1(%5)"), "{text}");
2521 }
2522
2523 #[test]
2524 fn a_label_nothing_reaches_is_taken_out_rather_than_left_for_the_verifier() {
2525 assert_eq!(
2528 body("int f(int x) { return x; spare: return 0; }\n"),
2529 "block0(%0: i32):\n return %0\n"
2530 );
2531 }
2532
2533 #[test]
2534 fn a_bit_field_is_read_by_loading_the_bytes_it_lies_in_and_shifting() {
2535 let text = body(
2536 "struct s { unsigned a : 3; signed b : 5; };\nint f(struct s *p) { return p->b; }\n",
2537 );
2538 assert_eq!(
2541 text,
2542 "\
2543block0(%0: ptr):
2544 %1 = load.i8 %0, align 1
2545 %2 = iconst.i8 3
2546 %3 = ashr %1, %2
2547 %4 = sext.i32 %3
2548 return %4
2549"
2550 );
2551 }
2552
2553 #[test]
2554 fn a_store_to_a_bit_field_does_not_write_a_byte_it_has_no_bit_in() {
2555 let text =
2559 body("struct s { int a : 24; char c; };\nvoid f(struct s *p, int v) { p->a = v; }\n");
2560 assert_eq!(
2561 text,
2562 "\
2563block0(%0: ptr, %1: i32):
2564 %2 = iconst.i32 16777215
2565 %3 = and %1, %2
2566 %4 = trunc.i16 %3
2567 store %4 -> %0, align 2
2568 %5 = iconst.i32 16
2569 %6 = lshr %3, %5
2570 %7 = trunc.i8 %6
2571 %8 = iconst.i64 2
2572 %9 = ptr_add %0, %8
2573 store %7 -> %9, align 1
2574 return
2575"
2576 );
2577 }
2578
2579 #[test]
2580 fn what_an_assignment_to_a_bit_field_is_worth_is_what_fits_in_it() {
2581 let text =
2582 body("struct s { unsigned b : 5; };\nunsigned f(struct s *p) { return p->b = 33; }\n");
2583 assert!(text.contains("%3 = iconst.i8 31\n %4 = and %2, %3"), "{text}");
2586 assert!(text.ends_with("%9 = zext.i32 %4\n return %9\n"), "{text}");
2587 }
2588
2589 #[test]
2590 fn an_assignment_a_statement_throws_away_builds_none_of_what_it_is_worth() {
2591 let text = body("struct s { signed b : 5; };\nvoid f(struct s *p) { p->b = 3; }\n");
2594 assert_eq!(text.matches("ashr").count(), 0, "{text}");
2595 assert!(text.ends_with("store %8 -> %0, align 1\n return\n"), "{text}");
2596 }
2597
2598 #[test]
2599 fn a_bit_field_in_an_initializer_goes_in_over_bytes_that_were_zeroed_first() {
2600 let text = body(
2604 "struct s { int a : 3; int b; };\nint f(void) { struct s v = { 1 }; return v.b; }\n",
2605 );
2606 assert!(text.contains("memset %0, %1, size 8, align 4"), "{text}");
2607 }
2608
2609 #[test]
2610 fn the_image_of_a_static_bit_field_is_the_bytes_the_fields_share() {
2611 let text = ir("struct s { unsigned a : 3; unsigned b : 5; } g = { 1, 2 };\n");
2614 assert!(
2615 text.contains("global @g : bytes 4 = { bytes \"\\11\", zero 3 }, align 4"),
2616 "{text}"
2617 );
2618 }
2619
2620 #[test]
2621 fn an_initialized_flexible_array_member_makes_the_object_larger_than_its_type() {
2622 let text = ir(concat!(
2627 "struct a { int i; int j[]; } x = { 1, { 2, 0, 2, 3 } };\n",
2628 "struct b { char c; char p[]; } y = { 'o', \"wx\" };\n",
2629 "struct c { char c; char p[]; } z = { '9', { 'e', 'b' } };\n",
2630 "char s[2] = \"hi\";\n",
2631 ));
2632 assert!(
2633 text.contains("global @x : bytes 20 = { i32 1, i32 2, i32 0, i32 2, i32 3 }"),
2634 "{text}"
2635 );
2636 assert!(text.contains("global @y : bytes 4 = { i8 111, bytes \"wx\\00\" }"), "{text}");
2637 assert!(text.contains("global @z : bytes 3 = { i8 57, i8 101, i8 98 }"), "{text}");
2638 assert!(text.contains("global @s : bytes 2 = { bytes \"hi\" }"), "{text}");
2641 }
2642
2643 #[test]
2644 fn a_definition_takes_a_parameter_it_left_unnamed() {
2645 let text = ir("int f(int a, int) { return a; }\n");
2649 assert!(text.contains("func @f(i32, i32) -> i32"), "{text}");
2650 assert!(text.contains("block0(%0: i32, %1: i32):"), "{text}");
2651
2652 let text = ir("int g(int, int n) { return n; }\n");
2655 assert!(text.contains("block0(%0: i32, %1: i32):\n return %1\n"), "{text}");
2656 }
2657
2658 #[test]
2659 fn an_assignment_of_a_structure_is_the_object_it_wrote() {
2660 let text = body(concat!(
2665 "struct s { int f; int g; };\n",
2666 "void h(struct s *a, struct s *c, struct s *d, struct s *e)\n",
2667 "{ *d = *e = a[0] = *c; }\n",
2668 ));
2669 assert_eq!(text.matches("memcpy").count(), 3, "{text}");
2670 assert!(text.contains("memcpy %8, %1, size 8, align 4\n"), "{text}");
2671 assert!(text.contains("memcpy %3, %8, size 8, align 4\n"), "{text}");
2672 assert!(text.contains("memcpy %2, %3, size 8, align 4\n"), "{text}");
2673 }
2674
2675 #[test]
2676 fn a_string_literal_stops_at_the_end_of_the_array_it_is_filling() {
2677 let mut opts = options();
2682 opts.emit = EmitKind::Ir;
2683 let result = run(
2684 &opts,
2685 concat!(
2686 "const char a[2][3] = { \"1234\", \"xyz\" };\n",
2687 "static const char b[3][5] = { \"12345\", \"678\", \"9\" };\n",
2688 "union u { struct { char x[4]; char y[4]; }; struct { char z[8]; }; };\n",
2689 "const union u c = { { \"1234\", \"567\" } };\n",
2690 ),
2691 );
2692 let text = result.text();
2693 assert_eq!(
2694 result.messages,
2695 ["/main.c:1:24: warning: initializer-string for array of 'const char' is too long \
2696 (5 chars into 3 available) [E0637]"]
2697 );
2698 assert!(text.contains("global @a : bytes 6 = { bytes \"123\", bytes \"xyz\" }"), "{text}");
2699 assert!(
2700 text.contains(
2701 "global @b : bytes 15 = { bytes \"12345\", bytes \"678\\00\", zero 1, \
2702 bytes \"9\\00\", zero 3 }"
2703 ),
2704 "{text}"
2705 );
2706 assert!(
2709 text.contains("global @c : bytes 8 = { bytes \"1234\", bytes \"567\\00\" }"),
2710 "{text}"
2711 );
2712 }
2713
2714 #[test]
2715 fn a_cast_of_a_record_to_its_own_type_is_the_object_that_was_cast() {
2716 let text = body(concat!(
2720 "struct s { int a, b; };\nstruct v { struct s s; int t; };\n",
2721 "void g(struct v *);\n",
2722 "void f(struct s *p) { struct v w = { (struct s)*p, 5 }; g(&w); }\n",
2723 ));
2724 assert_eq!(text.matches("memcpy").count(), 1, "{text}");
2725 }
2726
2727 #[test]
2728 fn a_compound_literal_read_in_a_static_initializer_lays_its_bytes_into_the_image() {
2729 let text = ir(concat!(
2734 "struct s { int x; };\n",
2735 "struct t { struct s s; int o; } a = { (struct s){ 2 }, 3 };\n",
2736 "int n = (int){ 7 };\n",
2737 "struct u { struct s p; struct s q; } b = { (struct s){ 1 }, (struct s){ } };\n",
2738 ));
2739 assert!(text.contains("global @a : bytes 8 = { i32 2, i32 3 }"), "{text}");
2740 assert!(text.contains("global @n : i32 = 7,"), "{text}");
2741 assert!(text.contains("global @b : bytes 8 = { i32 1, zero 4 }"), "{text}");
2744 }
2745
2746 #[test]
2747 fn the_address_of_a_compound_literal_asks_for_the_object_it_points_at() {
2748 let text = ir("struct s { int x; };\nstruct s *q = &(struct s){ 9 };\n");
2752 assert!(text.contains("global @.Lanon.0 : i32 = 9, align 4, linkage(internal)"), "{text}");
2753 assert!(text.contains("global @q : bytes 8 = { addr.8 @.Lanon.0 }"), "{text}");
2754 }
2755
2756 #[test]
2757 fn an_object_of_no_size_at_all_has_an_image_with_nothing_in_it() {
2758 let text = ir("unsigned char foo[1][0];\n");
2762 assert!(text.contains("global @foo : bytes 0 = {}, align 1"), "{text}");
2763 }
2764
2765 #[test]
2766 fn a_null_pointer_in_an_image_is_the_bits_an_address_has_room_for() {
2767 let text = ir("void *p = 0;\nchar *q = (char *) 4096;\n");
2770 assert!(text.contains("global @p : i64 = 0, align 8"), "{text}");
2771 assert!(text.contains("global @q : i64 = 4096, align 8"), "{text}");
2772 }
2773
2774 #[test]
2775 fn an_object_another_module_defines_may_be_one_that_cannot_be_written_through() {
2776 let text = ir("extern const int limit;\nint f(void) { return limit; }\n");
2780 assert!(
2781 text.contains("global @limit : bytes 4, align 4, linkage(external), constant"),
2782 "{text}"
2783 );
2784 }
2785
2786 #[test]
2787 fn a_conditional_whose_value_is_an_object_answers_where_the_object_is() {
2788 let text = body(
2793 "\
2794struct s { int a, b; };
2795struct s pick(int c, struct s x, struct s y) { return c ? x : y; }
2796",
2797 );
2798 assert!(text.contains("block3(%7: ptr)"), "{text}");
2800 assert!(text.contains("jump block3(%3)") && text.contains("jump block3(%4)"), "{text}");
2801 assert!(!text.contains("memcpy"), "the arms are joined rather than copied: {text}");
2802 }
2803
2804 #[test]
2805 fn a_structure_that_fits_in_registers_travels_as_the_registers_it_fits_in() {
2806 let text = ir("\
2810struct pair { int a, b; };
2811struct pair make(int a, int b);
2812struct pair twice(struct pair p) { return make(p.a, p.b); }
2813");
2814 assert!(text.contains("func @make(i32, i32) -> i64"), "{text}");
2815 assert!(text.contains("func @twice(i64) -> i64"), "{text}");
2816 }
2817
2818 #[test]
2819 fn a_structure_too_large_for_the_registers_travels_as_where_its_bytes_are() {
2820 let text = ir("\
2824struct big { double v[8]; };
2825struct big grow(struct big b);
2826struct big twice(struct big b) { return grow(grow(b)); }
2827");
2828 assert!(
2829 text.contains("func @grow(ptr sret(64, align 8), ptr byval(64, align 8))"),
2830 "{text}"
2831 );
2832 assert!(text.contains("block0(%0: ptr, %1: ptr):"), "{text}");
2833 assert_eq!(text.matches("call @grow").count(), 2, "{text}");
2836 }
2837
2838 #[test]
2839 fn a_structure_passed_to_a_variadic_function_says_so_at_the_call() {
2840 let text = ir("\
2845struct big { double v[8]; };
2846struct pair { int a, b; };
2847int p(const char *, ...);
2848int f(struct big b, struct pair q) { return p(\"\", 1, b, q); }
2849");
2850 assert!(
2851 text.contains("call @p(%4, %5, %2 byval(64, align 8), %6) : (ptr, ...) -> i32"),
2852 "{text}"
2853 );
2854 }
2855
2856 #[test]
2857 fn what_a_call_produced_is_somewhere_before_anything_is_read_out_of_it() {
2858 let body = body(
2861 "\
2862struct pair { int a, b; };
2863struct pair make(int a, int b);
2864int second(void) { return make(1, 2).b; }
2865",
2866 );
2867 assert!(body.starts_with("block0:\n %0 = alloca, size 8, align 4\n"), "{body}");
2868 assert!(body.contains("store %3 -> %0, align 4\n"), "{body}");
2869 }
2870
2871 #[test]
2872 fn a_structure_of_floats_travels_in_floating_point_registers_on_aarch64() {
2873 let source = "\
2877struct hfa { float x, y, z; };
2878int take(struct hfa h);
2879int give(struct hfa h) { return take(h); }
2880";
2881 assert!(ir(source).contains("func @take(f64, f32) -> i32"), "{}", ir(source));
2882 let mut opts = options();
2883 opts.emit = EmitKind::Ir;
2884 opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
2885 let result = run(&opts, source);
2886 assert_eq!(result.messages, Vec::<String>::new());
2887 assert!(result.text().contains("func @take(f32, f32, f32) -> i32"), "{}", result.text());
2888 }
2889
2890 #[test]
2891 fn an_array_whose_length_is_not_a_constant_is_a_slot_made_where_its_declaration_is() {
2892 let source = "\
2895int use(int *);
2896void f(int n) {
2897 {
2898 int a[n];
2899 use(a);
2900 }
2901 use(0);
2902}
2903";
2904 let body = body(source);
2905 assert!(body.contains("mul.nsw"), "{body}");
2906 assert!(body.contains("stacksave"), "{body}");
2907 assert!(body.contains("alloca %"), "{body}");
2908 assert!(body.contains("stackrestore"), "{body}");
2909 }
2910
2911 #[test]
2912 fn a_goto_out_of_the_scope_of_one_gives_its_stack_back_on_the_way() {
2913 let source = "\
2918int use(int *);
2919int f(int n) {
2920 {
2921 int a[n];
2922 if (use(a)) goto out;
2923 use(0);
2924 }
2925out:
2926 return 0;
2927}
2928";
2929 let body = body(source);
2930 assert_eq!(body.matches("stackrestore").count(), 2, "{body}");
2932 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
2933 assert!(after.starts_with(" %4\n jump block"), "{body}");
2934 }
2935
2936 #[test]
2937 fn a_goto_to_a_label_the_array_is_still_alive_at_leaves_the_stack_alone() {
2938 let source = "\
2942int use(int *);
2943int f(int n) {
2944 int a[n];
2945again:
2946 if (use(a)) goto again;
2947 return 0;
2948}
2949";
2950 let body = body(source);
2951 assert!(body.contains("stacksave"), "{body}");
2952 assert!(!body.contains("stackrestore"), "{body}");
2953 }
2954
2955 #[test]
2956 fn a_goto_back_to_a_label_in_front_of_one_gives_it_back_every_time_round() {
2957 let source = "\
2962int use(int *);
2963int f(int n) {
2964again:
2965 {
2966 int a[n];
2967 if (use(a)) goto again;
2968 }
2969 return 0;
2970}
2971";
2972 let body = body(source);
2973 assert_eq!(body.matches("stacksave").count(), 1, "{body}");
2974 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
2975 assert!(after.starts_with(" %4\n jump block1\n"), "{body}");
2976 }
2977
2978 #[test]
2979 fn the_head_of_a_for_loop_is_a_scope_that_closes_where_the_loop_is_left() {
2980 let source = "\
2986int f(void);
2987void t(void) {
2988 int count = 10;
2989 for (; count--;) {
2990 int b[f()];
2991 int i;
2992 for (i = 0; i < f(); i++) {
2993 b[i] = count;
2994 }
2995 }
2996}
2997";
2998 let body = body(source);
2999 assert_eq!(body.matches("stacksave").count(), 1, "{body}");
3003 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
3004 let (next, _) = after.split_once("\n\n").expect("a block after the restore");
3005 assert!(next.contains("jump block1("), "{body}");
3006 }
3007
3008 #[test]
3009 fn how_long_one_of_those_is_was_decided_where_it_was_declared_and_not_where_it_is_asked() {
3010 let source = "\
3013unsigned long f(int n) {
3014 int a[n];
3015 n = 0;
3016 return sizeof a;
3017}
3018";
3019 let body = body(source);
3020 assert_eq!(body.matches("sext.i64 %0").count(), 2, "{body}");
3022 }
3023
3024 #[test]
3025 fn a_block_in_the_middle_of_an_expression_is_walked_where_the_expression_is() {
3026 let source = "\
3029int use(int);
3030int f(int x) {
3031 return ({
3032 int t = use(x);
3033 t * t;
3034 });
3035}
3036";
3037 let expected = "\
3038block0(%0: i32):
3039 %1 = call @use(%0) : (i32) -> i32
3040 %2 = mul.nsw %1, %1
3041 return %2
3042";
3043 assert_eq!(body(source), expected);
3044 }
3045
3046 #[test]
3047 fn one_of_those_that_control_never_leaves_is_lowered_and_what_follows_it_is_dropped() {
3048 let source = "int f(int x) { return ({ return x; 0; }); }\n";
3052 assert_eq!(body(source), "block0(%0: i32):\n return %0\n");
3053 }
3054
3055 #[test]
3056 fn one_argument_off_a_variable_argument_list_stays_an_intrinsic() {
3057 let source = "double f(__builtin_va_list ap) { return __builtin_va_arg(ap, double) + __builtin_va_arg(ap, double); }\n";
3061 let expected = "\
3062block0(%0: ptr):
3063 %1 = va_arg.f64 %0
3064 %2 = va_arg.f64 %0
3065 %3 = fadd %1, %2
3066 return %3
3067";
3068 assert_eq!(body(source), expected);
3069 }
3070
3071 #[test]
3072 fn one_that_reads_a_structure_answers_where_the_object_is() {
3073 let source = "\
3082struct s { int a; long b; };
3083long f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.b; }
3084";
3085 let expected = "\
3086block0(%0: ptr):
3087 %1 = alloca, size 16, align 8
3088 %2 = va_object %0, size 16, align 8, in(int 8 at 0, int 8 at 8)
3089 memcpy %1, %2, size 16, align 8
3090 %3 = iconst.i64 8
3091 %4 = ptr_add %1, %3
3092 %5 = load.i64 %4, align 8
3093 return %5
3094";
3095 assert_eq!(body(source), expected);
3096 }
3097
3098 #[test]
3102 fn the_classification_says_which_registers_the_object_arrived_in() {
3103 let source = "\
3104struct s { double a; double b; };
3105double f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.a; }
3106";
3107 assert!(
3108 body(source)
3109 .contains("va_object %0, size 16, align 8, in(float f64 at 0, float f64 at 8)"),
3110 "{}",
3111 body(source)
3112 );
3113
3114 let big = "\
3115struct s { long a[4]; };
3116long f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.a[0]; }
3117";
3118 assert!(body(big).contains("va_object %0, size 32, align 8\n"), "{}", body(big));
3119 }
3120
3121 #[test]
3122 fn a_jump_to_an_address_branches_to_every_label_the_function_takes_the_address_of() {
3123 let source = "\
3127int f(int c) {
3128 void *p = c ? &&one : &&two;
3129 goto *p;
3130one:
3131 return 1;
3132two:
3133 return 2;
3134}
3135";
3136 let expected = "\
3137block0(%0: i32):
3138 %1 = iconst.i32 0
3139 %2 = icmp ne %0, %1
3140 br_if %2, block1, block2
3141
3142block1:
3143 %3 = block_addr block3
3144 jump block4(%3)
3145
3146block2:
3147 %4 = block_addr block5
3148 jump block4(%4)
3149
3150block3:
3151 %5 = iconst.i32 1
3152 return %5
3153
3154block4(%6: ptr):
3155 indirect_br %6, block3, block5
3156
3157block5:
3158 %7 = iconst.i32 2
3159 return %7
3160";
3161 assert_eq!(body(source), expected);
3162 }
3163
3164 #[test]
3165 fn a_jump_to_an_address_no_label_in_the_function_has_arrives_nowhere() {
3166 let source = "void **next(void);
3169void f(void) { goto *next(); }
3170";
3171 let expected = "\
3172block0:
3173 %0 = call @next() : () -> ptr
3174 unreachable
3175";
3176 assert_eq!(body(source), expected);
3177 }
3178
3179 #[test]
3180 fn an_asm_with_no_operands_is_volatile_and_the_clobbers_are_the_whole_of_what_it_says() {
3181 let source = "void f(void) { __asm__(\"mfence\" ::: \"memory\"); }\n";
3184 let expected = "\
3185block0:
3186 inline_asm.volatile \"mfence\", \"\", \"memory\"()
3187 return
3188";
3189 assert_eq!(body(source), expected);
3190 }
3191
3192 #[test]
3193 fn the_constraints_are_one_list_in_the_order_the_template_counts_the_operands() {
3194 let source = "\
3197int f(int x, int y) {
3198 int r;
3199 __asm__(\"addl %2, %0\" : \"=r\"(r), \"+r\"(y) : \"r\"(x));
3200 return r + y;
3201}
3202";
3203 let expected = "\
3204block0(%0: i32, %1: i32):
3205 %2, %3 = inline_asm.(i32, i32) \"addl %2, %0\", \"=r,+r,r\", \"\"(%1, %0)
3206 %4 = add.nsw %2, %3
3207 return %4
3208";
3209 assert_eq!(body(source), expected);
3210 }
3211
3212 #[test]
3213 fn a_memory_operand_travels_as_the_address_of_an_object_that_is_given_a_slot() {
3214 let source = "\
3219struct pair { int a, b; };
3220int f(int x) {
3221 int slot = x;
3222 struct pair p = { x, x };
3223 __asm__(\"incl %0\" : \"+m\"(slot), \"=m\"(p));
3224 return slot + p.a;
3225}
3226";
3227 let text = body(source);
3228 assert!(text.contains("inline_asm \"incl %0\", \"+m,=m\", \"\"(%1, %2)\n"), "{text}");
3229 assert!(text.contains("%1 = alloca, size 4, align 4\n"), "{text}");
3230 assert!(text.contains("%2 = alloca, size 8, align 4\n"), "{text}");
3231 }
3232
3233 #[test]
3234 fn an_asm_goto_falls_through_to_its_first_target_and_writes_its_outputs_there() {
3235 let source = "\
3240int f(int x) {
3241 int r = 7;
3242 __asm__ goto(\"cbnz %0, %l1\" : \"=r\"(r) : \"r\"(x) :: away);
3243 return r;
3244away:
3245 return r;
3246}
3247";
3248 let expected = "\
3249block0(%0: i32):
3250 %1 = iconst.i32 7
3251 %2 = inline_asm.volatile \"cbnz %0, %l1\", \"=r,r\", \"\"(%0), labels [block1, block2]
3252
3253block1:
3254 return %2
3255
3256block2:
3257 return %1
3258";
3259 assert_eq!(body(source), expected);
3260 }
3261
3262 #[test]
3263 fn an_asm_statement_that_is_not_well_formed_is_reported_in_the_words_gcc_uses() {
3264 let mut opts = options();
3268 opts.emit = EmitKind::Ir;
3269 for (source, expected) in [
3270 (
3271 "void f(int x) { __asm__(\"\" : \"r\"(x)); }\n",
3272 "output operand constraint lacks '='",
3273 ),
3274 (
3275 "void f(int x) { __asm__(\"\" : \"=r\"(x + 1)); }\n",
3276 "lvalue required in 'asm' statement",
3277 ),
3278 (
3279 "const int g = 1;\nvoid f(void) { __asm__(\"\" : \"=r\"(g)); }\n",
3280 "read-only variable 'g' used as 'asm' output",
3281 ),
3282 (
3283 "void f(int x) { __asm__(\"\" : : \"=r\"(x)); }\n",
3284 "input operand constraint contains '='",
3285 ),
3286 (
3287 "void f(void) { __asm__(\"\" : : \"m\"(1)); }\n",
3288 "memory input 0 is not directly addressable",
3289 ),
3290 ("void f(void) { __asm__(L\"\"); }\n", "wide string literal in 'asm'"),
3291 (
3292 "void f(int x, int y) { __asm__(\"\" : [a] \"=r\"(x) : [a] \"r\"(y)); }\n",
3293 "duplicate asm operand name 'a'",
3294 ),
3295 ("void f(int x) { __asm__(\"%[in]\" : \"=r\"(x)); }\n", "undefined named operand 'in'"),
3296 ] {
3297 let result = run(&opts, source);
3298 assert!(result.failed(), "expected this to be reported:\n{source}");
3299 assert!(
3300 result.messages.iter().any(|m| m.contains(expected)),
3301 "{expected}\n{:?}",
3302 result.messages
3303 );
3304 }
3305 }
3306
3307 #[test]
3308 fn what_the_walk_cannot_build_yet_is_reported_rather_than_mislowered() {
3309 let mut opts = options();
3310 opts.emit = EmitKind::Ir;
3311 for source in [
3312 "int f(int n) { void *p = &&out; if (n) goto *p; { int a[n]; out: return 1; } }\n",
3313 "int f(int n) { int a[n]; __asm__ goto(\"\" ::::out); out: return a[0]; }\n",
3314 ] {
3315 let result = run(&opts, source);
3316 assert!(result.failed(), "expected this to be reported:\n{source}");
3317 assert!(
3318 result.messages.iter().any(|m| m.contains("not supported yet")),
3319 "{:?}",
3320 result.messages
3321 );
3322 }
3323 }
3324
3325 fn round_trip(source: &str) -> (String, String) {
3327 let printed = ir(source);
3328 let mut opts = options();
3329 opts.emit = EmitKind::Ir;
3330 let mut fs = MemoryFileSystem::new();
3331 fs.insert("/main.ir", printed.clone().into_bytes());
3332 let result = compile_ir(&opts, "/main.ir", &fs);
3333 assert_eq!(result.messages, Vec::<String>::new(), "expected this to read back:\n{printed}");
3334 (printed, result.text().to_owned())
3335 }
3336
3337 #[test]
3338 fn ir_that_arrives_as_an_input_is_read_back_and_written_out_the_same() {
3339 let (printed, again) = round_trip(
3343 "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",
3344 );
3345 assert_eq!(printed, again);
3346 }
3347
3348 #[test]
3349 fn ir_that_is_not_ir_says_which_line_stopped_it() {
3350 let mut opts = options();
3351 opts.emit = EmitKind::Ir;
3352 let mut fs = MemoryFileSystem::new();
3353 let text = "\
3354; ModuleID = 'a.c'
3355; format 0
3356target triple = \"x86_64-unknown-linux-gnu\"
3357target datalayout = \"e-p:64:64-i64:64-S128\"
3358
3359func @f(), linkage(external) {
3360block0:
3361 frobnicate
3362}
3363";
3364 fs.insert("/main.ir", text.as_bytes().to_vec());
3365 let result = compile_ir(&opts, "/main.ir", &fs);
3366 assert!(result.failed());
3367 assert!(result.messages[0].contains("/main.ir:8"), "{:?}", result.messages);
3368 }
3369
3370 #[test]
3371 fn ir_that_reads_but_does_not_hold_together_is_reported_by_the_verifier() {
3372 let mut opts = options();
3375 opts.emit = EmitKind::Ir;
3376 let mut fs = MemoryFileSystem::new();
3377 let text = "\
3378; ModuleID = 'a.c'
3379; format 0
3380target triple = \"x86_64-unknown-linux-gnu\"
3381target datalayout = \"e-p:64:64-i64:64-S128\"
3382
3383func @f(), linkage(external) {
3384block0:
3385 %0 = iconst.i32 1
3386 return %0
3387}
3388";
3389 fs.insert("/main.ir", text.as_bytes().to_vec());
3390 let result = compile_ir(&opts, "/main.ir", &fs);
3391 assert!(result.failed());
3392 assert!(result.messages[0].contains("invalid IR"), "{:?}", result.messages);
3393 }
3394
3395 #[test]
3396 fn a_typed_tree_is_not_something_an_input_of_ir_can_produce() {
3397 let mut fs = MemoryFileSystem::new();
3399 fs.insert("/main.ir", Vec::new());
3400 let result = compile_ir(&options(), "/main.ir", &fs);
3401 assert!(result.failed());
3402 assert!(result.messages[0].contains("can only be emitted as IR"), "{:?}", result.messages);
3403 }
3404
3405 #[test]
3406 fn the_printed_ir_reads_back_as_the_same_module() {
3407 let text = ir("\
3410struct point { int x, y; };
3411static const char greeting[] = \"hi\";
3412int table[4] = { 1, 2, 3 };
3413int puts(const char *);
3414double half(double x) { return x / 2.0; }
3415int f(int n) {
3416 int total = 0;
3417 for (int i = 0; i < n; i++) {
3418 if (i == 3) continue;
3419 total += table[i];
3420 }
3421 switch (n) {
3422 case 0: total = 1;
3423 case 1: total++; break;
3424 default: total = -total;
3425 }
3426 struct point p = { total, 1 };
3427 int *q = &p.y;
3428 puts(greeting);
3429 return p.x + *q;
3430}
3431int dispatch(int c) {
3432 void *p = c ? &&one : &&two;
3433 goto *p;
3434one:
3435 return 1;
3436two:
3437 return 2;
3438}
3439int assembly(int x, int *p) {
3440 int r;
3441 __asm__ volatile(\"xadd %0, %2\" : \"=r\"(r), \"+m\"(*p) : \"0\"(x) : \"cc\");
3442 __asm__ goto(\"cbnz %0, %l1\" : : \"r\"(r) : : away);
3443 return r;
3444away:
3445 return 0;
3446}
3447");
3448 let mut names = Interner::new();
3449 let module = rucc_ir::parse(&text, &mut names).expect("the printer writes what it reads");
3450 assert_eq!(rucc_ir::print(&module, &names), text);
3451 }
3452}