1use std::path::Path;
14
15use rucc_base::Interner;
16use rucc_codegen::pipeline::{self, Machine};
17use rucc_diag::{Diagnostic, Severity, Span};
18use rucc_lex::{Convert, Keywords, PpToken, convert};
19use rucc_sema::{Checker, Context as CheckContext};
20use rucc_session::{EmitKind, FileSystem, Options, Session};
21use rucc_target::TargetInfo;
22
23use crate::preprocess::render;
24
25#[derive(Debug, Clone, PartialEq, Eq, Default)]
32pub enum Artifact {
33 #[default]
36 Nothing,
37 Text(String),
39 Object(Vec<u8>),
41}
42
43impl Artifact {
44 #[must_use]
46 pub fn bytes(&self) -> &[u8] {
47 match self {
48 Artifact::Nothing => &[],
49 Artifact::Text(text) => text.as_bytes(),
50 Artifact::Object(bytes) => bytes,
51 }
52 }
53}
54
55#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct Compiled {
58 pub artifact: Artifact,
60 pub messages: Vec<String>,
62 pub errors: u32,
64}
65
66impl Compiled {
67 #[must_use]
69 pub fn failed(&self) -> bool {
70 self.errors > 0
71 }
72
73 #[must_use]
78 pub fn text(&self) -> &str {
79 match &self.artifact {
80 Artifact::Text(text) => text,
81 _ => "",
82 }
83 }
84}
85
86#[must_use]
99pub fn compile(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
100 let mut sess = Session::new(opts.clone());
101 let keywords = Keywords::new(&mut sess.interner, opts.std, opts.gnu_extensions);
105 let mut diagnostics: Vec<Diagnostic> = Vec::new();
106
107 let bytes = match fs.read(Path::new(name)) {
108 Ok(bytes) => bytes,
109 Err(e) => return failure(format!("{name}: {e}")),
110 };
111 let Ok(file) = sess.sources.add_shared(name, bytes, None) else {
112 return failure(format!("{name}: the source map has no room left for this file"));
113 };
114
115 let mut pp = rucc_pp::Preprocessor::new();
119 let predef = rucc_pp::Predef::for_options(opts);
120 let expanded: Vec<PpToken> = {
121 let mut cx = rucc_pp::Context::new(&mut sess.interner, &mut sess.sources, fs, &opts.search);
122 cx.lex = rucc_lex::Options::for_dialect(opts.std, opts.gnu_extensions);
123 if pp.predefine(&sess.target, &predef, &mut cx).is_err() {
124 return failure(format!("{name}: the source map has no room for the built in macros"));
125 }
126 pp.run(file, &mut cx).iter().map(|token| token.to_pp()).collect()
127 };
128 diagnostics.extend(pp.take_diagnostics());
129
130 let cx = Convert {
133 keywords: &keywords,
134 interner: &sess.interner,
135 target: &sess.target,
136 std: opts.std,
137 gnu: opts.gnu_extensions,
138 pedantic: opts.pedantic,
139 };
140 let (tokens, complaints) = convert(&expanded, &cx);
141 diagnostics.extend(complaints);
142
143 let parsed = rucc_parse::parse(
144 &tokens,
145 rucc_parse::Context {
146 interner: &sess.interner,
147 std: opts.std,
148 gnu: opts.gnu_extensions,
149 pedantic: opts.pedantic,
150 error_limit: opts.error_limit as usize,
151 },
152 );
153 let parse_failed = parsed.diagnostics.iter().any(|d| d.severity.is_fatal());
154 diagnostics.extend(parsed.diagnostics);
155
156 let mut artifact = Artifact::Nothing;
157 if !parse_failed {
158 let mut checker = Checker::new(
159 &parsed.ast,
160 CheckContext {
161 names: &sess.interner,
162 target: &sess.target,
163 std: opts.std,
164 gnu: opts.gnu_extensions,
165 pedantic: opts.pedantic,
166 error_limit: opts.error_limit as usize,
167 },
168 );
169 checker.check_unit();
170 let checked = checker.finish();
171 if !checked.failed() {
172 match opts.emit {
173 EmitKind::Tast => {
174 artifact = Artifact::Text(rucc_sema::print(
175 &checked.tast,
176 &checked.types,
177 &sess.interner,
178 ));
179 }
180 EmitKind::Ir
181 | EmitKind::MirFinal
182 | EmitKind::Asm
183 | EmitKind::Object
184 | EmitKind::Executable => {
185 let lowered = rucc_lower::lower(
186 name,
187 rucc_lower::Context {
188 tast: &checked.tast,
189 types: &checked.types,
190 target: &sess.target,
191 names: &mut sess.interner,
192 },
193 );
194 let failed = lowered.diagnostics.iter().any(|d| d.severity.is_fatal());
198 if !failed {
199 if let Err(errors) = rucc_ir::verify(&lowered.module, &sess.interner) {
204 for error in errors {
205 diagnostics.push(internal(&format!("invalid IR, {error}")));
206 }
207 } else if opts.emit == EmitKind::Ir {
208 artifact =
209 Artifact::Text(rucc_ir::print(&lowered.module, &sess.interner));
210 } else {
211 match generate(&lowered.module, &mut sess.interner, &sess.target, opts)
214 {
215 Ok(made) => artifact = made,
216 Err(complaints) => diagnostics.extend(complaints),
217 }
218 }
219 }
220 diagnostics.extend(lowered.diagnostics);
221 }
222 _ => {}
223 }
224 }
225 diagnostics.extend(checked.diagnostics);
226 }
227
228 let mut messages = Vec::with_capacity(diagnostics.len());
229 let mut errors = 0;
230 for diag in &diagnostics {
231 if diag.severity.is_fatal()
232 || (diag.severity == Severity::Warning && opts.warnings_are_errors)
233 {
234 errors += 1;
235 }
236 messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
237 }
238 if errors > 0 {
239 artifact = Artifact::Nothing;
241 }
242 Compiled { artifact, messages, errors }
243}
244
245#[must_use]
255pub fn compile_ir(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
256 let mut sess = Session::new(opts.clone());
257 if opts.emit != EmitKind::Ir {
258 return failure(format!(
259 "{name}: an input of IR can only be emitted as IR, and `--emit={}` asks for what \
260 the C in front of it became",
261 opts.emit.as_str()
262 ));
263 }
264 let bytes = match fs.read(Path::new(name)) {
265 Ok(bytes) => bytes,
266 Err(e) => return failure(format!("{name}: {e}")),
267 };
268 let Ok(text) = std::str::from_utf8(bytes.as_slice()) else {
269 return failure(format!("{name}: this is not text, so it is not IR"));
270 };
271
272 let module = match rucc_ir::parse(text, &mut sess.interner) {
273 Ok(module) => module,
274 Err(error) => {
275 return failure(format!("{name}:{}: {}", error.line, error.message));
276 }
277 };
278 let mut diagnostics: Vec<Diagnostic> = Vec::new();
279 if let Err(errors) = rucc_ir::verify(&module, &sess.interner) {
280 for error in errors {
281 diagnostics.push(invalid(&format!("invalid IR, {error}")));
282 }
283 }
284 let mut messages = Vec::with_capacity(diagnostics.len());
285 for diag in &diagnostics {
286 messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
287 }
288 let errors = u32::try_from(messages.len()).unwrap_or(u32::MAX);
289 let artifact = if errors > 0 {
290 Artifact::Nothing
291 } else {
292 Artifact::Text(rucc_ir::print(&module, &sess.interner))
293 };
294 Compiled { artifact, messages, errors }
295}
296
297fn generate(
316 module: &rucc_ir::Module,
317 names: &mut Interner,
318 target: &TargetInfo,
319 opts: &Options,
320) -> Result<Artifact, Vec<Diagnostic>> {
321 let Some(machine) = Machine::for_target(target) else {
322 return Err(vec![unsupported(&format!(
323 "there is no back end for {} in this compiler yet, so there is nothing to generate",
324 target.triple
325 ))]);
326 };
327 let flags = pipeline::Flags { frame_pointer: opts.frame_pointer, red_zone: opts.red_zone };
328
329 let mut funcs = Vec::new();
330 let mut complaints = Vec::new();
331 for id in module.funcs() {
332 if module[id].is_declaration() {
333 continue;
334 }
335 match pipeline::compile(&module[id], names, &machine, flags) {
336 Ok(func) => funcs.push(func),
337 Err(why) => {
338 let name = names.resolve(module[id].name).to_owned();
339 complaints.push(unsupported(&format!("cannot generate code for '{name}': {why}")));
340 }
341 }
342 }
343 if !complaints.is_empty() {
344 return Err(complaints);
345 }
346 match opts.emit {
350 EmitKind::Asm => rucc_asm::print(&funcs, names, target)
351 .map(Artifact::Text)
352 .map_err(|why| vec![internal(&why.to_string())]),
353 EmitKind::Object | EmitKind::Executable => {
356 let text = rucc_asm::assemble(&funcs, names, target)
357 .map_err(|why| vec![internal(&why.to_string())])?;
358 rucc_object::write(&text, target).map(Artifact::Object).map_err(|why| match why {
361 rucc_object::Error::Format { .. } => vec![unsupported(&why.to_string())],
362 rucc_object::Error::Refused { .. } => vec![internal(&why.to_string())],
363 })
364 }
365 _ => Ok(Artifact::Text(rucc_mir::print(&funcs, names, target.regs))),
366 }
367}
368
369fn unsupported(message: &str) -> Diagnostic {
375 Diagnostic::error(message.to_owned(), Span::DUMMY)
376 .with_code("E0653")
377 .note("this construct is not lowered yet, see spec/17-milestones.md", Span::DUMMY)
378}
379
380fn invalid(message: &str) -> Diagnostic {
382 Diagnostic::error(message.to_owned(), Span::DUMMY).with_code("E0661")
383}
384
385fn internal(message: &str) -> Diagnostic {
387 Diagnostic::error(format!("internal error: {message}"), Span::DUMMY)
388 .with_code("E0652")
389 .note("this is a bug in rucc rather than in the program, please report it", Span::DUMMY)
390}
391
392fn failure(message: String) -> Compiled {
395 Compiled {
396 artifact: Artifact::Nothing,
397 messages: vec![format!("rucc: error: {message}")],
398 errors: 1,
399 }
400}
401
402#[cfg(test)]
403mod tests {
404 use rucc_session::{MemoryFileSystem, Std};
405 use rucc_target::Triple;
406
407 use super::*;
408
409 fn options() -> Options {
410 let mut opts = Options::new("x86_64-unknown-linux-gnu".parse::<Triple>().unwrap());
411 opts.emit = EmitKind::Tast;
412 opts
413 }
414
415 fn run(opts: &Options, source: &str) -> Compiled {
416 let mut fs = MemoryFileSystem::new();
417 fs.insert("/main.c", source.to_owned().into_bytes());
418 compile(opts, "/main.c", &fs)
419 }
420
421 fn freestanding() -> Options {
425 let mut opts = options();
426 opts.hosted = false;
427 opts.search.push_system(rucc_session::runtime::DIR);
428 opts
429 }
430
431 fn shipped(source: &str) -> String {
433 let result = run(&freestanding(), source);
434 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
435 result.text().to_owned()
436 }
437
438 fn tast(source: &str) -> String {
440 let result = run(&options(), source);
441 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
442 result.text().to_owned()
443 }
444
445 #[test]
446 fn the_shipped_stdarg_declares_a_list_and_the_four_operators() {
447 let text = shipped(concat!(
448 "#include <stdarg.h>\n",
449 "int sum(int n, ...) {\n",
450 " va_list ap, copy;\n",
451 " va_start(ap, n);\n",
452 " va_copy(copy, ap);\n",
453 " int total = va_arg(ap, int) + va_arg(copy, int);\n",
454 " va_end(ap);\n",
455 " va_end(copy);\n",
456 " return total;\n",
457 "}\n",
458 ));
459 assert!(text.contains("va-start"), "{text}");
460 assert!(text.contains("va-copy"), "{text}");
461 assert!(text.contains("va-arg"), "{text}");
462 assert!(text.contains("va-end"), "{text}");
463 }
464
465 #[test]
469 fn stdarg_hands_out_the_type_alone_when_that_is_all_that_was_asked_for() {
470 let text = shipped(concat!(
471 "#define __need___va_list\n",
472 "#include <stdarg.h>\n",
473 "int vprint(const char *f, __gnuc_va_list ap);\n",
474 "#ifdef va_start\n",
475 "#error va_start should not be defined\n",
476 "#endif\n",
477 "#ifdef _VA_LIST_DEFINED\n",
478 "#error va_list should not have been made\n",
479 "#endif\n",
480 ));
481 assert!(text.contains("vprint"), "{text}");
482 }
483
484 #[test]
487 fn stddef_answers_one_piece_at_a_time_and_the_next_request_still_gets_through() {
488 let text = shipped(concat!(
489 "#define __need_size_t\n",
490 "#include <stddef.h>\n",
491 "#ifdef offsetof\n",
492 "#error offsetof should not be defined yet\n",
493 "#endif\n",
494 "#define __need_ptrdiff_t\n",
495 "#include <stddef.h>\n",
496 "#include <stddef.h>\n",
497 "size_t a;\n",
498 "ptrdiff_t b;\n",
499 "wchar_t c;\n",
500 "max_align_t d;\n",
501 "void *e = NULL;\n",
502 "struct P { int x; long y; };\n",
503 "size_t f = offsetof(struct P, y);\n",
504 ));
505 assert!(text.contains("decl #0 a : unsigned long"), "{text}");
506 assert!(text.contains("decl #1 b : long"), "{text}");
507 }
508
509 #[test]
510 fn the_shipped_limits_and_float_are_the_targets_own_answers() {
511 let text = shipped(concat!(
512 "#include <limits.h>\n",
513 "#include <float.h>\n",
514 "int bits = CHAR_BIT;\n",
515 "long big = LONG_MAX;\n",
516 "int low = INT_MIN;\n",
517 "int radix = FLT_RADIX;\n",
518 "int digits = DBL_MANT_DIG;\n",
519 ));
520 assert!(text.contains("const 8 : int"), "{text}");
521 assert!(text.contains("const 9223372036854775807 : long"), "{text}");
522 assert!(text.contains("const 2 : int"), "{text}");
523 assert!(text.contains("const 53 : int"), "{text}");
524 }
525
526 #[test]
530 fn the_shipped_stdint_writes_the_whole_set_when_there_is_no_library_to_defer_to() {
531 let text = shipped(concat!(
532 "#include <stdint.h>\n",
533 "int64_t a = INT64_C(1);\n",
534 "uint_least16_t b;\n",
535 "intptr_t c;\n",
536 "uintmax_t d = UINTMAX_MAX;\n",
537 "int wide = sizeof(int_fast64_t);\n",
538 ));
539 assert!(text.contains("decl #0 a : long"), "{text}");
540 assert!(text.contains("decl #1 b : unsigned short"), "{text}");
541 assert!(text.contains("decl #2 c : long"), "{text}");
542 }
543
544 #[test]
545 fn the_three_formality_headers_still_have_to_work() {
546 let text = shipped(concat!(
547 "#include <stdbool.h>\n",
548 "#include <stdalign.h>\n",
549 "#include <iso646.h>\n",
550 "#include <stdnoreturn.h>\n",
551 "int t = true and not false;\n",
552 "_Alignas(16) char buf[16];\n",
553 "int a = alignof(long);\n",
554 ));
555 assert!(text.contains("decl #0 t : int"), "{text}");
556 assert!(text.contains("const 8 : unsigned long"), "{text}");
557 }
558
559 #[test]
562 fn every_shipped_header_can_be_included_twice() {
563 let mut source = String::new();
564 for _ in 0..2 {
565 for name in rucc_session::runtime::names() {
566 source.push_str(&format!("#include <{name}>\n"));
567 }
568 }
569 source.push_str("int x;\n");
570 let text = shipped(&source);
571 assert!(text.starts_with("decl #0 x : int"), "{text}");
572 }
573
574 #[test]
575 fn a_file_that_is_not_there_says_so_and_produces_nothing() {
576 let fs = MemoryFileSystem::new();
577 let result = compile(&options(), "/nope.c", &fs);
578 assert!(result.failed());
579 assert!(result.messages[0].contains("/nope.c"), "{:?}", result.messages);
580 assert!(result.text().is_empty());
581 }
582
583 #[test]
584 fn an_object_comes_out_with_its_type_its_linkage_and_how_much_of_a_definition_it_is() {
585 let text = tast("int x = 1;\n");
586 let expected = "\
587decl #0 x : int object external static defined
588 init
589 +0
590 const 1 : int
591";
592 assert_eq!(text, expected);
593 }
594
595 #[test]
596 fn the_macros_are_expanded_before_anything_is_parsed() {
597 let text = tast("#define N 2\nint a[N];\n");
601 assert!(text.starts_with("decl #0 a : int[2] object external static tentative"), "{text}");
602 }
603
604 #[test]
610 fn a_pragma_is_not_a_declaration_and_the_parse_walks_past_the_ones_it_does_not_read() {
611 let text = tast(concat!(
612 "#pragma pack(4)\n",
613 "struct s { int a; };\n",
614 "#pragma pack()\n",
615 "int b;\n",
616 "_Pragma(\"GCC visibility push(default)\") int c;\n",
617 ));
618 assert!(text.contains("decl #0 b : int"), "{text}");
619 assert!(text.contains("decl #1 c : int"), "{text}");
620 }
621
622 #[test]
630 fn the_layout_attributes_move_the_members_and_the_record_the_way_gcc_lays_them_out() {
631 tast(concat!(
632 "struct A { char c; int i; } __attribute__((packed));\n",
633 "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
634 "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
635 "struct B { char c; int i; } __attribute__((aligned));\n",
638 "_Static_assert(sizeof(struct B) == 16 && _Alignof(struct B) == 16, \"B\");\n",
639 "struct C { char c; int i __attribute__((packed)); };\n",
640 "_Static_assert(sizeof(struct C) == 5 && _Alignof(struct C) == 1, \"C\");\n",
641 "_Static_assert(__builtin_offsetof(struct C, i) == 1, \"C.i\");\n",
642 "struct D { char c; int i; } __attribute__((packed, aligned(4)));\n",
643 "_Static_assert(sizeof(struct D) == 8 && _Alignof(struct D) == 4, \"D\");\n",
644 "_Static_assert(__builtin_offsetof(struct D, i) == 1, \"D.i\");\n",
645 "struct E { char c; _Alignas(8) int i; };\n",
646 "_Static_assert(sizeof(struct E) == 16 && _Alignof(struct E) == 8, \"E\");\n",
647 "_Static_assert(__builtin_offsetof(struct E, i) == 8, \"E.i\");\n",
648 "struct F { char c; int i __attribute__((aligned(8))); };\n",
649 "_Static_assert(sizeof(struct F) == 16 && _Alignof(struct F) == 8, \"F\");\n",
650 "struct G { char c; short s; } __attribute__((aligned(2)));\n",
653 "_Static_assert(sizeof(struct G) == 4 && _Alignof(struct G) == 2, \"G\");\n",
654 "struct H { char c; int i; } __attribute__((aligned(2)));\n",
655 "_Static_assert(sizeof(struct H) == 8 && _Alignof(struct H) == 4, \"H\");\n",
656 "struct I { [[gnu::packed]] char c; int i; };\n",
659 "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
660 "struct J { char c; [[gnu::packed]] int i; };\n",
661 "_Static_assert(sizeof(struct J) == 5 && _Alignof(struct J) == 1, \"J\");\n",
662 "struct M { char c; int i : 5; int j : 20; } __attribute__((packed));\n",
663 "_Static_assert(sizeof(struct M) == 5 && _Alignof(struct M) == 1, \"M\");\n",
664 "struct N { char c; long long l; } __attribute__((aligned(32)));\n",
665 "_Static_assert(sizeof(struct N) == 32 && _Alignof(struct N) == 32, \"N\");\n",
666 "union L { char c; int i; } __attribute__((packed));\n",
667 "_Static_assert(sizeof(union L) == 4 && _Alignof(union L) == 1, \"L\");\n",
668 ));
669 }
670
671 #[test]
681 fn packing_is_what_decides_whether_a_bit_field_may_straddle_its_own_storage() {
682 assert_eq!(bit_field_byte("struct s { int x : 12; char y : 6; };"), 2);
684 assert_eq!(
685 bit_field_byte("struct s { int x : 12; char y : 6; } __attribute__((packed));"),
686 1
687 );
688 assert_eq!(
689 bit_field_byte("struct s { int x : 12; __attribute__((packed)) char y : 6; };"),
690 1
691 );
692 assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { int x : 12; char y : 6; };"), 1);
693 assert_eq!(bit_field_byte("struct s { char x; int y : 30; };"), 4);
695 assert_eq!(bit_field_byte("struct s { char x; int y : 30; } __attribute__((packed));"), 1);
696 assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { char x; int y : 30; };"), 1);
698 assert_eq!(bit_field_byte("#pragma pack(2)\nstruct s { char x; int y : 30; };"), 1);
699 }
700
701 fn bit_field_byte(record: &str) -> u64 {
703 let source = format!("{record}\nint f(struct s *p) {{ return p->y; }}\n");
704 let body = body(&source);
705 let Some((before, _)) = body.split_once("ptr_add") else { return 0 };
706 let (_, constant) = before.rsplit_once("iconst.i64 ").expect("an offset constant");
707 constant.lines().next().expect("a line").trim().parse().expect("a byte offset")
708 }
709
710 #[test]
716 fn an_attribute_among_the_specifiers_is_kept_beside_the_ones_written_in_front() {
717 tast(concat!(
718 "struct a { char c; __attribute__((aligned(8))) int i; };\n",
719 "_Static_assert(sizeof(struct a) == 16 && _Alignof(struct a) == 8, \"a\");\n",
720 "_Static_assert(__builtin_offsetof(struct a, i) == 8, \"a.i\");\n",
721 "struct b { char c; __attribute__((packed)) int i; };\n",
722 "_Static_assert(sizeof(struct b) == 5 && _Alignof(struct b) == 1, \"b\");\n",
723 "_Static_assert(__builtin_offsetof(struct b, i) == 1, \"b.i\");\n",
724 "typedef struct { char c; int i; } __attribute__((packed)) c;\n",
725 "_Static_assert(sizeof(c) == 5 && _Alignof(c) == 1, \"c\");\n",
726 ));
727 }
728
729 #[test]
735 fn pragma_pack_caps_every_member_and_is_read_where_the_body_closes() {
736 tast(concat!(
737 "#pragma pack(1)\n",
738 "struct A { char c; int i; };\n",
739 "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
740 "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
741 "#pragma pack()\n",
742 "struct B { char c; int i; };\n",
743 "_Static_assert(sizeof(struct B) == 8 && _Alignof(struct B) == 4, \"B\");\n",
744 "#pragma pack(2)\n",
745 "struct C { char c; int i; double d; };\n",
746 "_Static_assert(sizeof(struct C) == 14 && _Alignof(struct C) == 2, \"C\");\n",
747 "_Static_assert(__builtin_offsetof(struct C, d) == 6, \"C.d\");\n",
748 "struct K { char c; int i __attribute__((aligned(8))); };\n",
750 "_Static_assert(sizeof(struct K) == 6 && _Alignof(struct K) == 2, \"K\");\n",
751 "_Static_assert(__builtin_offsetof(struct K, i) == 2, \"K.i\");\n",
752 "struct J { char c; int i; } __attribute__((aligned(8)));\n",
754 "_Static_assert(sizeof(struct J) == 8 && _Alignof(struct J) == 8, \"J\");\n",
755 "#pragma pack()\n",
756 "#pragma pack(push, 1)\n",
757 "struct D { char c; short s; };\n",
758 "_Static_assert(sizeof(struct D) == 3 && _Alignof(struct D) == 1, \"D\");\n",
759 "#pragma pack(pop)\n",
760 "struct E { char c; short s; };\n",
761 "_Static_assert(sizeof(struct E) == 4 && _Alignof(struct E) == 2, \"E\");\n",
762 "struct H { char c;\n",
764 "#pragma pack(1)\n",
765 " int i; };\n",
766 "_Static_assert(sizeof(struct H) == 5 && _Alignof(struct H) == 1, \"H\");\n",
767 "#pragma pack(1)\n",
768 "struct I { char c;\n",
769 "#pragma pack()\n",
770 " int i; };\n",
771 "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
772 "#pragma pack()\n",
773 "#pragma pack(push, 8)\n",
775 "#pragma pack(push, 1)\n",
776 "struct P { char c; int i; };\n",
777 "_Static_assert(sizeof(struct P) == 5 && _Alignof(struct P) == 1, \"P\");\n",
778 "#pragma pack(pop)\n",
779 "struct Q { char c; int i; };\n",
780 "_Static_assert(sizeof(struct Q) == 8 && _Alignof(struct Q) == 4, \"Q\");\n",
781 "#pragma pack(pop)\n",
782 "#pragma pack(16)\n",
784 "struct R { char c; int i; };\n",
785 "_Static_assert(sizeof(struct R) == 8 && _Alignof(struct R) == 4, \"R\");\n",
786 "#pragma pack()\n",
787 "#pragma pack(1)\n",
788 "struct S { char c; int i : 5; int j : 20; };\n",
789 "_Static_assert(sizeof(struct S) == 5 && _Alignof(struct S) == 1, \"S\");\n",
790 "union T { char c; int i; };\n",
791 "_Static_assert(sizeof(union T) == 4 && _Alignof(union T) == 1, \"T\");\n",
792 "#pragma pack()\n",
793 ));
794 }
795
796 #[test]
800 fn a_pack_line_that_is_not_one_is_reported_in_the_words_gcc_uses() {
801 let result = run(
802 &options(),
803 concat!(
804 "#pragma pack 4\n",
805 "#pragma pack(pop)\n",
806 "#pragma pack(3)\n",
807 "#pragma pack(1) junk\n",
808 "#pragma pack(push, 1\n",
809 "#pragma pack(x)\n",
810 "#pragma pack(0)\n",
813 "#pragma pack(push)\n",
814 "struct s { char c; int i; };\n",
815 "#pragma pack(pop)\n",
816 "#pragma pack(pop, foo)\n",
817 ),
818 );
819 let expected = [
820 "missing `(` after `#pragma pack` - ignored",
821 "`#pragma pack (pop)` encountered without matching `#pragma pack (push)`",
822 "alignment must be a small power of two, not 3",
823 "junk at end of `#pragma pack`",
824 "malformed `#pragma pack(push[, id][, <n>])` - ignored",
825 "unknown action `x` for `#pragma pack` - ignored",
826 "`#pragma pack(pop, foo)` encountered without matching `#pragma pack(push, foo)`",
827 ];
828 assert_eq!(result.messages.len(), expected.len(), "{:?}", result.messages);
829 for (message, want) in result.messages.iter().zip(expected) {
830 assert!(message.contains(want), "expected {want:?} in {message:?}");
831 }
832 }
833
834 #[test]
838 fn the_wide_integer_answers_to_all_three_of_its_names() {
839 let text = tast("__uint128_t a; __int128_t b; unsigned __int128 c;\n");
840 assert!(text.contains("decl #0 a : unsigned __int128"), "{text}");
841 assert!(text.contains("decl #1 b : __int128"), "{text}");
842 assert!(text.contains("decl #2 c : unsigned __int128"), "{text}");
843 }
844
845 #[test]
846 fn every_conversion_the_language_performs_is_a_node_in_the_output() {
847 let text = tast("long f(int a, long b) { return a + b; }\n");
851 assert!(text.contains("convert arithmetic"), "{text}");
852 }
853
854 #[test]
855 fn a_mistake_in_each_phase_reaches_the_caller_and_writes_no_tree() {
856 for source in [
857 "#error stop\n",
858 "int f(void) { return 1 + ; }\n",
859 "int f(void) { return undeclared; }\n",
860 ] {
861 let result = run(&options(), source);
862 assert!(result.failed(), "expected this to fail:\n{source}");
863 assert!(
864 result.text().is_empty(),
865 "a file that did not compile wrote a tree:\n{source}"
866 );
867 }
868 }
869
870 #[test]
871 fn one_undeclared_name_is_one_message_and_not_one_per_use() {
872 let result = run(&options(), "int f(void) { return nope + nope * nope; }\n");
876 assert_eq!(result.errors, 1, "{:?}", result.messages);
877 }
878
879 #[test]
880 fn a_declaration_the_parser_skipped_does_not_become_an_undeclared_name_as_well() {
881 let result = run(&options(), "int x = ;\nint f(void) { return x; }\n");
885 assert_eq!(result.errors, 1, "{:?}", result.messages);
886 }
887
888 #[test]
889 fn werror_turns_a_warning_into_an_error_in_the_count_and_in_the_word() {
890 let source = "int f(void) { char c = 300; return c; }\n";
891 let plain = run(&options(), source);
892 assert_eq!(plain.errors, 0, "{:?}", plain.messages);
893 assert_eq!(plain.messages.len(), 1, "expected a warning about the narrowed constant");
894 assert!(!plain.text().is_empty(), "a warning is not a reason to write nothing");
895
896 let mut opts = options();
897 opts.warnings_are_errors = true;
898 let strict = run(&opts, source);
899 assert!(strict.failed());
900 assert!(strict.text().is_empty(), "and under -Werror it is a reason to write nothing");
901 for message in &strict.messages {
902 assert!(!message.contains("warning:"), "{message}");
903 }
904 }
905
906 #[test]
907 fn the_dialect_reaches_the_keywords_and_the_checking() {
908 let source = "typeof(1) x;\n";
911 let mut opts = options();
912 opts.std = Std::C23;
913 opts.gnu_extensions = false;
914 assert!(!run(&opts, source).failed(), "{:?}", run(&opts, source).messages);
915
916 opts.std = Std::C17;
917 assert!(run(&opts, source).failed());
918 }
919
920 #[test]
921 fn asking_for_a_kind_that_is_not_written_yet_runs_the_front_end_and_writes_nothing() {
922 let mut opts = options();
923 opts.emit = EmitKind::Object;
924 let result = run(&opts, "int x = 1;\n");
925 assert!(!result.failed(), "{:?}", result.messages);
926 assert!(result.text().is_empty());
927 assert!(run(&opts, "int f(void) { return undeclared; }\n").failed());
930 }
931
932 fn mir(source: &str) -> String {
934 let mut opts = options();
935 opts.emit = EmitKind::MirFinal;
936 let result = run(&opts, source);
937 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
938 result.text().to_owned()
939 }
940
941 #[test]
947 fn a_function_goes_from_c_to_instructions_with_real_registers_in_them() {
948 let text = mir("int add(int a, int b) { return a + b; }\n");
949 assert!(text.starts_with("mfunc @add {"), "{text}");
950 assert!(text.contains("x64.add_rr_32"), "{text}");
951 assert!(text.contains("x64.ret"), "{text}");
952 assert!(!text.contains('%'), "{text}");
955 }
956
957 #[test]
959 fn a_function_with_no_body_produces_no_machine_function() {
960 let text = mir("int g(int);\nint f(int a) { return g(a); }\n");
961 assert_eq!(text.matches("mfunc @").count(), 1, "{text}");
962 assert!(text.contains("mfunc @f {"), "{text}");
963 assert!(text.contains("x64.call"), "{text}");
964 }
965
966 #[test]
968 fn every_definition_in_the_file_is_generated_and_they_keep_their_order() {
969 let text = mir("int a(int x) { return x; }\nint b(int x) { return x; }\n");
970 let first = text.find("mfunc @a").expect("the first function");
971 let second = text.find("mfunc @b").expect("the second function");
972 assert!(first < second, "{text}");
973 }
974
975 #[test]
977 fn the_target_decides_which_convention_the_generated_code_follows() {
978 let mut opts = options();
979 opts.emit = EmitKind::MirFinal;
980 let linux = run(&opts, "int f(int a) { return a; }\n").text().to_owned();
981 assert!(linux.contains("$rdi"), "{linux}");
982
983 opts.target = "x86_64-pc-windows-msvc".parse::<Triple>().unwrap();
984 let windows = run(&opts, "int f(int a) { return a; }\n").text().to_owned();
985 assert!(windows.contains("$rcx"), "{windows}");
986 assert!(!windows.contains("$rdi"), "{windows}");
987 }
988
989 #[test]
991 fn a_target_this_has_no_back_end_for_is_reported_rather_than_generated() {
992 let mut opts = options();
993 opts.emit = EmitKind::MirFinal;
994 opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
995 let result = run(&opts, "int f(int a) { return a; }\n");
996 assert!(result.failed());
997 assert!(result.messages[0].contains("no back end for aarch64"), "{:?}", result.messages);
998 assert!(result.text().is_empty());
999 }
1000
1001 #[test]
1008 fn a_construct_the_back_end_cannot_reach_yet_is_reported_against_its_function() {
1009 let mut opts = options();
1010 opts.emit = EmitKind::MirFinal;
1011 let result =
1012 run(&opts, "double a(double x) { return x; }\ndouble b(double x) { return x; }\n");
1013 assert!(result.failed());
1014 assert_eq!(result.messages.len(), 2, "{:?}", result.messages);
1015 assert!(result.messages[0].contains("cannot generate code for 'a'"), "{:?}", result);
1016 assert!(result.messages[0].contains("vector register"), "{:?}", result);
1017 assert!(result.messages[1].contains("cannot generate code for 'b'"), "{:?}", result);
1018 assert!(result.text().is_empty());
1019 }
1020
1021 #[test]
1023 fn the_frame_flags_on_the_command_line_reach_the_generated_frame() {
1024 let source = "int f(int a) { return a; }\n";
1025 assert!(!mir(source).contains("$rbp"), "a leaf needs no frame pointer by default");
1026
1027 let mut opts = options();
1028 opts.emit = EmitKind::MirFinal;
1029 opts.frame_pointer = true;
1030 let kept = run(&opts, source).text().to_owned();
1031 assert!(kept.contains("x64.push_64 $rbp"), "{kept}");
1032 }
1033
1034 fn asm(source: &str) -> String {
1036 let mut opts = options();
1037 opts.emit = EmitKind::Asm;
1038 let result = run(&opts, source);
1039 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1040 result.text().to_owned()
1041 }
1042
1043 #[test]
1050 fn a_function_goes_from_c_to_assembly_an_assembler_would_take() {
1051 let text = asm("int add(int a, int b) { return a + b; }\n");
1052 assert!(text.contains("\t.globl\tadd\n"), "{text}");
1053 assert!(text.contains("\t.type\tadd, @function\n"), "{text}");
1054 assert!(text.contains("\nadd:\n"), "{text}");
1055 assert!(text.contains("\taddl\t"), "{text}");
1056 assert!(text.contains("\tret\n"), "{text}");
1057 assert!(text.contains("\t.size\tadd, .-add\n"), "{text}");
1058 assert!(text.contains(".note.GNU-stack"), "{text}");
1061 }
1062
1063 #[test]
1065 fn the_target_decides_how_the_assembly_is_spelled() {
1066 let mut opts = options();
1067 opts.emit = EmitKind::Asm;
1068 opts.target = "x86_64-apple-darwin".parse::<Triple>().unwrap();
1069 let text = run(&opts, "int f(void) { return 0; }\n").text().to_owned();
1070 assert!(text.contains("__TEXT,__text"), "{text}");
1071 assert!(text.contains("\n_f:\n"), "{text}");
1072 assert!(!text.contains(".note.GNU-stack"), "{text}");
1073 }
1074
1075 fn obj(source: &str) -> Vec<u8> {
1077 let mut opts = options();
1078 opts.emit = EmitKind::Object;
1079 let result = run(&opts, source);
1080 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1081 match result.artifact {
1082 Artifact::Object(bytes) => bytes,
1083 other => panic!("expected an object, got {other:?}"),
1084 }
1085 }
1086
1087 #[test]
1093 fn a_function_goes_from_c_to_an_object_a_linker_would_take() {
1094 let bytes = obj("int add(int a, int b) { return a + b; }\n");
1095 assert_eq!(&bytes[..4], b"\x7fELF", "an object file starts by saying it is one");
1096 let text = asm("int add(int a, int b) { return a + b; }\n");
1097 assert!(
1098 text.contains("\taddl\t"),
1099 "and the listing of it is the same instructions:\n{text}"
1100 );
1101 }
1102
1103 #[test]
1105 fn the_object_and_the_listing_are_two_spellings_of_one_compilation() {
1106 let source = "int callee(void); int g(void) { return callee(); }\n";
1110 let bytes = obj(source);
1111 assert!(
1112 bytes.windows(7).any(|w| w == b"callee\0"),
1113 "the object has to name the callee for the linker to find it"
1114 );
1115 let text = asm(source);
1116 assert!(text.contains("\tcall\tcallee\n"), "{text}");
1117 }
1118
1119 #[test]
1125 fn compiling_for_an_executable_produces_an_object_and_not_a_dump() {
1126 let mut opts = options();
1127 opts.emit = EmitKind::Executable;
1129 let result = run(&opts, "int main(void) { return 0; }\n");
1130 assert_eq!(result.messages, Vec::<String>::new());
1131 match result.artifact {
1132 Artifact::Object(bytes) => assert_eq!(&bytes[..4], b"\x7fELF"),
1133 other => panic!("expected an object, got {other:?}"),
1134 }
1135 }
1136
1137 #[test]
1139 fn a_platform_with_no_object_writer_is_said_so_rather_than_written_as_elf() {
1140 let mut opts = options();
1141 opts.emit = EmitKind::Object;
1142 opts.target = "x86_64-apple-darwin".parse::<Triple>().unwrap();
1143 let result = run(&opts, "int f(void) { return 0; }\n");
1144 assert!(result.failed(), "an object nobody can read is worse than a message");
1145 assert!(
1146 result.messages.iter().any(|m| m.contains("no object writer")),
1147 "{:?}",
1148 result.messages
1149 );
1150 }
1151
1152 fn ir(source: &str) -> String {
1154 let mut opts = options();
1155 opts.emit = EmitKind::Ir;
1156 let result = run(&opts, source);
1157 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1158 result.text().to_owned()
1159 }
1160
1161 fn body(source: &str) -> String {
1163 let text = ir(source);
1164 let (_, rest) = text.split_once("{\n").expect("a function definition");
1165 let (body, _) = rest.rsplit_once("}\n").expect("a function definition");
1166 body.to_owned()
1167 }
1168
1169 #[test]
1177 fn builtin_constant_p_is_folded_where_it_is_written_rather_than_called() {
1178 let text = ir(concat!(
1179 "int g;\n",
1180 "int a = __builtin_constant_p(1);\n",
1181 "int b = __builtin_constant_p(g);\n",
1182 "int c = __builtin_constant_p(\"abc\");\n",
1183 "int d = __builtin_constant_p(&g);\n",
1184 "int e = __builtin_constant_p(1.5);\n",
1185 "int h = __builtin_choose_expr(__builtin_constant_p(3), 11, 22);\n",
1186 ));
1187 assert!(text.contains("global @a : i32 = 1,"), "{text}");
1188 assert!(text.contains("global @b : i32 = 0,"), "{text}");
1189 assert!(text.contains("global @c : i32 = 1,"), "{text}");
1190 assert!(text.contains("global @d : i32 = 0,"), "{text}");
1191 assert!(text.contains("global @e : i32 = 1,"), "{text}");
1192 assert!(text.contains("global @h : i32 = 11,"), "{text}");
1193 assert!(!text.contains("__builtin_constant_p"), "it is not a call to anything:\n{text}");
1194
1195 let text = body("int f(void) { int i = 0; __builtin_constant_p(i++); return i; }\n");
1199 assert_eq!(text, "block0:\n %0 = iconst.i32 0\n %1 = iconst.i32 0\n return %0\n");
1200 }
1201
1202 #[test]
1211 fn a_call_to_a_library_builtin_reaches_the_library_function() {
1212 let text = body("void f(void) { __builtin_abort(); }\n");
1213 assert_eq!(text, "block0:\n call @abort() : ()\n return\n");
1214
1215 let text = ir("int f(const char *s) { return __builtin_puts(s) + __builtin_strlen(s); }\n");
1218 assert!(text.contains("call @puts(%0) : (ptr) -> i32"), "{text}");
1219 assert!(text.contains("call @strlen(%0) : (ptr) -> i64"), "{text}");
1220 assert!(!text.contains("__builtin_"), "the prefix is not part of any name here:\n{text}");
1221 }
1222
1223 #[test]
1230 fn a_library_builtin_is_diagnosed_under_the_name_the_program_wrote() {
1231 let mut opts = options();
1232 opts.emit = EmitKind::Ir;
1233 let messages = run(&opts, "void f(void) { __builtin_abort(1); }\n").messages;
1234 assert!(
1235 messages.iter().any(|m| m.contains("__builtin_abort")),
1236 "expected the written name in {messages:?}"
1237 );
1238 }
1239
1240 #[test]
1247 fn a_classification_c_has_an_operator_for_is_that_operator() {
1248 for (builtin, operator) in [
1249 ("__builtin_isgreater", "binary >"),
1250 ("__builtin_isgreaterequal", "binary >="),
1251 ("__builtin_isless", "binary <"),
1252 ("__builtin_islessequal", "binary <="),
1253 ] {
1254 let source = format!("int f(double x, double y) {{ return {builtin}(x, y); }}\n");
1255 let text = tast(&source);
1256 assert!(text.contains(&format!("{operator} : int")), "for {builtin}:\n{text}");
1257 }
1258 }
1259
1260 #[test]
1269 fn the_classification_builtins_are_comparisons_and_not_calls() {
1270 let text = body("int f(double x, double y) { return __builtin_isunordered(x, y); }\n");
1271 assert_eq!(
1272 text,
1273 "block0(%0: f64, %1: f64):\n %2 = fcmp uno %0, %1\n %3 = zext.i32 \
1274 %2\n return %3\n"
1275 );
1276
1277 let text = body("int f(double x, double y) { return __builtin_islessgreater(x, y); }\n");
1279 assert!(text.contains("fcmp one %0, %1"), "{text}");
1280
1281 let text = body("int f(double x) { return __builtin_isnan(x); }\n");
1282 assert!(text.contains("fcmp uno %0, %0"), "{text}");
1283
1284 let text = body("int f(double x) { return __builtin_isinf(x); }\n");
1285 assert!(text.contains("fconst.f64 0x7ff0000000000000"), "{text}");
1286 assert!(text.contains("fconst.f64 0xfff0000000000000"), "{text}");
1287 assert!(text.contains("%3 = fcmp oeq %0, %1"), "{text}");
1288 assert!(text.contains("%4 = fcmp oeq %0, %2"), "{text}");
1289 assert!(text.contains("%5 = or %3, %4"), "{text}");
1290
1291 let text = body("int f(double x) { return __builtin_isfinite(x); }\n");
1294 assert!(text.contains("%3 = fcmp olt %2, %0"), "{text}");
1295 assert!(text.contains("%4 = fcmp olt %0, %1"), "{text}");
1296 assert!(text.contains("%5 = and %3, %4"), "{text}");
1297
1298 let text = body("int f(double x) { return __builtin_signbit(x); }\n");
1299 assert!(text.contains("%1 = bitcast.i64 %0"), "{text}");
1300 assert!(text.contains("icmp slt %1, %2"), "{text}");
1301
1302 let text = body("int f(long double x) { return __builtin_signbitl(x); }\n");
1305 assert!(text.contains("%1 = bitcast.i80 %0"), "{text}");
1306
1307 let text = body("double g(void);\nint f(void) { return __builtin_isnan(g()); }\n");
1310 assert_eq!(text.matches("call @g()").count(), 1, "{text}");
1311 }
1312
1313 #[test]
1320 fn a_classification_spelling_that_names_a_width_converts_before_it_asks() {
1321 let text = ir(concat!(
1322 "int a = __builtin_isinff(1e300);\n",
1323 "int b = __builtin_isinf(1e300);\n",
1324 "int c = __builtin_isnan(0.0);\n",
1328 "int d = __builtin_signbit(-0.0);\n",
1329 "int e = __builtin_islessgreater(1.0, 2.0);\n",
1330 ));
1331 assert!(text.contains("global @a : i32 = 1,"), "{text}");
1332 assert!(text.contains("global @b : i32 = 0,"), "{text}");
1333 assert!(text.contains("global @c : i32 = 0,"), "{text}");
1334 assert!(text.contains("global @d : i32 = 1,"), "{text}");
1335 assert!(text.contains("global @e : i32 = 1,"), "{text}");
1336 }
1337
1338 #[test]
1340 fn a_classification_builtin_refuses_an_argument_that_is_not_floating_point() {
1341 let mut opts = options();
1342 opts.emit = EmitKind::Ir;
1343 let source = concat!(
1344 "int a(int x) { return __builtin_isnan(x); }\n",
1345 "int b(int x, int y) { return __builtin_isunordered(x, y); }\n",
1346 "int c(double x) { return __builtin_isnan(x, x); }\n",
1347 );
1348 let messages = run(&opts, source).messages;
1349 assert_eq!(
1350 messages,
1351 [
1352 "/main.c:1:23: error: non-floating-point argument in call to function \
1353 '__builtin_isnan' [E0685]",
1354 "/main.c:2:30: error: non-floating-point arguments in call to function \
1355 '__builtin_isunordered' [E0685]",
1356 "/main.c:3:26: error: too many arguments to function '__builtin_isnan' [E0511]",
1357 ]
1358 );
1359 }
1360
1361 #[test]
1369 fn a_builtin_whose_answer_is_a_constant_is_one_and_not_a_call() {
1370 let text = ir(concat!(
1371 "double a = __builtin_inf();\n",
1372 "float b = __builtin_huge_valf();\n",
1373 "long double c = __builtin_infl();\n",
1374 "double d = __builtin_huge_val();\n",
1375 ));
1376 assert!(text.contains("global @a : f64 = 0x7ff0000000000000,"), "{text}");
1377 assert!(text.contains("global @b : f32 = 0x7f800000,"), "{text}");
1378 assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
1379 assert!(text.contains("global @d : f64 = 0x7ff0000000000000,"), "{text}");
1380 assert!(!text.contains("call"), "{text}");
1381 }
1382
1383 #[test]
1392 fn a_nan_is_written_with_the_payload_the_program_asked_for() {
1393 let text = ir(concat!(
1394 "double a = __builtin_nan(\"\");\n",
1395 "double b = __builtin_nan(\"0x1\");\n",
1396 "double c = __builtin_nan(\"010\");\n",
1398 "double d = __builtin_nans(\"\");\n",
1399 "double e = __builtin_nans(\"0x1\");\n",
1400 "float f = __builtin_nanf(\"0x1\");\n",
1401 "float g = __builtin_nansf(\"\");\n",
1402 "long double h = __builtin_nansl(\"\");\n",
1403 ));
1404 assert!(text.contains("global @a : f64 = 0x7ff8000000000000,"), "{text}");
1405 assert!(text.contains("global @b : f64 = 0x7ff8000000000001,"), "{text}");
1406 assert!(text.contains("global @c : f64 = 0x7ff8000000000008,"), "{text}");
1407 assert!(text.contains("global @d : f64 = 0x7ff4000000000000,"), "{text}");
1408 assert!(text.contains("global @e : f64 = 0x7ff0000000000001,"), "{text}");
1409 assert!(text.contains("global @f : f32 = 0x7fc00001,"), "{text}");
1410 assert!(text.contains("global @g : f32 = 0x7fa00000,"), "{text}");
1411 assert!(text.contains("f80 0x7fffa000000000000000"), "{text}");
1412
1413 let text = ir(concat!(
1416 "double f(const char *p) { return __builtin_nan(p); }\n",
1417 "double g(void) { return __builtin_nans(\"1x\"); }\n",
1418 ));
1419 assert_eq!(text.matches("call @nan(").count(), 1, "{text}");
1420 assert_eq!(text.matches("call @nans(").count(), 1, "{text}");
1421 }
1422
1423 #[test]
1431 fn the_length_and_the_order_of_a_string_literal_are_known_here() {
1432 let text = ir(concat!(
1433 "unsigned long a = __builtin_strlen(\"hello\");\n",
1434 "unsigned long b = __builtin_strlen(\"a\\0bc\");\n",
1435 "int c = __builtin_strcmp(\"X\", \"X\\376\") < 0;\n",
1436 "int d = __builtin_strcmp(\"abc\", \"abc\");\n",
1437 "int e = __builtin_strcmp(\"abc\", \"ab\") > 0;\n",
1438 ));
1439 assert!(text.contains("global @a : i64 = 5,"), "{text}");
1440 assert!(text.contains("global @b : i64 = 1,"), "{text}");
1441 assert!(text.contains("global @c : i32 = 1,"), "{text}");
1442 assert!(text.contains("global @d : i32 = 0,"), "{text}");
1443 assert!(text.contains("global @e : i32 = 1,"), "{text}");
1444 assert!(!text.contains("call"), "{text}");
1445
1446 let text = ir("unsigned long f(const char *p) { return __builtin_strlen(p); }\n");
1448 assert!(text.contains("call @strlen("), "{text}");
1449 }
1450
1451 #[test]
1458 fn a_sign_builtin_is_a_mask_over_the_bits_and_not_a_call() {
1459 let text = body("double f(double x) { return __builtin_fabs(x); }\n");
1460 assert!(text.contains("bitcast.i64 %0"), "{text}");
1461 assert!(text.contains("iconst.i64 9223372036854775807"), "{text}");
1462 assert!(text.contains("and %1, %2"), "{text}");
1463 assert!(text.contains("bitcast.f64 %3"), "{text}");
1464 assert!(!text.contains("call"), "{text}");
1465
1466 let text = body("double f(double x, double y) { return __builtin_copysign(x, y); }\n");
1467 assert!(text.contains("iconst.i64 -9223372036854775808"), "{text}");
1468 assert!(text.contains("%8 = or %4, %7"), "{text}");
1469 assert!(!text.contains("call"), "{text}");
1470
1471 let text = body("long double f(long double x) { return __builtin_fabsl(x); }\n");
1474 assert!(text.contains("bitcast.i80 %0"), "{text}");
1475 assert!(text.contains("bitcast.f80"), "{text}");
1476
1477 let text = body("double f(float x) { return __builtin_fabs(x); }\n");
1480 assert!(text.contains("fpext.f64 %0"), "{text}");
1481 assert!(text.contains("bitcast.i64 %1"), "{text}");
1482 }
1483
1484 #[test]
1493 fn the_sign_builtins_answer_a_zero_and_a_nan_the_way_the_bits_say() {
1494 let text = ir(concat!(
1495 "double a = __builtin_fabs(-3.5);\n",
1496 "double b = __builtin_copysign(1.0, -0.0);\n",
1497 "double c = __builtin_copysign(0.0, -2.0);\n",
1498 "double d = __builtin_copysign(-__builtin_nan(\"\"), 1.0);\n",
1500 "double e = __builtin_fabs(-__builtin_nan(\"0x1\"));\n",
1501 "float g = __builtin_copysignf(-0.0f, 2.0f);\n",
1502 "long double h = __builtin_copysignl(1.0L, -1.0L);\n",
1503 "long double i = __builtin_fabsl(-__builtin_infl());\n",
1504 ));
1505 assert!(text.contains("global @a : f64 = 0x400c000000000000,"), "{text}");
1506 assert!(text.contains("global @b : f64 = 0xbff0000000000000,"), "{text}");
1507 assert!(text.contains("global @c : f64 = 0x8000000000000000,"), "{text}");
1508 assert!(text.contains("global @d : f64 = 0x7ff8000000000000,"), "{text}");
1509 assert!(text.contains("global @e : f64 = 0x7ff8000000000001,"), "{text}");
1510 assert!(text.contains("global @g : f32 = 0x0,"), "{text}");
1511 assert!(text.contains("f80 0xbfff8000000000000000"), "{text}");
1512 assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
1513 }
1514
1515 #[test]
1522 fn a_constexpr_object_is_a_constant_wherever_one_is_required() {
1523 let text = ir(concat!(
1524 "constexpr int side = 4;\n",
1525 "constexpr int wider = side + 1;\n",
1526 "constexpr double half = 1.5;\n",
1527 "struct point { int x; int y; };\n",
1528 "constexpr struct point origin = { 5, 6 };\n",
1529 "int square[side * side];\n",
1530 "int rectangle[wider];\n",
1531 "int rounded[(int)half * 2];\n",
1532 "int across[origin.y];\n",
1533 "enum named { four = side };\n",
1534 "int e = four;\n",
1535 ));
1536 assert!(text.contains("global @square : bytes 64 ="), "{text}");
1537 assert!(text.contains("global @rectangle : bytes 20 ="), "{text}");
1538 assert!(text.contains("global @rounded : bytes 8 ="), "{text}");
1539 assert!(text.contains("global @across : bytes 24 ="), "{text}");
1540 assert!(text.contains("global @e : i32 = 4,"), "{text}");
1541
1542 let mut opts = options();
1545 opts.emit = EmitKind::Ir;
1546 let konst = "const int n = 1;\nint a[n];\n";
1547 let message = "/main.c:2:5: error: variably modified 'a' at file scope [E0538]";
1548 assert_eq!(run(&opts, konst).messages, [message]);
1549
1550 let subscript = "constexpr int t[3] = { 1, 2, 3 };\nint a[t[1]];\n";
1552 assert_eq!(run(&opts, subscript).messages, [message]);
1553
1554 let address = "constexpr int c = 3;\nint *p = &c;\n";
1556 let warning = "/main.c:2:6: warning: initialization discards 'const' qualifier from \
1557 pointer target type [E0514]";
1558 assert_eq!(run(&opts, address).messages, [warning]);
1559 }
1560
1561 #[test]
1570 fn an_old_style_definition_takes_its_types_from_the_declarations_under_its_list() {
1571 let mut opts = options();
1574 opts.std = Std::C17;
1575 let source = concat!(
1576 "int add(a, b)\n",
1577 "int a;\n",
1578 "int b;\n",
1579 "{ return a + b; }\n",
1580 "int promoted(c)\n",
1581 "char c;\n",
1582 "{ return c; }\n",
1583 "int narrow(char);\n",
1584 "int narrow(c)\n",
1585 "char c;\n",
1586 "{ return c; }\n",
1587 "int first(a)\n",
1588 "int a[4];\n",
1589 "{ return a[0]; }\n",
1590 );
1591 let result = run(&opts, source);
1592 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1593 let text = result.text();
1594 assert!(text.contains("add : int(int, int) function external defined"), "{text}");
1595 assert!(text.contains("promoted : int(int) function external defined"), "{text}");
1596 assert!(text.contains("c : char object automatic defined"), "{text}");
1598 assert!(text.contains("narrow : int(char) function external defined"), "{text}");
1599 assert!(text.contains("first : int(int *) function external defined"), "{text}");
1601 }
1602
1603 #[test]
1610 fn the_two_halves_of_an_old_style_parameter_list_have_to_agree() {
1611 let mut opts = options();
1612 opts.std = Std::C17;
1613 for (source, message) in [
1614 ("int f(a, a)\nint a;\n{ return a; }\n", "1:10: error: multiple parameters named 'a'"),
1615 (
1616 "int f(a)\nint a;\nint b;\n{ return a; }\n",
1617 "3:5: error: declaration for parameter 'b' but no such parameter",
1618 ),
1619 ("int f(a)\nint a;\nint a;\n{ return a; }\n", "3:5: error: redefinition of parameter"),
1620 ("int f(a)\nint a = 1;\n{ return a; }\n", "2:5: error: parameter 'a' is initialized"),
1621 (
1622 "int f(a)\nstatic int a;\n{ return a; }\n",
1623 "2:12: error: storage class specified for parameter 'a'",
1624 ),
1625 (
1626 "int f(char);\nint f(a)\nshort a;\n{ return a; }\n",
1627 "2:7: error: argument 'a' doesn't match prototype",
1628 ),
1629 ] {
1630 let result = run(&opts, source);
1631 assert!(result.failed(), "expected this to fail:\n{source}");
1632 assert!(result.messages[0].contains(message), "{:?}", result.messages);
1633 }
1634
1635 let implicit = "int f(a, b)\nint a;\n{ return a + b; }\n";
1638 let mut older = options();
1639 older.std = Std::C89;
1640 assert!(!run(&older, implicit).failed(), "{:?}", run(&older, implicit).messages);
1641 let result = run(&opts, implicit);
1642 assert!(
1643 result.messages[0].contains("1:10: error: type of 'b' defaults to 'int'"),
1644 "{:?}",
1645 result.messages
1646 );
1647
1648 let mut newer = options();
1652 newer.std = Std::C23;
1653 let plain = "int f(a)\nint a;\n{ return a; }\n";
1654 let result = run(&newer, plain);
1655 assert!(!result.failed(), "{:?}", result.messages);
1656 assert_eq!(
1657 result.messages,
1658 ["/main.c:1:5: warning: old-style function definition [E0412]"]
1659 );
1660 assert!(run(&opts, plain).messages.is_empty(), "and nothing to say in the dialects before");
1661 }
1662
1663 #[test]
1670 fn a_type_is_refused_when_it_passes_the_largest_object_and_not_before() {
1671 let text = ir(concat!(
1672 "struct huge_struct { short buf[(1L << 62) - 256]; int a, b, c, d; };\n",
1673 "struct brim { char buf[9223372036854775807L]; };\n",
1674 "struct bitty { char buf[9223372036854775800L]; int x : 1; };\n",
1675 "unsigned long h = sizeof(struct huge_struct);\n",
1676 "unsigned long b = sizeof(struct brim);\n",
1677 "unsigned long y = sizeof(struct bitty);\n",
1678 ));
1679 assert!(text.contains("global @h : i64 = 9223372036854775312,"), "{text}");
1680 assert!(text.contains("global @b : i64 = 9223372036854775807,"), "{text}");
1681 assert!(text.contains("global @y : i64 = 9223372036854775804,"), "{text}");
1682
1683 let mut opts = options();
1684 opts.emit = EmitKind::Ir;
1685 let over = "struct over { char buf[9223372036854775800L]; char x[8]; };\n";
1686 let message = "/main.c:1:1: error: type 'struct over' is too large [E0560]";
1687 assert_eq!(run(&opts, over).messages, [message]);
1688 let array = "struct wide { short buf[1L << 62]; };\n";
1689 let message = "/main.c:1:25: error: size of array 'buf' exceeds \
1690 maximum object size '9223372036854775807' [E0537]";
1691 assert_eq!(run(&opts, array).messages[0], message);
1692 }
1693
1694 fn compile_bytes(source: &[u8]) -> Compiled {
1699 let mut opts = options();
1700 opts.emit = EmitKind::Ir;
1701 let mut fs = MemoryFileSystem::new();
1702 fs.insert("/main.c", source.to_vec());
1703 compile(&opts, "/main.c", &fs)
1704 }
1705
1706 #[test]
1713 fn a_byte_that_is_not_a_character_is_kept_in_a_literal_and_refused_outside_one() {
1714 let mut source = b"char s[] = \"a".to_vec();
1715 source.push(0xff);
1716 source.extend_from_slice(b"b\";\nchar c = '");
1717 source.push(0xff);
1718 source.extend_from_slice(b"';\n");
1719 let result = compile_bytes(&source);
1720 assert_eq!(result.messages, Vec::<String>::new(), "a raw byte in a literal is that byte");
1721 assert!(result.text().contains(r#"bytes "a\ffb\00""#), "{}", result.text());
1722 assert!(result.text().contains("global @c : i8 = -1,"), "{}", result.text());
1724
1725 let mut stray = b"int a".to_vec();
1726 stray.push(0xff);
1727 stray.extend_from_slice(b" = 1;\n");
1728 let result = compile_bytes(&stray);
1729 assert!(
1730 result.messages.iter().any(|m| m.contains("source is not valid UTF-8 here")),
1731 "{:?}",
1732 result.messages
1733 );
1734 }
1735
1736 #[test]
1737 fn an_object_becomes_a_global_with_an_image_and_a_function_becomes_a_func() {
1738 let text = ir("int x = 7;\nint add(int a, int b) { return a + b; }\n");
1739 assert!(text.contains("global @x : i32 = 7, align 4, linkage(external)\n"), "{text}");
1740 let expected = "\
1741func @add(i32, i32) -> i32, linkage(external) {
1742block0(%0: i32, %1: i32):
1743 %2 = add.nsw %0, %1
1744 return %2
1745}
1746";
1747 assert!(text.contains(expected), "{text}");
1748 }
1749
1750 #[test]
1751 fn a_local_nothing_takes_the_address_of_is_a_value_and_never_a_stack_slot() {
1752 let text = body("int f(int n) { int a = n + 1; int b = a * 2; return a + b; }\n");
1753 assert!(!text.contains("alloca"), "{text}");
1754 assert!(!text.contains("load"), "{text}");
1755 assert!(!text.contains("store"), "{text}");
1756 }
1757
1758 #[test]
1759 fn a_local_whose_address_is_taken_gets_a_slot_in_the_entry_block() {
1760 let text = body("int g(int *);\nint f(void) { int a = 1; return g(&a); }\n");
1761 let expected = "\
1762block0:
1763 %0 = alloca, size 4, align 4
1764 %1 = iconst.i32 1
1765 store %1 -> %0, align 4
1766 %2 = call @g(%0) : (ptr) -> i32
1767 return %2
1768";
1769 assert_eq!(text, expected);
1770 }
1771
1772 #[test]
1773 fn a_loop_carries_what_it_changes_as_block_parameters() {
1774 let text = body(
1777 "int f(int n) {\n int total = 0;\n for (int i = 0; i < n; i++) total += i;\n \
1778 return total;\n}\n",
1779 );
1780 assert!(!text.contains("alloca"), "{text}");
1781 assert!(text.contains("block1(%3: i32, %4: i32):"), "{text}");
1782 assert!(text.contains("jump block1("), "{text}");
1783 }
1784
1785 #[test]
1786 fn a_comparison_used_as_a_condition_is_not_widened_and_narrowed_again() {
1787 let text = body("int f(int a, int b) { if (a < b) return 1; return 0; }\n");
1788 assert!(text.contains("icmp slt %0, %1"), "{text}");
1789 assert!(!text.contains("zext"), "{text}");
1790 }
1791
1792 #[test]
1793 fn the_right_side_of_a_short_circuit_is_in_a_block_of_its_own() {
1794 let text = body("int f(int a, int b) { return a && b; }\n");
1795 let expected = "\
1796block0(%0: i32, %1: i32):
1797 %2 = iconst.i32 0
1798 %3 = icmp ne %0, %2
1799 %4 = iconst.i1 0
1800 br_if %3, block1, block2(%4)
1801
1802block1:
1803 %5 = iconst.i32 0
1804 %6 = icmp ne %1, %5
1805 jump block2(%6)
1806
1807block2(%7: i1):
1808 %8 = zext.i32 %7
1809 return %8
1810";
1811 assert_eq!(text, expected);
1812 }
1813
1814 #[test]
1815 fn code_after_a_return_is_not_built_and_does_not_leave_an_empty_block_behind() {
1816 let text = body("int f(int a) { if (a) return 1; else return 2; return 3; }\n");
1817 assert!(!text.contains("block3"), "{text}");
1820 assert!(!text.contains("iconst.i32 3"), "{text}");
1821 }
1822
1823 #[test]
1824 fn falling_off_the_end_returns_zero_from_main_and_nothing_from_a_void_function() {
1825 assert!(body("int main(void) { }\n").contains("iconst.i32 0\n return"));
1826 assert_eq!(body("void f(void) { }\n"), "block0:\n return\n");
1827 assert!(body("int f(void) { }\n").contains("unreachable"));
1828 }
1829
1830 #[test]
1831 fn a_structure_is_copied_rather_than_held_in_a_value() {
1832 let text = body(
1833 "struct point { int x, y; };\n\
1834 int f(void) { struct point p = { 1, 2 }; struct point q = p; return q.x; }\n",
1835 );
1836 assert!(text.contains("memcpy"), "{text}");
1837 }
1838
1839 #[test]
1840 fn an_initializer_that_leaves_part_of_an_object_unwritten_zeroes_it_first() {
1841 let text = body("int f(void) { int a[4] = { 1 }; return a[3]; }\n");
1842 assert!(text.contains("memset"), "{text}");
1843 }
1844
1845 #[test]
1846 fn a_switch_is_one_branch_and_a_case_that_falls_through_carries_what_it_wrote() {
1847 let text = body(
1848 "int f(int x) { int r = 0; switch (x) { case 1: r = 1; case 2: r += 2; break; \
1849 default: r = 4; } return r; }\n",
1850 );
1851 let expected = "\
1852block0(%0: i32):
1853 %1 = iconst.i32 0
1854 switch %0, block1, [1 => block2, 2 => block3(%1)]
1855
1856block1:
1857 %2 = iconst.i32 4
1858 jump block4(%2)
1859
1860block2:
1861 %3 = iconst.i32 1
1862 jump block3(%3)
1863
1864block3(%4: i32):
1865 %5 = iconst.i32 2
1866 %6 = add.nsw %4, %5
1867 jump block4(%6)
1868
1869block4(%7: i32):
1870 return %7
1871";
1872 assert_eq!(text, expected);
1873 }
1874
1875 #[test]
1876 fn a_case_range_is_tested_for_rather_than_put_in_the_table() {
1877 let text = body("int f(int x) { switch (x) { case 1 ... 9: return 1; } return 0; }\n");
1880 assert!(text.contains("%2 = sub %0, %1"), "{text}");
1881 assert!(text.contains("icmp ule"), "{text}");
1882 assert!(!text.contains("switch"), "{text}");
1883 }
1884
1885 #[test]
1886 fn break_leaves_the_switch_and_continue_leaves_the_loop_around_it() {
1887 let text = body(
1888 "int f(int n) { int t = 0; for (int i = 0; i < n; i++) { switch (i) { \
1889 case 0: continue; case 1: break; default: t += i; } t++; } return t; }\n",
1890 );
1891 assert!(text.contains("switch %3, block4, [0 => block5, 1 => block6]"), "{text}");
1894 assert!(text.contains("block5:\n jump block7("), "{text}");
1895 assert!(text.contains("block6:\n jump block8("), "{text}");
1896 }
1897
1898 #[test]
1899 fn a_switch_with_nothing_to_branch_on_still_runs_what_comes_after_it() {
1900 assert_eq!(body("void f(int x) { switch (x) { } }\n"), "block0(%0: i32):\n return\n");
1901 }
1902
1903 #[test]
1904 fn a_label_a_loop_is_only_entered_through_builds_the_loop_around_it() {
1905 let text = body(
1910 "int f(int x, int n) { switch (x) { case 1: break; while (n) { case 2: n--; } } \
1911 return n; }\n",
1912 );
1913 assert!(text.contains("switch %0, block1(%1), [1 => block2, 2 => block3(%1)]"), "{text}");
1916 assert!(text.contains("block3(%3: i32):\n %4 = iconst.i32 1"), "{text}");
1917 assert!(text.contains("block5:\n jump block3("), "{text}");
1918 }
1919
1920 #[test]
1921 fn a_goto_into_a_loop_body_enters_it_without_the_test() {
1922 let text = body("int f(int x, int n) { goto in; while (n) { in: n--; } return n; }\n");
1925 assert!(text.starts_with("block0(%0: i32, %1: i32):\n jump block1(%1)"), "{text}");
1926 assert!(text.contains("block1(%2: i32):\n %3 = iconst.i32 1"), "{text}");
1927 assert!(text.contains("br_if %7, block3, block4"), "{text}");
1928 }
1929
1930 #[test]
1931 fn a_goto_is_a_jump_to_the_block_the_label_starts() {
1932 let text = body("int f(int x) { int r = 0; if (x) goto out; r = 1; out: return r; }\n");
1933 assert!(!text.contains("alloca"), "{text}");
1935 assert!(text.contains("block3(%4: i32):\n return %4"), "{text}");
1936 assert_eq!(text.matches("jump block3(").count(), 2, "{text}");
1937 }
1938
1939 #[test]
1940 fn a_backward_goto_is_a_loop_and_carries_what_it_changes() {
1941 let text =
1942 body("int f(int n) { int i = 0; again: if (i < n) { i++; goto again; } return i; }\n");
1943 assert!(!text.contains("alloca"), "{text}");
1944 assert!(text.contains("block1(%2: i32):"), "{text}");
1945 assert!(text.contains("jump block1(%5)"), "{text}");
1946 }
1947
1948 #[test]
1949 fn a_label_nothing_reaches_is_taken_out_rather_than_left_for_the_verifier() {
1950 assert_eq!(
1953 body("int f(int x) { return x; spare: return 0; }\n"),
1954 "block0(%0: i32):\n return %0\n"
1955 );
1956 }
1957
1958 #[test]
1959 fn a_bit_field_is_read_by_loading_the_bytes_it_lies_in_and_shifting() {
1960 let text = body(
1961 "struct s { unsigned a : 3; signed b : 5; };\nint f(struct s *p) { return p->b; }\n",
1962 );
1963 assert_eq!(
1966 text,
1967 "\
1968block0(%0: ptr):
1969 %1 = load.i8 %0, align 1
1970 %2 = iconst.i8 3
1971 %3 = ashr %1, %2
1972 %4 = sext.i32 %3
1973 return %4
1974"
1975 );
1976 }
1977
1978 #[test]
1979 fn a_store_to_a_bit_field_does_not_write_a_byte_it_has_no_bit_in() {
1980 let text =
1984 body("struct s { int a : 24; char c; };\nvoid f(struct s *p, int v) { p->a = v; }\n");
1985 assert_eq!(
1986 text,
1987 "\
1988block0(%0: ptr, %1: i32):
1989 %2 = iconst.i32 16777215
1990 %3 = and %1, %2
1991 %4 = trunc.i16 %3
1992 store %4 -> %0, align 2
1993 %5 = iconst.i32 16
1994 %6 = lshr %3, %5
1995 %7 = trunc.i8 %6
1996 %8 = iconst.i64 2
1997 %9 = ptr_add %0, %8
1998 store %7 -> %9, align 1
1999 return
2000"
2001 );
2002 }
2003
2004 #[test]
2005 fn what_an_assignment_to_a_bit_field_is_worth_is_what_fits_in_it() {
2006 let text =
2007 body("struct s { unsigned b : 5; };\nunsigned f(struct s *p) { return p->b = 33; }\n");
2008 assert!(text.contains("%3 = iconst.i8 31\n %4 = and %2, %3"), "{text}");
2011 assert!(text.ends_with("%9 = zext.i32 %4\n return %9\n"), "{text}");
2012 }
2013
2014 #[test]
2015 fn an_assignment_a_statement_throws_away_builds_none_of_what_it_is_worth() {
2016 let text = body("struct s { signed b : 5; };\nvoid f(struct s *p) { p->b = 3; }\n");
2019 assert_eq!(text.matches("ashr").count(), 0, "{text}");
2020 assert!(text.ends_with("store %8 -> %0, align 1\n return\n"), "{text}");
2021 }
2022
2023 #[test]
2024 fn a_bit_field_in_an_initializer_goes_in_over_bytes_that_were_zeroed_first() {
2025 let text = body(
2029 "struct s { int a : 3; int b; };\nint f(void) { struct s v = { 1 }; return v.b; }\n",
2030 );
2031 assert!(text.contains("memset %0, %1, size 8, align 4"), "{text}");
2032 }
2033
2034 #[test]
2035 fn the_image_of_a_static_bit_field_is_the_bytes_the_fields_share() {
2036 let text = ir("struct s { unsigned a : 3; unsigned b : 5; } g = { 1, 2 };\n");
2039 assert!(
2040 text.contains("global @g : bytes 4 = { bytes \"\\11\", zero 3 }, align 4"),
2041 "{text}"
2042 );
2043 }
2044
2045 #[test]
2046 fn an_initialized_flexible_array_member_makes_the_object_larger_than_its_type() {
2047 let text = ir(concat!(
2052 "struct a { int i; int j[]; } x = { 1, { 2, 0, 2, 3 } };\n",
2053 "struct b { char c; char p[]; } y = { 'o', \"wx\" };\n",
2054 "struct c { char c; char p[]; } z = { '9', { 'e', 'b' } };\n",
2055 "char s[2] = \"hi\";\n",
2056 ));
2057 assert!(
2058 text.contains("global @x : bytes 20 = { i32 1, i32 2, i32 0, i32 2, i32 3 }"),
2059 "{text}"
2060 );
2061 assert!(text.contains("global @y : bytes 4 = { i8 111, bytes \"wx\\00\" }"), "{text}");
2062 assert!(text.contains("global @z : bytes 3 = { i8 57, i8 101, i8 98 }"), "{text}");
2063 assert!(text.contains("global @s : bytes 2 = { bytes \"hi\" }"), "{text}");
2066 }
2067
2068 #[test]
2069 fn a_definition_takes_a_parameter_it_left_unnamed() {
2070 let text = ir("int f(int a, int) { return a; }\n");
2074 assert!(text.contains("func @f(i32, i32) -> i32"), "{text}");
2075 assert!(text.contains("block0(%0: i32, %1: i32):"), "{text}");
2076
2077 let text = ir("int g(int, int n) { return n; }\n");
2080 assert!(text.contains("block0(%0: i32, %1: i32):\n return %1\n"), "{text}");
2081 }
2082
2083 #[test]
2084 fn an_assignment_of_a_structure_is_the_object_it_wrote() {
2085 let text = body(concat!(
2090 "struct s { int f; int g; };\n",
2091 "void h(struct s *a, struct s *c, struct s *d, struct s *e)\n",
2092 "{ *d = *e = a[0] = *c; }\n",
2093 ));
2094 assert_eq!(text.matches("memcpy").count(), 3, "{text}");
2095 assert!(text.contains("memcpy %8, %1, size 8, align 4\n"), "{text}");
2096 assert!(text.contains("memcpy %3, %8, size 8, align 4\n"), "{text}");
2097 assert!(text.contains("memcpy %2, %3, size 8, align 4\n"), "{text}");
2098 }
2099
2100 #[test]
2101 fn a_string_literal_stops_at_the_end_of_the_array_it_is_filling() {
2102 let mut opts = options();
2107 opts.emit = EmitKind::Ir;
2108 let result = run(
2109 &opts,
2110 concat!(
2111 "const char a[2][3] = { \"1234\", \"xyz\" };\n",
2112 "static const char b[3][5] = { \"12345\", \"678\", \"9\" };\n",
2113 "union u { struct { char x[4]; char y[4]; }; struct { char z[8]; }; };\n",
2114 "const union u c = { { \"1234\", \"567\" } };\n",
2115 ),
2116 );
2117 let text = result.text();
2118 assert_eq!(
2119 result.messages,
2120 ["/main.c:1:24: warning: initializer-string for array of 'const char' is too long \
2121 (5 chars into 3 available) [E0637]"]
2122 );
2123 assert!(text.contains("global @a : bytes 6 = { bytes \"123\", bytes \"xyz\" }"), "{text}");
2124 assert!(
2125 text.contains(
2126 "global @b : bytes 15 = { bytes \"12345\", bytes \"678\\00\", zero 1, \
2127 bytes \"9\\00\", zero 3 }"
2128 ),
2129 "{text}"
2130 );
2131 assert!(
2134 text.contains("global @c : bytes 8 = { bytes \"1234\", bytes \"567\\00\" }"),
2135 "{text}"
2136 );
2137 }
2138
2139 #[test]
2140 fn a_cast_of_a_record_to_its_own_type_is_the_object_that_was_cast() {
2141 let text = body(concat!(
2145 "struct s { int a, b; };\nstruct v { struct s s; int t; };\n",
2146 "void g(struct v *);\n",
2147 "void f(struct s *p) { struct v w = { (struct s)*p, 5 }; g(&w); }\n",
2148 ));
2149 assert_eq!(text.matches("memcpy").count(), 1, "{text}");
2150 }
2151
2152 #[test]
2153 fn a_compound_literal_read_in_a_static_initializer_lays_its_bytes_into_the_image() {
2154 let text = ir(concat!(
2159 "struct s { int x; };\n",
2160 "struct t { struct s s; int o; } a = { (struct s){ 2 }, 3 };\n",
2161 "int n = (int){ 7 };\n",
2162 "struct u { struct s p; struct s q; } b = { (struct s){ 1 }, (struct s){ } };\n",
2163 ));
2164 assert!(text.contains("global @a : bytes 8 = { i32 2, i32 3 }"), "{text}");
2165 assert!(text.contains("global @n : i32 = 7,"), "{text}");
2166 assert!(text.contains("global @b : bytes 8 = { i32 1, zero 4 }"), "{text}");
2169 }
2170
2171 #[test]
2172 fn the_address_of_a_compound_literal_asks_for_the_object_it_points_at() {
2173 let text = ir("struct s { int x; };\nstruct s *q = &(struct s){ 9 };\n");
2177 assert!(text.contains("global @.Lanon.0 : i32 = 9, align 4, linkage(internal)"), "{text}");
2178 assert!(text.contains("global @q : bytes 8 = { addr.8 @.Lanon.0 }"), "{text}");
2179 }
2180
2181 #[test]
2182 fn an_object_of_no_size_at_all_has_an_image_with_nothing_in_it() {
2183 let text = ir("unsigned char foo[1][0];\n");
2187 assert!(text.contains("global @foo : bytes 0 = {}, align 1"), "{text}");
2188 }
2189
2190 #[test]
2191 fn a_null_pointer_in_an_image_is_the_bits_an_address_has_room_for() {
2192 let text = ir("void *p = 0;\nchar *q = (char *) 4096;\n");
2195 assert!(text.contains("global @p : i64 = 0, align 8"), "{text}");
2196 assert!(text.contains("global @q : i64 = 4096, align 8"), "{text}");
2197 }
2198
2199 #[test]
2200 fn an_object_another_module_defines_may_be_one_that_cannot_be_written_through() {
2201 let text = ir("extern const int limit;\nint f(void) { return limit; }\n");
2205 assert!(
2206 text.contains("global @limit : bytes 4, align 4, linkage(external), constant"),
2207 "{text}"
2208 );
2209 }
2210
2211 #[test]
2212 fn a_conditional_whose_value_is_an_object_answers_where_the_object_is() {
2213 let text = body(
2218 "\
2219struct s { int a, b; };
2220struct s pick(int c, struct s x, struct s y) { return c ? x : y; }
2221",
2222 );
2223 assert!(text.contains("block3(%7: ptr)"), "{text}");
2225 assert!(text.contains("jump block3(%3)") && text.contains("jump block3(%4)"), "{text}");
2226 assert!(!text.contains("memcpy"), "the arms are joined rather than copied: {text}");
2227 }
2228
2229 #[test]
2230 fn a_structure_that_fits_in_registers_travels_as_the_registers_it_fits_in() {
2231 let text = ir("\
2235struct pair { int a, b; };
2236struct pair make(int a, int b);
2237struct pair twice(struct pair p) { return make(p.a, p.b); }
2238");
2239 assert!(text.contains("func @make(i32, i32) -> i64"), "{text}");
2240 assert!(text.contains("func @twice(i64) -> i64"), "{text}");
2241 }
2242
2243 #[test]
2244 fn a_structure_too_large_for_the_registers_travels_as_where_its_bytes_are() {
2245 let text = ir("\
2249struct big { double v[8]; };
2250struct big grow(struct big b);
2251struct big twice(struct big b) { return grow(grow(b)); }
2252");
2253 assert!(
2254 text.contains("func @grow(ptr sret(64, align 8), ptr byval(64, align 8))"),
2255 "{text}"
2256 );
2257 assert!(text.contains("block0(%0: ptr, %1: ptr):"), "{text}");
2258 assert_eq!(text.matches("call @grow").count(), 2, "{text}");
2261 }
2262
2263 #[test]
2264 fn a_structure_passed_to_a_variadic_function_says_so_at_the_call() {
2265 let text = ir("\
2270struct big { double v[8]; };
2271struct pair { int a, b; };
2272int p(const char *, ...);
2273int f(struct big b, struct pair q) { return p(\"\", 1, b, q); }
2274");
2275 assert!(
2276 text.contains("call @p(%4, %5, %2 byval(64, align 8), %6) : (ptr, ...) -> i32"),
2277 "{text}"
2278 );
2279 }
2280
2281 #[test]
2282 fn what_a_call_produced_is_somewhere_before_anything_is_read_out_of_it() {
2283 let body = body(
2286 "\
2287struct pair { int a, b; };
2288struct pair make(int a, int b);
2289int second(void) { return make(1, 2).b; }
2290",
2291 );
2292 assert!(body.starts_with("block0:\n %0 = alloca, size 8, align 4\n"), "{body}");
2293 assert!(body.contains("store %3 -> %0, align 4\n"), "{body}");
2294 }
2295
2296 #[test]
2297 fn a_structure_of_floats_travels_in_floating_point_registers_on_aarch64() {
2298 let source = "\
2302struct hfa { float x, y, z; };
2303int take(struct hfa h);
2304int give(struct hfa h) { return take(h); }
2305";
2306 assert!(ir(source).contains("func @take(f64, f32) -> i32"), "{}", ir(source));
2307 let mut opts = options();
2308 opts.emit = EmitKind::Ir;
2309 opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
2310 let result = run(&opts, source);
2311 assert_eq!(result.messages, Vec::<String>::new());
2312 assert!(result.text().contains("func @take(f32, f32, f32) -> i32"), "{}", result.text());
2313 }
2314
2315 #[test]
2316 fn an_array_whose_length_is_not_a_constant_is_a_slot_made_where_its_declaration_is() {
2317 let source = "\
2320int use(int *);
2321void f(int n) {
2322 {
2323 int a[n];
2324 use(a);
2325 }
2326 use(0);
2327}
2328";
2329 let body = body(source);
2330 assert!(body.contains("mul.nsw"), "{body}");
2331 assert!(body.contains("stacksave"), "{body}");
2332 assert!(body.contains("alloca %"), "{body}");
2333 assert!(body.contains("stackrestore"), "{body}");
2334 }
2335
2336 #[test]
2337 fn a_goto_out_of_the_scope_of_one_gives_its_stack_back_on_the_way() {
2338 let source = "\
2343int use(int *);
2344int f(int n) {
2345 {
2346 int a[n];
2347 if (use(a)) goto out;
2348 use(0);
2349 }
2350out:
2351 return 0;
2352}
2353";
2354 let body = body(source);
2355 assert_eq!(body.matches("stackrestore").count(), 2, "{body}");
2357 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
2358 assert!(after.starts_with(" %4\n jump block"), "{body}");
2359 }
2360
2361 #[test]
2362 fn a_goto_to_a_label_the_array_is_still_alive_at_leaves_the_stack_alone() {
2363 let source = "\
2367int use(int *);
2368int f(int n) {
2369 int a[n];
2370again:
2371 if (use(a)) goto again;
2372 return 0;
2373}
2374";
2375 let body = body(source);
2376 assert!(body.contains("stacksave"), "{body}");
2377 assert!(!body.contains("stackrestore"), "{body}");
2378 }
2379
2380 #[test]
2381 fn a_goto_back_to_a_label_in_front_of_one_gives_it_back_every_time_round() {
2382 let source = "\
2387int use(int *);
2388int f(int n) {
2389again:
2390 {
2391 int a[n];
2392 if (use(a)) goto again;
2393 }
2394 return 0;
2395}
2396";
2397 let body = body(source);
2398 assert_eq!(body.matches("stacksave").count(), 1, "{body}");
2399 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
2400 assert!(after.starts_with(" %4\n jump block1\n"), "{body}");
2401 }
2402
2403 #[test]
2404 fn the_head_of_a_for_loop_is_a_scope_that_closes_where_the_loop_is_left() {
2405 let source = "\
2411int f(void);
2412void t(void) {
2413 int count = 10;
2414 for (; count--;) {
2415 int b[f()];
2416 int i;
2417 for (i = 0; i < f(); i++) {
2418 b[i] = count;
2419 }
2420 }
2421}
2422";
2423 let body = body(source);
2424 assert_eq!(body.matches("stacksave").count(), 1, "{body}");
2428 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
2429 let (next, _) = after.split_once("\n\n").expect("a block after the restore");
2430 assert!(next.contains("jump block1("), "{body}");
2431 }
2432
2433 #[test]
2434 fn how_long_one_of_those_is_was_decided_where_it_was_declared_and_not_where_it_is_asked() {
2435 let source = "\
2438unsigned long f(int n) {
2439 int a[n];
2440 n = 0;
2441 return sizeof a;
2442}
2443";
2444 let body = body(source);
2445 assert_eq!(body.matches("sext.i64 %0").count(), 2, "{body}");
2447 }
2448
2449 #[test]
2450 fn a_block_in_the_middle_of_an_expression_is_walked_where_the_expression_is() {
2451 let source = "\
2454int use(int);
2455int f(int x) {
2456 return ({
2457 int t = use(x);
2458 t * t;
2459 });
2460}
2461";
2462 let expected = "\
2463block0(%0: i32):
2464 %1 = call @use(%0) : (i32) -> i32
2465 %2 = mul.nsw %1, %1
2466 return %2
2467";
2468 assert_eq!(body(source), expected);
2469 }
2470
2471 #[test]
2472 fn one_of_those_that_control_never_leaves_is_lowered_and_what_follows_it_is_dropped() {
2473 let source = "int f(int x) { return ({ return x; 0; }); }\n";
2477 assert_eq!(body(source), "block0(%0: i32):\n return %0\n");
2478 }
2479
2480 #[test]
2481 fn one_argument_off_a_variable_argument_list_stays_an_intrinsic() {
2482 let source = "double f(__builtin_va_list ap) { return __builtin_va_arg(ap, double) + __builtin_va_arg(ap, double); }\n";
2486 let expected = "\
2487block0(%0: ptr):
2488 %1 = va_arg.f64 %0
2489 %2 = va_arg.f64 %0
2490 %3 = fadd %1, %2
2491 return %3
2492";
2493 assert_eq!(body(source), expected);
2494 }
2495
2496 #[test]
2497 fn one_that_reads_a_structure_answers_where_the_object_is() {
2498 let source = "\
2505struct s { int a; long b; };
2506long f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.b; }
2507";
2508 let expected = "\
2509block0(%0: ptr):
2510 %1 = alloca, size 16, align 8
2511 %2 = va_object %0, size 16, align 8
2512 memcpy %1, %2, size 16, align 8
2513 %3 = iconst.i64 8
2514 %4 = ptr_add %1, %3
2515 %5 = load.i64 %4, align 8
2516 return %5
2517";
2518 assert_eq!(body(source), expected);
2519 }
2520
2521 #[test]
2522 fn a_jump_to_an_address_branches_to_every_label_the_function_takes_the_address_of() {
2523 let source = "\
2527int f(int c) {
2528 void *p = c ? &&one : &&two;
2529 goto *p;
2530one:
2531 return 1;
2532two:
2533 return 2;
2534}
2535";
2536 let expected = "\
2537block0(%0: i32):
2538 %1 = iconst.i32 0
2539 %2 = icmp ne %0, %1
2540 br_if %2, block1, block2
2541
2542block1:
2543 %3 = block_addr block3
2544 jump block4(%3)
2545
2546block2:
2547 %4 = block_addr block5
2548 jump block4(%4)
2549
2550block3:
2551 %5 = iconst.i32 1
2552 return %5
2553
2554block4(%6: ptr):
2555 indirect_br %6, block3, block5
2556
2557block5:
2558 %7 = iconst.i32 2
2559 return %7
2560";
2561 assert_eq!(body(source), expected);
2562 }
2563
2564 #[test]
2565 fn a_jump_to_an_address_no_label_in_the_function_has_arrives_nowhere() {
2566 let source = "void **next(void);
2569void f(void) { goto *next(); }
2570";
2571 let expected = "\
2572block0:
2573 %0 = call @next() : () -> ptr
2574 unreachable
2575";
2576 assert_eq!(body(source), expected);
2577 }
2578
2579 #[test]
2580 fn an_asm_with_no_operands_is_volatile_and_the_clobbers_are_the_whole_of_what_it_says() {
2581 let source = "void f(void) { __asm__(\"mfence\" ::: \"memory\"); }\n";
2584 let expected = "\
2585block0:
2586 inline_asm.volatile \"mfence\", \"\", \"memory\"()
2587 return
2588";
2589 assert_eq!(body(source), expected);
2590 }
2591
2592 #[test]
2593 fn the_constraints_are_one_list_in_the_order_the_template_counts_the_operands() {
2594 let source = "\
2597int f(int x, int y) {
2598 int r;
2599 __asm__(\"addl %2, %0\" : \"=r\"(r), \"+r\"(y) : \"r\"(x));
2600 return r + y;
2601}
2602";
2603 let expected = "\
2604block0(%0: i32, %1: i32):
2605 %2, %3 = inline_asm.(i32, i32) \"addl %2, %0\", \"=r,+r,r\", \"\"(%1, %0)
2606 %4 = add.nsw %2, %3
2607 return %4
2608";
2609 assert_eq!(body(source), expected);
2610 }
2611
2612 #[test]
2613 fn a_memory_operand_travels_as_the_address_of_an_object_that_is_given_a_slot() {
2614 let source = "\
2619struct pair { int a, b; };
2620int f(int x) {
2621 int slot = x;
2622 struct pair p = { x, x };
2623 __asm__(\"incl %0\" : \"+m\"(slot), \"=m\"(p));
2624 return slot + p.a;
2625}
2626";
2627 let text = body(source);
2628 assert!(text.contains("inline_asm \"incl %0\", \"+m,=m\", \"\"(%1, %2)\n"), "{text}");
2629 assert!(text.contains("%1 = alloca, size 4, align 4\n"), "{text}");
2630 assert!(text.contains("%2 = alloca, size 8, align 4\n"), "{text}");
2631 }
2632
2633 #[test]
2634 fn an_asm_goto_falls_through_to_its_first_target_and_writes_its_outputs_there() {
2635 let source = "\
2640int f(int x) {
2641 int r = 7;
2642 __asm__ goto(\"cbnz %0, %l1\" : \"=r\"(r) : \"r\"(x) :: away);
2643 return r;
2644away:
2645 return r;
2646}
2647";
2648 let expected = "\
2649block0(%0: i32):
2650 %1 = iconst.i32 7
2651 %2 = inline_asm.volatile \"cbnz %0, %l1\", \"=r,r\", \"\"(%0), labels [block1, block2]
2652
2653block1:
2654 return %2
2655
2656block2:
2657 return %1
2658";
2659 assert_eq!(body(source), expected);
2660 }
2661
2662 #[test]
2663 fn an_asm_statement_that_is_not_well_formed_is_reported_in_the_words_gcc_uses() {
2664 let mut opts = options();
2668 opts.emit = EmitKind::Ir;
2669 for (source, expected) in [
2670 (
2671 "void f(int x) { __asm__(\"\" : \"r\"(x)); }\n",
2672 "output operand constraint lacks '='",
2673 ),
2674 (
2675 "void f(int x) { __asm__(\"\" : \"=r\"(x + 1)); }\n",
2676 "lvalue required in 'asm' statement",
2677 ),
2678 (
2679 "const int g = 1;\nvoid f(void) { __asm__(\"\" : \"=r\"(g)); }\n",
2680 "read-only variable 'g' used as 'asm' output",
2681 ),
2682 (
2683 "void f(int x) { __asm__(\"\" : : \"=r\"(x)); }\n",
2684 "input operand constraint contains '='",
2685 ),
2686 (
2687 "void f(void) { __asm__(\"\" : : \"m\"(1)); }\n",
2688 "memory input 0 is not directly addressable",
2689 ),
2690 ("void f(void) { __asm__(L\"\"); }\n", "wide string literal in 'asm'"),
2691 (
2692 "void f(int x, int y) { __asm__(\"\" : [a] \"=r\"(x) : [a] \"r\"(y)); }\n",
2693 "duplicate asm operand name 'a'",
2694 ),
2695 ("void f(int x) { __asm__(\"%[in]\" : \"=r\"(x)); }\n", "undefined named operand 'in'"),
2696 ] {
2697 let result = run(&opts, source);
2698 assert!(result.failed(), "expected this to be reported:\n{source}");
2699 assert!(
2700 result.messages.iter().any(|m| m.contains(expected)),
2701 "{expected}\n{:?}",
2702 result.messages
2703 );
2704 }
2705 }
2706
2707 #[test]
2708 fn what_the_walk_cannot_build_yet_is_reported_rather_than_mislowered() {
2709 let mut opts = options();
2710 opts.emit = EmitKind::Ir;
2711 for source in [
2712 "int f(int n) { void *p = &&out; if (n) goto *p; { int a[n]; out: return 1; } }\n",
2713 "int f(int n) { int a[n]; __asm__ goto(\"\" ::::out); out: return a[0]; }\n",
2714 ] {
2715 let result = run(&opts, source);
2716 assert!(result.failed(), "expected this to be reported:\n{source}");
2717 assert!(
2718 result.messages.iter().any(|m| m.contains("not supported yet")),
2719 "{:?}",
2720 result.messages
2721 );
2722 }
2723 }
2724
2725 fn round_trip(source: &str) -> (String, String) {
2727 let printed = ir(source);
2728 let mut opts = options();
2729 opts.emit = EmitKind::Ir;
2730 let mut fs = MemoryFileSystem::new();
2731 fs.insert("/main.ir", printed.clone().into_bytes());
2732 let result = compile_ir(&opts, "/main.ir", &fs);
2733 assert_eq!(result.messages, Vec::<String>::new(), "expected this to read back:\n{printed}");
2734 (printed, result.text().to_owned())
2735 }
2736
2737 #[test]
2738 fn ir_that_arrives_as_an_input_is_read_back_and_written_out_the_same() {
2739 let (printed, again) = round_trip(
2743 "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",
2744 );
2745 assert_eq!(printed, again);
2746 }
2747
2748 #[test]
2749 fn ir_that_is_not_ir_says_which_line_stopped_it() {
2750 let mut opts = options();
2751 opts.emit = EmitKind::Ir;
2752 let mut fs = MemoryFileSystem::new();
2753 let text = "\
2754; ModuleID = 'a.c'
2755; format 0
2756target triple = \"x86_64-unknown-linux-gnu\"
2757target datalayout = \"e-p:64:64-i64:64-S128\"
2758
2759func @f(), linkage(external) {
2760block0:
2761 frobnicate
2762}
2763";
2764 fs.insert("/main.ir", text.as_bytes().to_vec());
2765 let result = compile_ir(&opts, "/main.ir", &fs);
2766 assert!(result.failed());
2767 assert!(result.messages[0].contains("/main.ir:8"), "{:?}", result.messages);
2768 }
2769
2770 #[test]
2771 fn ir_that_reads_but_does_not_hold_together_is_reported_by_the_verifier() {
2772 let mut opts = options();
2775 opts.emit = EmitKind::Ir;
2776 let mut fs = MemoryFileSystem::new();
2777 let text = "\
2778; ModuleID = 'a.c'
2779; format 0
2780target triple = \"x86_64-unknown-linux-gnu\"
2781target datalayout = \"e-p:64:64-i64:64-S128\"
2782
2783func @f(), linkage(external) {
2784block0:
2785 %0 = iconst.i32 1
2786 return %0
2787}
2788";
2789 fs.insert("/main.ir", text.as_bytes().to_vec());
2790 let result = compile_ir(&opts, "/main.ir", &fs);
2791 assert!(result.failed());
2792 assert!(result.messages[0].contains("invalid IR"), "{:?}", result.messages);
2793 }
2794
2795 #[test]
2796 fn a_typed_tree_is_not_something_an_input_of_ir_can_produce() {
2797 let mut fs = MemoryFileSystem::new();
2799 fs.insert("/main.ir", Vec::new());
2800 let result = compile_ir(&options(), "/main.ir", &fs);
2801 assert!(result.failed());
2802 assert!(result.messages[0].contains("can only be emitted as IR"), "{:?}", result.messages);
2803 }
2804
2805 #[test]
2806 fn the_printed_ir_reads_back_as_the_same_module() {
2807 let text = ir("\
2810struct point { int x, y; };
2811static const char greeting[] = \"hi\";
2812int table[4] = { 1, 2, 3 };
2813int puts(const char *);
2814double half(double x) { return x / 2.0; }
2815int f(int n) {
2816 int total = 0;
2817 for (int i = 0; i < n; i++) {
2818 if (i == 3) continue;
2819 total += table[i];
2820 }
2821 switch (n) {
2822 case 0: total = 1;
2823 case 1: total++; break;
2824 default: total = -total;
2825 }
2826 struct point p = { total, 1 };
2827 int *q = &p.y;
2828 puts(greeting);
2829 return p.x + *q;
2830}
2831int dispatch(int c) {
2832 void *p = c ? &&one : &&two;
2833 goto *p;
2834one:
2835 return 1;
2836two:
2837 return 2;
2838}
2839int assembly(int x, int *p) {
2840 int r;
2841 __asm__ volatile(\"xadd %0, %2\" : \"=r\"(r), \"+m\"(*p) : \"0\"(x) : \"cc\");
2842 __asm__ goto(\"cbnz %0, %l1\" : : \"r\"(r) : : away);
2843 return r;
2844away:
2845 return 0;
2846}
2847");
2848 let mut names = Interner::new();
2849 let module = rucc_ir::parse(&text, &mut names).expect("the printer writes what it reads");
2850 assert_eq!(rucc_ir::print(&module, &names), text);
2851 }
2852}