1use std::path::Path;
14
15use rucc_base::Interner;
16use rucc_codegen::coverage::Fired;
17use rucc_codegen::elsewhere::Elsewhere;
18use rucc_codegen::pipeline::{self, Machine};
19use rucc_diag::{Diagnostic, Severity, Span};
20use rucc_ir::{Pic as IrPic, Visibility as IrVisibility};
21use rucc_lex::{Convert, Keywords, PpToken, convert};
22use rucc_sema::{Checker, Context as CheckContext};
23use rucc_session::{EmitKind, FileSystem, Options, Pic, Session, Visibility};
24use rucc_target::TargetInfo;
25use rucc_tuple::ObjectFormat;
26
27use crate::preprocess::render;
28
29#[derive(Debug, Clone, PartialEq, Eq, Default)]
36pub enum Artifact {
37 #[default]
40 Nothing,
41 Text(String),
43 Object(Vec<u8>),
45}
46
47impl Artifact {
48 #[must_use]
50 pub fn bytes(&self) -> &[u8] {
51 match self {
52 Artifact::Nothing => &[],
53 Artifact::Text(text) => text.as_bytes(),
54 Artifact::Object(bytes) => bytes,
55 }
56 }
57}
58
59#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct Compiled {
62 pub artifact: Artifact,
64 pub messages: Vec<String>,
66 pub errors: u32,
68 pub fired: Fired,
74 pub dumps: Vec<rucc_opt::Dump>,
80 pub remarks: String,
86 pub deps: Vec<rucc_pp::Dependency>,
91 pub temps: Temps,
98}
99
100#[derive(Debug, Clone, PartialEq, Eq, Default)]
107pub struct Temps {
108 pub preprocessed: Option<String>,
110 pub assembly: Option<String>,
112}
113
114impl Compiled {
115 #[must_use]
117 pub fn failed(&self) -> bool {
118 self.errors > 0
119 }
120
121 #[must_use]
126 pub fn text(&self) -> &str {
127 match &self.artifact {
128 Artifact::Text(text) => text,
129 _ => "",
130 }
131 }
132}
133
134#[must_use]
147pub fn compile(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
148 let mut sess = Session::new(opts.clone());
149 let keywords = Keywords::new(&mut sess.interner, opts.std, opts.gnu_extensions);
153 let mut diagnostics: Vec<Diagnostic> = Vec::new();
154 let mut fired = Fired::new();
156 let mut dumps = Vec::new();
158 let mut remarks = String::new();
159 let mut temps = Temps::default();
161
162 let bytes = match fs.read(Path::new(name)) {
163 Ok(bytes) => bytes,
164 Err(e) => return failure(format!("{name}: {e}")),
165 };
166 let Ok(file) = sess.sources.add_shared(name, bytes, None) else {
167 return failure(format!("{name}: the source map has no room left for this file"));
168 };
169
170 let mut pp = rucc_pp::Preprocessor::new();
174 let predef = rucc_pp::Predef::for_options(opts);
175 let expanded: Vec<PpToken> = {
176 let mut tokens = Vec::new();
177 {
182 let mut cx =
183 rucc_pp::Context::new(&mut sess.interner, &mut sess.sources, fs, &opts.search);
184 cx.lex = rucc_lex::Options::for_dialect(opts.std, opts.gnu_extensions);
185 if pp.predefine(&sess.target, &predef, &mut cx).is_err() {
186 return failure(format!(
187 "{name}: the source map has no room for the built in macros"
188 ));
189 }
190 if pp.preinclude(&opts.preincludes, &mut tokens, &mut cx).is_err() {
191 return failure(format!("{name}: the source map has no room for the command line"));
192 }
193 tokens.append(&mut pp.run(file, &mut cx));
194 }
195 if opts.save_temps.wanted() {
196 temps.preprocessed = Some(rucc_pp::print(
197 file,
198 &tokens,
199 pp.line_directives(),
200 &sess.sources,
201 &sess.interner,
202 rucc_pp::PrintOptions { line_markers: opts.line_markers },
203 ));
204 }
205 tokens.iter().map(|token| token.to_pp()).collect()
206 };
207 diagnostics.extend(pp.take_diagnostics());
208 let deps = pp.dependencies().to_vec();
211
212 let cx = Convert {
215 keywords: &keywords,
216 interner: &sess.interner,
217 target: &sess.target,
218 std: opts.std,
219 gnu: opts.gnu_extensions,
220 pedantic: opts.pedantic,
221 };
222 let (tokens, complaints) = convert(&expanded, &cx);
223 diagnostics.extend(complaints);
224
225 let parsed = rucc_parse::parse(
226 &tokens,
227 rucc_parse::Context {
228 interner: &sess.interner,
229 std: opts.std,
230 gnu: opts.gnu_extensions,
231 pedantic: opts.pedantic,
232 error_limit: opts.error_limit as usize,
233 },
234 );
235 let parse_failed = parsed.diagnostics.iter().any(|d| d.severity.is_fatal());
236 diagnostics.extend(parsed.diagnostics);
237
238 let mut artifact = Artifact::Nothing;
239 let mut instrumented = Instrumented::default();
242 if !parse_failed {
243 let mut checker = Checker::new(
244 &parsed.ast,
245 CheckContext {
246 names: &sess.interner,
247 target: &sess.target,
248 std: opts.std,
249 gnu: opts.gnu_extensions,
250 pedantic: opts.pedantic,
251 permissive: opts.permissive,
252 gnu89_inline: opts.gnu89_inline,
253 error_limit: opts.error_limit as usize,
254 builtins: opts.builtins && opts.hosted,
257 no_builtin: &opts.no_builtin,
258 },
259 );
260 checker.check_unit();
261 let checked = checker.finish();
262 if !checked.failed() {
263 match opts.emit {
264 EmitKind::Tast => {
265 artifact = Artifact::Text(rucc_sema::print(
266 &checked.tast,
267 &checked.types,
268 &sess.interner,
269 ));
270 }
271 EmitKind::TypeGranules => {
275 artifact = Artifact::Text(rucc_types::granule_report(
276 &checked.types,
277 &sess.interner,
278 &sess.target,
279 ));
280 }
281 EmitKind::Ir
282 | EmitKind::MirFinal
283 | EmitKind::Asm
284 | EmitKind::Object
285 | EmitKind::Executable
286 | EmitKind::SafetySummary => {
287 let mut lowered = rucc_lower::lower(
288 name,
289 rucc_lower::Context {
290 tast: &checked.tast,
291 types: &checked.types,
292 target: &sess.target,
293 names: &mut sess.interner,
294 visibility: match opts.visibility {
295 Visibility::Default => IrVisibility::Default,
296 Visibility::Hidden => IrVisibility::Hidden,
297 Visibility::Protected => IrVisibility::Protected,
298 },
299 },
300 );
301 let failed = lowered.diagnostics.iter().any(|d| d.severity.is_fatal());
305 if !failed {
306 if let Err(errors) = rucc_ir::verify(&lowered.module, &sess.interner) {
311 for error in errors {
312 diagnostics.push(internal(&format!("invalid IR, {error}")));
313 }
314 } else if let Err(complaints) =
315 instrument(&mut lowered.module, &mut sess.interner, opts)
316 .map(|done| instrumented = done)
317 {
318 diagnostics.extend(complaints);
319 } else if let Err(complaints) = optimize(
320 &mut lowered.module,
321 &sess.interner,
322 &sess.target,
323 opts,
324 name,
325 &mut dumps,
326 &mut remarks,
327 ) {
328 diagnostics.extend(complaints);
329 } else if opts.emit == EmitKind::SafetySummary {
330 artifact = Artifact::Text(
335 rucc_safety::summarize(
336 &lowered.module,
337 &sess.interner,
338 name,
339 opts.safety.as_str(),
340 instrumented.checks,
341 instrumented.interposed,
342 instrumented.crossings,
343 )
344 .render(),
345 );
346 } else if opts.emit == EmitKind::Ir {
347 artifact =
352 Artifact::Text(rucc_ir::print(&lowered.module, &sess.interner));
353 } else {
354 match generate(
357 &mut lowered.module,
358 &mut sess.interner,
359 &sess.target,
360 opts,
361 &mut fired,
362 &mut temps.assembly,
363 ) {
364 Ok(made) => artifact = made,
365 Err(complaints) => diagnostics.extend(complaints),
366 }
367 }
368 }
369 diagnostics.extend(lowered.diagnostics);
370 }
371 _ => {}
372 }
373 }
374 diagnostics.extend(checked.diagnostics);
375 }
376
377 let mut messages = Vec::with_capacity(diagnostics.len());
378 let mut errors = 0;
379 for diag in &diagnostics {
380 if !opts.warnings && diag.severity == Severity::Warning {
384 continue;
385 }
386 if diag.severity.is_fatal()
387 || (diag.severity == Severity::Warning && opts.warnings_are_errors)
388 {
389 errors += 1;
390 }
391 messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
392 }
393 if errors > 0 {
394 artifact = Artifact::Nothing;
396 }
397 Compiled { artifact, messages, errors, fired, dumps, remarks, deps, temps }
400}
401
402#[must_use]
412pub fn compile_ir(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
413 let mut sess = Session::new(opts.clone());
414 if opts.emit != EmitKind::Ir {
415 return failure(format!(
416 "{name}: an input of IR can only be emitted as IR, and `--emit={}` asks for what \
417 the C in front of it became",
418 opts.emit.as_str()
419 ));
420 }
421 let bytes = match fs.read(Path::new(name)) {
422 Ok(bytes) => bytes,
423 Err(e) => return failure(format!("{name}: {e}")),
424 };
425 let Ok(text) = std::str::from_utf8(bytes.as_slice()) else {
426 return failure(format!("{name}: this is not text, so it is not IR"));
427 };
428
429 let module = match rucc_ir::parse(text, &mut sess.interner) {
430 Ok(module) => module,
431 Err(error) => {
432 return failure(format!("{name}:{}: {}", error.line, error.message));
433 }
434 };
435 let mut diagnostics: Vec<Diagnostic> = Vec::new();
436 if let Err(errors) = rucc_ir::verify(&module, &sess.interner) {
437 for error in errors {
438 diagnostics.push(invalid(&format!("invalid IR, {error}")));
439 }
440 }
441 let mut messages = Vec::with_capacity(diagnostics.len());
442 for diag in &diagnostics {
443 messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
444 }
445 let errors = u32::try_from(messages.len()).unwrap_or(u32::MAX);
446 let artifact = if errors > 0 {
447 Artifact::Nothing
448 } else {
449 Artifact::Text(rucc_ir::print(&module, &sess.interner))
450 };
451 Compiled {
453 artifact,
454 messages,
455 errors,
456 fired: Fired::new(),
457 dumps: Vec::new(),
458 remarks: String::new(),
459 deps: Vec::new(),
460 temps: Temps::default(),
461 }
462}
463
464fn instrument(
487 module: &mut rucc_ir::Module,
488 names: &mut Interner,
489 opts: &Options,
490) -> Result<Instrumented, Vec<Diagnostic>> {
491 if !opts.safety.instruments() {
492 return Ok(Instrumented::default());
493 }
494 let checks = rucc_safety::run(module);
495 let interposed = rucc_safety::redirect(module, names);
500 let crossings = rucc_safety::witness(module, names);
503 match rucc_ir::verify(module, names) {
504 Ok(()) => Ok(Instrumented { checks, interposed, crossings }),
505 Err(errors) => Err(errors
506 .iter()
507 .map(|e| internal(&format!("invalid IR after check insertion, {e}")))
508 .collect()),
509 }
510}
511
512#[derive(Clone, Copy, Debug, Default)]
518struct Instrumented {
519 checks: rucc_safety::Counts,
521 interposed: usize,
523 crossings: rucc_safety::Sites,
525}
526
527fn optimize(
539 module: &mut rucc_ir::Module,
540 names: &Interner,
541 target: &TargetInfo,
542 opts: &Options,
543 file: &str,
544 dumps: &mut Vec<rucc_opt::Dump>,
545 remarks: &mut String,
546) -> Result<(), Vec<Diagnostic>> {
547 let mut settings = rucc_opt::Options::for_level(opts.opt_level);
548 settings.interposition = match opts.interposition {
554 true => replaceable(target, opts),
555 false => IrPic::Executable,
556 };
557 settings.toggles.clone_from(&opts.passes);
558 settings.fuel = opts.pass_fuel.iter().cloned().collect();
559 settings.global_fuel = opts.pass_fuel_global;
560 settings.verify |= opts.verify_each;
561 for (on, spec) in &opts.pass_gates {
562 if let Err(why) = settings.gates.add(*on, spec) {
565 return Err(vec![internal(&why)]);
566 }
567 }
568 for spec in &opts.dump_ir {
569 if let Err(why) = settings.dumps.add(spec) {
572 return Err(vec![internal(&why)]);
573 }
574 }
575 let mut wants = rucc_opt::Wants::none();
576 for spec in &opts.opt_info {
577 if let Err(why) = wants.add(spec) {
580 return Err(vec![internal(&why)]);
581 }
582 }
583 let report = rucc_opt::run(module, names, &settings);
584 remarks.push_str(&rucc_opt::optinfo::render(file, &report, names, wants));
585 dumps.extend(report.dumps);
586 match report.broke.is_empty() {
587 true => Ok(()),
588 false => Err(report.broke.iter().map(|why| internal(why)).collect()),
589 }
590}
591
592fn replaceable(target: &TargetInfo, opts: &Options) -> IrPic {
626 match (target.tuple.os().object_format(), opts.pic) {
627 (Some(ObjectFormat::Elf), Pic::Library) => IrPic::Library,
628 _ => IrPic::Executable,
629 }
630}
631
632fn generate(
633 module: &mut rucc_ir::Module,
634 names: &mut Interner,
635 target: &TargetInfo,
636 opts: &Options,
637 fired: &mut Fired,
638 assembly: &mut Option<String>,
639) -> Result<Artifact, Vec<Diagnostic>> {
640 let Some(machine) = Machine::for_target(target) else {
641 return Err(vec![unsupported(&format!(
642 "there is no back end for {} in this compiler yet, so there is nothing to generate",
643 target.tuple
644 ))]);
645 };
646 let flags = pipeline::Flags { frame_pointer: opts.frame_pointer, red_zone: opts.red_zone };
647
648 if opts.safety.instruments() {
657 rucc_safety::lower(module, names);
658 if let Err(errors) = rucc_ir::verify(module, names) {
659 return Err(errors
660 .iter()
661 .map(|e| internal(&format!("invalid IR after check lowering, {e}")))
662 .collect());
663 }
664 }
665
666 let elsewhere = Elsewhere::of(module, replaceable(target, opts));
674
675 let mut funcs = Vec::new();
676 let mut complaints = Vec::new();
677 for id in module.funcs() {
678 if module[id].is_declaration() {
679 continue;
680 }
681 match pipeline::compile_recording(
682 &mut module[id],
683 names,
684 &machine,
685 &elsewhere,
686 flags,
687 fired,
688 ) {
689 Ok(func) => funcs.push(func),
690 Err(why) => {
691 let name = names.resolve(module[id].name).to_owned();
692 let span = why.inst().map_or(Span::DUMMY, |inst| module[id].span(inst));
695 let said = format!("cannot generate code for '{name}': {why}");
696 complaints.push(unsupported_at(&said, span));
697 }
698 }
699 }
700 if !complaints.is_empty() {
701 return Err(complaints);
702 }
703 let (globals, aliases) = match opts.emit {
709 EmitKind::Asm | EmitKind::Object | EmitKind::Executable => (
710 rucc_asm::globals(module, names).map_err(refused)?,
711 rucc_asm::aliases(module, names).map_err(refused)?,
712 ),
713 _ => (rucc_asm::Globals::default(), Vec::new()),
714 };
715 let unwind = opts.unwinds();
719 match opts.emit {
720 EmitKind::Asm => {
721 rucc_asm::print(&funcs, &globals, &aliases, names, target, unwind, sections(opts))
722 .map(Artifact::Text)
723 .map_err(refused)
724 }
725 EmitKind::Object | EmitKind::Executable => {
728 if opts.save_temps.wanted() {
729 let listing = rucc_asm::print(
730 &funcs,
731 &globals,
732 &aliases,
733 names,
734 target,
735 unwind,
736 sections(opts),
737 );
738 *assembly = Some(listing.map_err(refused)?);
739 }
740 let text = rucc_asm::assemble(&funcs, names, target, unwind).map_err(refused)?;
741 let data = globals.image();
742 rucc_object::write(&text, &data, &aliases, target, sections(opts))
745 .map(Artifact::Object)
746 .map_err(|why| match why {
747 rucc_object::Error::Format { .. } => vec![unsupported(&why.to_string())],
748 rucc_object::Error::Refused { .. } => vec![internal(&why.to_string())],
749 })
750 }
751 _ => Ok(Artifact::Text(rucc_mir::print(&funcs, names, target.regs))),
752 }
753}
754
755fn sections(opts: &Options) -> rucc_object::Sections {
762 rucc_object::Sections { functions: opts.function_sections, data: opts.data_sections }
763}
764
765fn refused(why: rucc_asm::Error) -> Vec<Diagnostic> {
771 match why {
772 rucc_asm::Error::Thread { .. } | rucc_asm::Error::IFunc { .. } => {
773 vec![unsupported(&why.to_string())]
774 }
775 _ => vec![internal(&why.to_string())],
776 }
777}
778
779fn unsupported(message: &str) -> Diagnostic {
785 unsupported_at(message, Span::DUMMY)
786}
787
788fn unsupported_at(message: &str, span: Span) -> Diagnostic {
794 Diagnostic::error(message.to_owned(), span)
795 .with_code("E0653")
796 .note("this construct is not lowered yet, see https://github.com/tamnd/rucc/issues", span)
797}
798
799fn invalid(message: &str) -> Diagnostic {
801 Diagnostic::error(message.to_owned(), Span::DUMMY).with_code("E0661")
802}
803
804fn internal(message: &str) -> Diagnostic {
806 Diagnostic::error(format!("internal error: {message}"), Span::DUMMY)
807 .with_code("E0652")
808 .note("this is a bug in rucc rather than in the program, please report it", Span::DUMMY)
809}
810
811fn failure(message: String) -> Compiled {
814 Compiled {
815 artifact: Artifact::Nothing,
816 messages: vec![format!("rucc: error: {message}")],
817 errors: 1,
818 fired: Fired::new(),
819 dumps: Vec::new(),
820 remarks: String::new(),
821 deps: Vec::new(),
822 temps: Temps::default(),
823 }
824}
825
826#[cfg(test)]
827mod tests {
828 use rucc_session::{MemoryFileSystem, Std};
829 use rucc_target::Triple;
830
831 use super::*;
832
833 fn options() -> Options {
834 let mut opts = Options::new("x86_64-unknown-linux-gnu".parse::<Triple>().unwrap());
835 opts.emit = EmitKind::Tast;
836 opts
837 }
838
839 fn run(opts: &Options, source: &str) -> Compiled {
840 let mut fs = MemoryFileSystem::new();
841 fs.insert("/main.c", source.to_owned().into_bytes());
842 compile(opts, "/main.c", &fs)
843 }
844
845 fn freestanding() -> Options {
849 let mut opts = options();
850 opts.hosted = false;
851 opts.search.push_system(rucc_session::runtime::DIR);
852 opts
853 }
854
855 fn shipped(source: &str) -> String {
857 let result = run(&freestanding(), source);
858 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
859 result.text().to_owned()
860 }
861
862 fn tast(source: &str) -> String {
864 let result = run(&options(), source);
865 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
866 result.text().to_owned()
867 }
868
869 #[test]
870 fn the_shipped_stdarg_declares_a_list_and_the_four_operators() {
871 let text = shipped(concat!(
872 "#include <stdarg.h>\n",
873 "int sum(int n, ...) {\n",
874 " va_list ap, copy;\n",
875 " va_start(ap, n);\n",
876 " va_copy(copy, ap);\n",
877 " int total = va_arg(ap, int) + va_arg(copy, int);\n",
878 " va_end(ap);\n",
879 " va_end(copy);\n",
880 " return total;\n",
881 "}\n",
882 ));
883 assert!(text.contains("va-start"), "{text}");
884 assert!(text.contains("va-copy"), "{text}");
885 assert!(text.contains("va-arg"), "{text}");
886 assert!(text.contains("va-end"), "{text}");
887 }
888
889 #[test]
893 fn stdarg_hands_out_the_type_alone_when_that_is_all_that_was_asked_for() {
894 let text = shipped(concat!(
895 "#define __need___va_list\n",
896 "#include <stdarg.h>\n",
897 "int vprint(const char *f, __gnuc_va_list ap);\n",
898 "#ifdef va_start\n",
899 "#error va_start should not be defined\n",
900 "#endif\n",
901 "#ifdef _VA_LIST_DEFINED\n",
902 "#error va_list should not have been made\n",
903 "#endif\n",
904 ));
905 assert!(text.contains("vprint"), "{text}");
906 }
907
908 #[test]
911 fn stddef_answers_one_piece_at_a_time_and_the_next_request_still_gets_through() {
912 let text = shipped(concat!(
913 "#define __need_size_t\n",
914 "#include <stddef.h>\n",
915 "#ifdef offsetof\n",
916 "#error offsetof should not be defined yet\n",
917 "#endif\n",
918 "#define __need_ptrdiff_t\n",
919 "#include <stddef.h>\n",
920 "#include <stddef.h>\n",
921 "size_t a;\n",
922 "ptrdiff_t b;\n",
923 "wchar_t c;\n",
924 "max_align_t d;\n",
925 "void *e = NULL;\n",
926 "struct P { int x; long y; };\n",
927 "size_t f = offsetof(struct P, y);\n",
928 ));
929 assert!(text.contains("decl #0 a : unsigned long"), "{text}");
930 assert!(text.contains("decl #1 b : long"), "{text}");
931 }
932
933 #[test]
934 fn the_shipped_limits_and_float_are_the_targets_own_answers() {
935 let text = shipped(concat!(
936 "#include <limits.h>\n",
937 "#include <float.h>\n",
938 "int bits = CHAR_BIT;\n",
939 "long big = LONG_MAX;\n",
940 "int low = INT_MIN;\n",
941 "int radix = FLT_RADIX;\n",
942 "int digits = DBL_MANT_DIG;\n",
943 ));
944 assert!(text.contains("const 8 : int"), "{text}");
945 assert!(text.contains("const 9223372036854775807 : long"), "{text}");
946 assert!(text.contains("const 2 : int"), "{text}");
947 assert!(text.contains("const 53 : int"), "{text}");
948 }
949
950 #[test]
954 fn the_shipped_stdint_writes_the_whole_set_when_there_is_no_library_to_defer_to() {
955 let text = shipped(concat!(
956 "#include <stdint.h>\n",
957 "int64_t a = INT64_C(1);\n",
958 "uint_least16_t b;\n",
959 "intptr_t c;\n",
960 "uintmax_t d = UINTMAX_MAX;\n",
961 "int wide = sizeof(int_fast64_t);\n",
962 ));
963 assert!(text.contains("decl #0 a : long"), "{text}");
964 assert!(text.contains("decl #1 b : unsigned short"), "{text}");
965 assert!(text.contains("decl #2 c : long"), "{text}");
966 }
967
968 #[test]
969 fn the_three_formality_headers_still_have_to_work() {
970 let text = shipped(concat!(
971 "#include <stdbool.h>\n",
972 "#include <stdalign.h>\n",
973 "#include <iso646.h>\n",
974 "#include <stdnoreturn.h>\n",
975 "int t = true and not false;\n",
976 "_Alignas(16) char buf[16];\n",
977 "int a = alignof(long);\n",
978 ));
979 assert!(text.contains("decl #0 t : int"), "{text}");
980 assert!(text.contains("const 8 : unsigned long"), "{text}");
981 }
982
983 #[test]
986 fn every_shipped_header_can_be_included_twice() {
987 let mut source = String::new();
988 for _ in 0..2 {
989 for name in rucc_session::runtime::names() {
990 source.push_str(&format!("#include <{name}>\n"));
991 }
992 }
993 source.push_str("int x;\n");
994 let text = shipped(&source);
995 assert!(text.starts_with("decl #0 x : int"), "{text}");
996 }
997
998 #[test]
999 fn a_file_that_is_not_there_says_so_and_produces_nothing() {
1000 let fs = MemoryFileSystem::new();
1001 let result = compile(&options(), "/nope.c", &fs);
1002 assert!(result.failed());
1003 assert!(result.messages[0].contains("/nope.c"), "{:?}", result.messages);
1004 assert!(result.text().is_empty());
1005 }
1006
1007 #[test]
1008 fn an_object_comes_out_with_its_type_its_linkage_and_how_much_of_a_definition_it_is() {
1009 let text = tast("int x = 1;\n");
1010 let expected = "\
1011decl #0 x : int object external static defined
1012 init
1013 +0
1014 const 1 : int
1015";
1016 assert_eq!(text, expected);
1017 }
1018
1019 #[test]
1020 fn the_macros_are_expanded_before_anything_is_parsed() {
1021 let text = tast("#define N 2\nint a[N];\n");
1025 assert!(text.starts_with("decl #0 a : int[2] object external static tentative"), "{text}");
1026 }
1027
1028 #[test]
1034 fn a_pragma_is_not_a_declaration_and_the_parse_walks_past_the_ones_it_does_not_read() {
1035 let text = tast(concat!(
1036 "#pragma pack(4)\n",
1037 "struct s { int a; };\n",
1038 "#pragma pack()\n",
1039 "int b;\n",
1040 "_Pragma(\"GCC visibility push(default)\") int c;\n",
1041 ));
1042 assert!(text.contains("decl #0 b : int"), "{text}");
1043 assert!(text.contains("decl #1 c : int"), "{text}");
1044 }
1045
1046 #[test]
1054 fn the_layout_attributes_move_the_members_and_the_record_the_way_gcc_lays_them_out() {
1055 tast(concat!(
1056 "struct A { char c; int i; } __attribute__((packed));\n",
1057 "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
1058 "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
1059 "struct B { char c; int i; } __attribute__((aligned));\n",
1062 "_Static_assert(sizeof(struct B) == 16 && _Alignof(struct B) == 16, \"B\");\n",
1063 "struct C { char c; int i __attribute__((packed)); };\n",
1064 "_Static_assert(sizeof(struct C) == 5 && _Alignof(struct C) == 1, \"C\");\n",
1065 "_Static_assert(__builtin_offsetof(struct C, i) == 1, \"C.i\");\n",
1066 "struct D { char c; int i; } __attribute__((packed, aligned(4)));\n",
1067 "_Static_assert(sizeof(struct D) == 8 && _Alignof(struct D) == 4, \"D\");\n",
1068 "_Static_assert(__builtin_offsetof(struct D, i) == 1, \"D.i\");\n",
1069 "struct E { char c; _Alignas(8) int i; };\n",
1070 "_Static_assert(sizeof(struct E) == 16 && _Alignof(struct E) == 8, \"E\");\n",
1071 "_Static_assert(__builtin_offsetof(struct E, i) == 8, \"E.i\");\n",
1072 "struct F { char c; int i __attribute__((aligned(8))); };\n",
1073 "_Static_assert(sizeof(struct F) == 16 && _Alignof(struct F) == 8, \"F\");\n",
1074 "struct G { char c; short s; } __attribute__((aligned(2)));\n",
1077 "_Static_assert(sizeof(struct G) == 4 && _Alignof(struct G) == 2, \"G\");\n",
1078 "struct H { char c; int i; } __attribute__((aligned(2)));\n",
1079 "_Static_assert(sizeof(struct H) == 8 && _Alignof(struct H) == 4, \"H\");\n",
1080 "struct I { [[gnu::packed]] char c; int i; };\n",
1083 "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
1084 "struct J { char c; [[gnu::packed]] int i; };\n",
1085 "_Static_assert(sizeof(struct J) == 5 && _Alignof(struct J) == 1, \"J\");\n",
1086 "struct M { char c; int i : 5; int j : 20; } __attribute__((packed));\n",
1087 "_Static_assert(sizeof(struct M) == 5 && _Alignof(struct M) == 1, \"M\");\n",
1088 "struct N { char c; long long l; } __attribute__((aligned(32)));\n",
1089 "_Static_assert(sizeof(struct N) == 32 && _Alignof(struct N) == 32, \"N\");\n",
1090 "union L { char c; int i; } __attribute__((packed));\n",
1091 "_Static_assert(sizeof(union L) == 4 && _Alignof(union L) == 1, \"L\");\n",
1092 "struct O { char c; int i; } __attribute__((__packed__));\n",
1096 "_Static_assert(sizeof(struct O) == 5 && _Alignof(struct O) == 1, \"O\");\n",
1097 "struct P { char c; int i; } __attribute__((__aligned__(8)));\n",
1098 "_Static_assert(sizeof(struct P) == 8 && _Alignof(struct P) == 8, \"P\");\n",
1099 ));
1100 }
1101
1102 #[test]
1111 fn the_aligned_attribute_on_a_declaration_raises_what_that_one_object_is_aligned_to() {
1112 tast(concat!(
1113 "int v __attribute__((aligned(64)));\n",
1114 "_Static_assert(__alignof__(v) == 64, \"v\");\n",
1115 "__attribute__((aligned(32))) int w;\n",
1118 "_Static_assert(__alignof__(w) == 32, \"w\");\n",
1119 "[[gnu::aligned(16)]] int x;\n",
1120 "_Static_assert(__alignof__(x) == 16, \"x\");\n",
1121 "int y __attribute__((aligned(2)));\n",
1124 "_Static_assert(__alignof__(y) == 4, \"y\");\n",
1125 "void f(void) { int a __attribute__((aligned(128)));\n",
1127 "_Static_assert(__alignof__(a) == 128, \"a\"); (void)a; }\n",
1128 "_Static_assert(__alignof__(int) == 4, \"int\");\n",
1131 "void g(void) __attribute__((aligned(256)));\n",
1134 "void g(void) {}\n",
1135 "_Static_assert(__alignof__(g) == 256, \"g\");\n",
1136 ));
1137 }
1138
1139 #[test]
1143 fn what_a_declaration_asked_to_be_aligned_to_is_what_the_assembler_is_told() {
1144 let text = asm(concat!(
1145 "int v __attribute__((aligned(64)));\n",
1146 "void g(void) __attribute__((aligned(256)));\n",
1147 "void g(void) {}\n",
1148 "void plain(void) {}\n",
1149 ));
1150 assert!(text.contains("\t.p2align\t6\n\t.type\tv, @object\n"), "{text}");
1151 assert!(text.contains("\t.p2align\t8, 0x90\n\t.globl\tg\n"), "{text}");
1152 assert!(text.contains("\t.p2align\t4, 0x90\n\t.globl\tplain\n"), "{text}");
1153 }
1154
1155 #[test]
1164 fn an_aligned_typedef_says_what_an_object_of_it_is_aligned_to_and_may_lower_it() {
1165 tast(concat!(
1166 "typedef int L __attribute__((aligned(2)));\n",
1167 "_Static_assert(__alignof__(L) == 2, \"L\");\n",
1168 "_Static_assert(_Alignof(L) == 2, \"L alignof\");\n",
1169 "_Static_assert(sizeof(L) == 4, \"L size\");\n",
1171 "struct T { char c; L x; };\n",
1172 "_Static_assert(sizeof(struct T) == 6, \"T\");\n",
1173 "_Static_assert(__builtin_offsetof(struct T, x) == 2, \"T.x\");\n",
1174 "typedef int H __attribute__((aligned(16)));\n",
1176 "_Static_assert(__alignof__(H) == 16, \"H\");\n",
1177 "_Static_assert(sizeof(H) == 4, \"H size\");\n",
1178 "struct U { char c; H x; };\n",
1179 "_Static_assert(sizeof(struct U) == 32, \"U\");\n",
1180 "_Static_assert(__builtin_offsetof(struct U, x) == 16, \"U.x\");\n",
1181 "typedef L M __attribute__((aligned(8)));\n",
1184 "_Static_assert(__alignof__(M) == 8, \"M\");\n",
1185 "typedef L N;\n",
1188 "_Static_assert(__alignof__(N) == 2, \"N\");\n",
1189 "_Static_assert(__alignof__(int) == 4, \"int\");\n",
1191 ));
1192 let text = asm(concat!(
1193 "typedef int L __attribute__((aligned(2)));\n",
1194 "typedef int H __attribute__((aligned(16)));\n",
1195 "L low;\n",
1196 "H high;\n",
1197 ));
1198 assert!(text.contains("\t.p2align\t1\n\t.type\tlow, @object\n"), "{text}");
1199 assert!(text.contains("\t.p2align\t4\n\t.type\thigh, @object\n"), "{text}");
1200 }
1201
1202 #[test]
1210 fn the_vector_size_attribute_builds_a_type_of_lanes_and_measures_it_in_bytes() {
1211 tast(concat!(
1212 "typedef int __attribute__((vector_size(16))) v4si;\n",
1213 "_Static_assert(sizeof(v4si) == 16 && _Alignof(v4si) == 16, \"v4si\");\n",
1214 "typedef char __attribute__((vector_size(16))) v16qi;\n",
1215 "_Static_assert(sizeof(v16qi) == 16, \"v16qi\");\n",
1216 "typedef int __attribute__((vector_size(4))) v1si;\n",
1219 "_Static_assert(sizeof(v1si) == 4, \"v1si\");\n",
1220 "typedef float __attribute__((__vector_size__(8))) v2sf;\n",
1222 "_Static_assert(sizeof(v2sf) == 8, \"v2sf\");\n",
1223 "typedef short [[gnu::vector_size(8)]] v4hi;\n",
1224 "_Static_assert(sizeof(v4hi) == 8, \"v4hi\");\n",
1225 "v4si g;\n",
1228 "_Static_assert(sizeof(g[0]) == 4, \"lane\");\n",
1229 "_Static_assert(sizeof(g + g) == 16, \"whole\");\n",
1230 "_Static_assert(sizeof(g + 1) == 16, \"broadcast\");\n",
1233 "_Static_assert(sizeof(v4si[3]) == 48, \"array\");\n",
1235 ));
1236 }
1237
1238 #[test]
1248 fn a_vector_is_written_whole_into_an_array_of_them_and_named_by_a_type_name() {
1249 tast(concat!(
1250 "typedef int __attribute__((vector_size(8))) v2si;\n",
1251 "v2si table[] = { (v2si){ 1, 2 }, (v2si){ 3, 4 } };\n",
1252 "_Static_assert(sizeof(table) == 16, \"two of them and not eight lanes\");\n",
1253 "v2si written = (int __attribute__((vector_size(8)))){ 5, 6 };\n",
1255 "_Static_assert(sizeof((int __attribute__((vector_size(16)))){ 0 }) == 16, \"named\");\n",
1256 "v2si lanes[2] = { 1, 2, 3, 4 };\n",
1259 "_Static_assert(sizeof(lanes) == 16, \"still elided\");\n",
1260 ));
1261 }
1262
1263 #[test]
1271 fn a_lane_is_assignable_and_a_shift_takes_a_count_of_its_own_lane() {
1272 let result = run(
1273 &options(),
1274 concat!(
1275 "typedef int __attribute__((vector_size(16))) v4si;\n",
1276 "typedef unsigned __attribute__((vector_size(16))) v4ui;\n",
1277 "void write(v4si *out, v4ui a, v4si b, int n) {\n",
1278 " v4si v = { 1, 2, 3, 4 };\n",
1279 " v[0] = n;\n",
1280 " v[1] += n;\n",
1281 " v[2]++;\n",
1282 " *&v[3] = n;\n",
1283 " v4ui shifted = a >> b;\n",
1285 " shifted <<= b;\n",
1286 " *out = v + (v4si)shifted + (1 << b);\n",
1289 "}\n",
1290 "void refused(const v4si c) {\n",
1293 " c[0] = 1;\n",
1294 "}\n",
1295 ),
1296 );
1297 assert_eq!(result.messages.len(), 1, "{:?}", result.messages);
1298 assert!(result.messages[0].contains("assignment of read-only"), "{:?}", result.messages);
1299 }
1300
1301 #[test]
1308 fn a_record_that_asks_for_the_other_byte_order_is_refused_rather_than_laid_out_in_this_one() {
1309 let opts = options();
1310 let big = "struct s { int i; } __attribute__((scalar_storage_order(\"big-endian\")));\n";
1311 assert_eq!(
1312 run(&opts, big).messages,
1313 ["/main.c:1:36: error: 'scalar_storage_order' is not implemented yet [E0688]\n\
1314 /main.c:1:36: note: every scalar in this record would be read in the wrong byte \
1315 order"]
1316 );
1317
1318 let armoured =
1319 "struct s { int i; } __attribute__((__scalar_storage_order__(\"little-endian\")));\n";
1320 let messages = run(&opts, armoured).messages;
1321 assert!(messages[0].contains("[E0688]"), "{messages:?}");
1322
1323 let front = "struct __attribute__((scalar_storage_order(\"big-endian\"))) s { int i; };\n";
1326 assert!(run(&opts, front).messages[0].contains("[E0688]"), "{front}");
1327 let standard = "struct s { int i; } [[gnu::scalar_storage_order(\"big-endian\")]];\n";
1328 assert!(run(&opts, standard).messages[0].contains("[E0688]"), "{standard}");
1329 }
1330
1331 #[test]
1341 fn packing_is_what_decides_whether_a_bit_field_may_straddle_its_own_storage() {
1342 assert_eq!(bit_field_byte("struct s { int x : 12; char y : 6; };"), 2);
1344 assert_eq!(
1345 bit_field_byte("struct s { int x : 12; char y : 6; } __attribute__((packed));"),
1346 1
1347 );
1348 assert_eq!(
1349 bit_field_byte("struct s { int x : 12; __attribute__((packed)) char y : 6; };"),
1350 1
1351 );
1352 assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { int x : 12; char y : 6; };"), 1);
1353 assert_eq!(bit_field_byte("struct s { char x; int y : 30; };"), 4);
1355 assert_eq!(bit_field_byte("struct s { char x; int y : 30; } __attribute__((packed));"), 1);
1356 assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { char x; int y : 30; };"), 1);
1358 assert_eq!(bit_field_byte("#pragma pack(2)\nstruct s { char x; int y : 30; };"), 1);
1359 }
1360
1361 fn bit_field_byte(record: &str) -> u64 {
1363 let source = format!("{record}\nint f(struct s *p) {{ return p->y; }}\n");
1364 let body = body(&source);
1365 let Some((before, _)) = body.split_once("ptr_add") else { return 0 };
1366 let (_, constant) = before.rsplit_once("iconst.i64 ").expect("an offset constant");
1367 constant.lines().next().expect("a line").trim().parse().expect("a byte offset")
1368 }
1369
1370 #[test]
1376 fn an_attribute_among_the_specifiers_is_kept_beside_the_ones_written_in_front() {
1377 tast(concat!(
1378 "struct a { char c; __attribute__((aligned(8))) int i; };\n",
1379 "_Static_assert(sizeof(struct a) == 16 && _Alignof(struct a) == 8, \"a\");\n",
1380 "_Static_assert(__builtin_offsetof(struct a, i) == 8, \"a.i\");\n",
1381 "struct b { char c; __attribute__((packed)) int i; };\n",
1382 "_Static_assert(sizeof(struct b) == 5 && _Alignof(struct b) == 1, \"b\");\n",
1383 "_Static_assert(__builtin_offsetof(struct b, i) == 1, \"b.i\");\n",
1384 "typedef struct { char c; int i; } __attribute__((packed)) c;\n",
1385 "_Static_assert(sizeof(c) == 5 && _Alignof(c) == 1, \"c\");\n",
1386 ));
1387 }
1388
1389 #[test]
1395 fn pragma_pack_caps_every_member_and_is_read_where_the_body_closes() {
1396 tast(concat!(
1397 "#pragma pack(1)\n",
1398 "struct A { char c; int i; };\n",
1399 "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
1400 "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
1401 "#pragma pack()\n",
1402 "struct B { char c; int i; };\n",
1403 "_Static_assert(sizeof(struct B) == 8 && _Alignof(struct B) == 4, \"B\");\n",
1404 "#pragma pack(2)\n",
1405 "struct C { char c; int i; double d; };\n",
1406 "_Static_assert(sizeof(struct C) == 14 && _Alignof(struct C) == 2, \"C\");\n",
1407 "_Static_assert(__builtin_offsetof(struct C, d) == 6, \"C.d\");\n",
1408 "struct K { char c; int i __attribute__((aligned(8))); };\n",
1410 "_Static_assert(sizeof(struct K) == 6 && _Alignof(struct K) == 2, \"K\");\n",
1411 "_Static_assert(__builtin_offsetof(struct K, i) == 2, \"K.i\");\n",
1412 "struct J { char c; int i; } __attribute__((aligned(8)));\n",
1414 "_Static_assert(sizeof(struct J) == 8 && _Alignof(struct J) == 8, \"J\");\n",
1415 "#pragma pack()\n",
1416 "#pragma pack(push, 1)\n",
1417 "struct D { char c; short s; };\n",
1418 "_Static_assert(sizeof(struct D) == 3 && _Alignof(struct D) == 1, \"D\");\n",
1419 "#pragma pack(pop)\n",
1420 "struct E { char c; short s; };\n",
1421 "_Static_assert(sizeof(struct E) == 4 && _Alignof(struct E) == 2, \"E\");\n",
1422 "struct H { char c;\n",
1424 "#pragma pack(1)\n",
1425 " int i; };\n",
1426 "_Static_assert(sizeof(struct H) == 5 && _Alignof(struct H) == 1, \"H\");\n",
1427 "#pragma pack(1)\n",
1428 "struct I { char c;\n",
1429 "#pragma pack()\n",
1430 " int i; };\n",
1431 "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
1432 "#pragma pack()\n",
1433 "#pragma pack(push, 8)\n",
1435 "#pragma pack(push, 1)\n",
1436 "struct P { char c; int i; };\n",
1437 "_Static_assert(sizeof(struct P) == 5 && _Alignof(struct P) == 1, \"P\");\n",
1438 "#pragma pack(pop)\n",
1439 "struct Q { char c; int i; };\n",
1440 "_Static_assert(sizeof(struct Q) == 8 && _Alignof(struct Q) == 4, \"Q\");\n",
1441 "#pragma pack(pop)\n",
1442 "#pragma pack(16)\n",
1444 "struct R { char c; int i; };\n",
1445 "_Static_assert(sizeof(struct R) == 8 && _Alignof(struct R) == 4, \"R\");\n",
1446 "#pragma pack()\n",
1447 "#pragma pack(1)\n",
1448 "struct S { char c; int i : 5; int j : 20; };\n",
1449 "_Static_assert(sizeof(struct S) == 5 && _Alignof(struct S) == 1, \"S\");\n",
1450 "union T { char c; int i; };\n",
1451 "_Static_assert(sizeof(union T) == 4 && _Alignof(union T) == 1, \"T\");\n",
1452 "#pragma pack()\n",
1453 ));
1454 }
1455
1456 #[test]
1460 fn a_pack_line_that_is_not_one_is_reported_in_the_words_gcc_uses() {
1461 let result = run(
1462 &options(),
1463 concat!(
1464 "#pragma pack 4\n",
1465 "#pragma pack(pop)\n",
1466 "#pragma pack(3)\n",
1467 "#pragma pack(1) junk\n",
1468 "#pragma pack(push, 1\n",
1469 "#pragma pack(x)\n",
1470 "#pragma pack(0)\n",
1473 "#pragma pack(push)\n",
1474 "struct s { char c; int i; };\n",
1475 "#pragma pack(pop)\n",
1476 "#pragma pack(pop, foo)\n",
1477 ),
1478 );
1479 let expected = [
1480 "missing `(` after `#pragma pack` - ignored",
1481 "`#pragma pack (pop)` encountered without matching `#pragma pack (push)`",
1482 "alignment must be a small power of two, not 3",
1483 "junk at end of `#pragma pack`",
1484 "malformed `#pragma pack(push[, id][, <n>])` - ignored",
1485 "unknown action `x` for `#pragma pack` - ignored",
1486 "`#pragma pack(pop, foo)` encountered without matching `#pragma pack(push, foo)`",
1487 ];
1488 assert_eq!(result.messages.len(), expected.len(), "{:?}", result.messages);
1489 for (message, want) in result.messages.iter().zip(expected) {
1490 assert!(message.contains(want), "expected {want:?} in {message:?}");
1491 }
1492 }
1493
1494 #[test]
1498 fn the_wide_integer_answers_to_all_three_of_its_names() {
1499 let text = tast("__uint128_t a; __int128_t b; unsigned __int128 c;\n");
1500 assert!(text.contains("decl #0 a : unsigned __int128"), "{text}");
1501 assert!(text.contains("decl #1 b : __int128"), "{text}");
1502 assert!(text.contains("decl #2 c : unsigned __int128"), "{text}");
1503 }
1504
1505 #[test]
1506 fn every_conversion_the_language_performs_is_a_node_in_the_output() {
1507 let text = tast("long f(int a, long b) { return a + b; }\n");
1511 assert!(text.contains("convert arithmetic"), "{text}");
1512 }
1513
1514 #[test]
1515 fn a_mistake_in_each_phase_reaches_the_caller_and_writes_no_tree() {
1516 for source in [
1517 "#error stop\n",
1518 "int f(void) { return 1 + ; }\n",
1519 "int f(void) { return undeclared; }\n",
1520 ] {
1521 let result = run(&options(), source);
1522 assert!(result.failed(), "expected this to fail:\n{source}");
1523 assert!(
1524 result.text().is_empty(),
1525 "a file that did not compile wrote a tree:\n{source}"
1526 );
1527 }
1528 }
1529
1530 #[test]
1531 fn one_undeclared_name_is_one_message_and_not_one_per_use() {
1532 let result = run(&options(), "int f(void) { return nope + nope * nope; }\n");
1536 assert_eq!(result.errors, 1, "{:?}", result.messages);
1537 }
1538
1539 #[test]
1540 fn a_declaration_the_parser_skipped_does_not_become_an_undeclared_name_as_well() {
1541 let result = run(&options(), "int x = ;\nint f(void) { return x; }\n");
1545 assert_eq!(result.errors, 1, "{:?}", result.messages);
1546 }
1547
1548 #[test]
1549 fn werror_turns_a_warning_into_an_error_in_the_count_and_in_the_word() {
1550 let source = "int f(void) { char c = 300; return c; }\n";
1551 let plain = run(&options(), source);
1552 assert_eq!(plain.errors, 0, "{:?}", plain.messages);
1553 assert_eq!(plain.messages.len(), 1, "expected a warning about the narrowed constant");
1554 assert!(!plain.text().is_empty(), "a warning is not a reason to write nothing");
1555
1556 let mut opts = options();
1557 opts.warnings_are_errors = true;
1558 let strict = run(&opts, source);
1559 assert!(strict.failed());
1560 assert!(strict.text().is_empty(), "and under -Werror it is a reason to write nothing");
1561 for message in &strict.messages {
1562 assert!(!message.contains("warning:"), "{message}");
1563 }
1564 }
1565
1566 #[test]
1567 fn w_drops_the_warning_before_werror_can_promote_it() {
1568 let source = "int f(void) { char c = 300; return c; }\n";
1569 let mut opts = options();
1570 opts.warnings = false;
1571 let quiet = run(&opts, source);
1572 assert_eq!(quiet.messages, Vec::<String>::new());
1573 assert_eq!(quiet.errors, 0);
1574 assert!(!quiet.text().is_empty(), "and the file still compiles");
1575
1576 opts.warnings_are_errors = true;
1579 let both = run(&opts, source);
1580 assert_eq!(both.messages, Vec::<String>::new());
1581 assert!(!both.failed(), "-w -Werror is not an error about a warning nobody saw");
1582 }
1583
1584 #[test]
1585 fn the_dialect_reaches_the_keywords_and_the_checking() {
1586 let source = "typeof(1) x;\n";
1589 let mut opts = options();
1590 opts.std = Std::C23;
1591 opts.gnu_extensions = false;
1592 assert!(!run(&opts, source).failed(), "{:?}", run(&opts, source).messages);
1593
1594 opts.std = Std::C17;
1595 assert!(run(&opts, source).failed());
1596 }
1597
1598 #[test]
1599 fn asking_for_a_kind_that_is_not_written_yet_runs_the_front_end_and_writes_nothing() {
1600 let mut opts = options();
1601 opts.emit = EmitKind::Object;
1602 let result = run(&opts, "int x = 1;\n");
1603 assert!(!result.failed(), "{:?}", result.messages);
1604 assert!(result.text().is_empty());
1605 assert!(run(&opts, "int f(void) { return undeclared; }\n").failed());
1608 }
1609
1610 fn mir(source: &str) -> String {
1612 let mut opts = options();
1613 opts.emit = EmitKind::MirFinal;
1614 let result = run(&opts, source);
1615 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1616 result.text().to_owned()
1617 }
1618
1619 #[test]
1625 fn a_function_goes_from_c_to_instructions_with_real_registers_in_them() {
1626 let text = mir("int add(int a, int b) { return a + b; }\n");
1627 assert!(text.starts_with("mfunc @add {"), "{text}");
1628 assert!(text.contains("x64.add_rr_32"), "{text}");
1629 assert!(text.contains("x64.ret"), "{text}");
1630 assert!(!text.contains('%'), "{text}");
1633 }
1634
1635 #[test]
1637 fn a_function_with_no_body_produces_no_machine_function() {
1638 let text = mir("int g(int);\nint f(int a) { return g(a); }\n");
1639 assert_eq!(text.matches("mfunc @").count(), 1, "{text}");
1640 assert!(text.contains("mfunc @f {"), "{text}");
1641 assert!(text.contains("x64.call"), "{text}");
1642 }
1643
1644 #[test]
1646 fn every_definition_in_the_file_is_generated_and_they_keep_their_order() {
1647 let text = mir("int a(int x) { return x; }\nint b(int x) { return x; }\n");
1648 let first = text.find("mfunc @a").expect("the first function");
1649 let second = text.find("mfunc @b").expect("the second function");
1650 assert!(first < second, "{text}");
1651 }
1652
1653 #[test]
1655 fn the_target_decides_which_convention_the_generated_code_follows() {
1656 let mut opts = options();
1657 opts.emit = EmitKind::MirFinal;
1658 let linux = run(&opts, "int f(int a) { return a; }\n").text().to_owned();
1659 assert!(linux.contains("$rdi"), "{linux}");
1660
1661 opts.target = "x86_64-pc-windows-msvc".parse::<Triple>().unwrap();
1662 let windows = run(&opts, "int f(int a) { return a; }\n").text().to_owned();
1663 assert!(windows.contains("$rcx"), "{windows}");
1664 assert!(!windows.contains("$rdi"), "{windows}");
1665 }
1666
1667 #[test]
1669 fn a_target_this_has_no_back_end_for_is_reported_rather_than_generated() {
1670 let mut opts = options();
1671 opts.emit = EmitKind::MirFinal;
1672 opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
1673 let result = run(&opts, "int f(int a) { return a; }\n");
1674 assert!(result.failed());
1675 assert!(result.messages[0].contains("no back end for aarch64"), "{:?}", result.messages);
1676 assert!(result.text().is_empty());
1677 }
1678
1679 #[test]
1686 fn a_construct_the_back_end_cannot_reach_yet_is_reported_against_its_function() {
1687 let mut opts = options();
1688 opts.emit = EmitKind::MirFinal;
1689 let source = "void a(int n) { int v[n]; v[0] = 1; }\n\
1690 void b(int n) { int v[n]; v[0] = 1; }\n";
1691 let result = run(&opts, source);
1692 assert!(result.failed());
1693 assert_eq!(result.messages.len(), 2, "{:?}", result.messages);
1694 assert!(result.messages[0].contains("cannot generate code for 'a'"), "{:?}", result);
1695 assert!(result.messages[0].contains("no rule lowers a `stacksave`"), "{:?}", result);
1696 assert!(result.messages[1].contains("cannot generate code for 'b'"), "{:?}", result);
1697 assert!(result.text().is_empty());
1698 }
1699
1700 #[test]
1707 fn an_opcode_with_no_name_in_the_rule_language_is_named_by_its_own_spelling() {
1708 let mut opts = options();
1709 opts.emit = EmitKind::MirFinal;
1710 let result = run(&opts, "int f(int a) {\n __int128 wide = a;\n return (int) wide;\n}\n");
1711 assert!(result.failed());
1712 assert!(
1713 result.messages[0].contains("no rule lowers a `sext` producing a `i128`"),
1714 "{result:?}"
1715 );
1716 assert!(result.messages[0].contains(":2:"), "the line the widening is on: {result:?}");
1717 assert!(!result.messages[0].contains("this instruction"), "{result:?}");
1718 }
1719
1720 #[test]
1722 fn the_note_on_unfinished_work_points_at_the_issues_rather_than_at_the_plan() {
1723 let mut opts = options();
1724 opts.emit = EmitKind::MirFinal;
1725 let result = run(&opts, "int f(int a) { __int128 wide = a; return (int) wide; }\n");
1726 assert!(result.failed());
1727 let note = result.messages.iter().find(|line| line.contains("note:")).expect("a note");
1728 assert!(note.contains("https://github.com/tamnd/rucc/issues"), "{note}");
1729 assert!(!note.contains("spec/17-milestones.md"), "{note}");
1730 }
1731
1732 #[test]
1734 fn the_frame_flags_on_the_command_line_reach_the_generated_frame() {
1735 let source = "int f(int a) { return a; }\n";
1736 assert!(!mir(source).contains("$rbp"), "a leaf needs no frame pointer by default");
1737
1738 let mut opts = options();
1739 opts.emit = EmitKind::MirFinal;
1740 opts.frame_pointer = true;
1741 let kept = run(&opts, source).text().to_owned();
1742 assert!(kept.contains("x64.push_64 $rbp"), "{kept}");
1743 }
1744
1745 fn asm(source: &str) -> String {
1747 let mut opts = options();
1748 opts.emit = EmitKind::Asm;
1749 let result = run(&opts, source);
1750 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1751 result.text().to_owned()
1752 }
1753
1754 #[test]
1761 fn a_function_goes_from_c_to_assembly_an_assembler_would_take() {
1762 let text = asm("int add(int a, int b) { return a + b; }\n");
1763 assert!(text.contains("\t.globl\tadd\n"), "{text}");
1764 assert!(text.contains("\t.type\tadd, @function\n"), "{text}");
1765 assert!(text.contains("\nadd:\n"), "{text}");
1766 assert!(text.contains("\taddl\t"), "{text}");
1767 assert!(text.contains("\tret\n"), "{text}");
1768 assert!(text.contains("\t.size\tadd, .-add\n"), "{text}");
1769 assert!(text.contains(".note.GNU-stack"), "{text}");
1772 }
1773
1774 #[test]
1780 fn a_call_through_a_function_pointer_goes_through_the_register_it_is_in() {
1781 let text = asm("int g(int);\nint f(int (*p)(int), int a) { return p(a) + g(a); }\n");
1782 assert!(text.contains("\tcall\t*%"), "{text}");
1783 assert!(text.contains("\tcall\tg\n"), "{text}");
1784 assert!(text.contains("%rdi"), "{text}");
1788 }
1789
1790 #[test]
1794 fn the_address_of_a_global_is_read_from_the_instruction_pointer() {
1795 let text = asm("extern int counter;\nint f(void) { return counter; }\n");
1796 assert!(text.contains("\tmovl\tcounter(%rip), %eax\n"), "{text}");
1797 }
1798
1799 #[test]
1808 fn a_branch_on_a_comparison_jumps_on_the_opposite_of_what_it_compared() {
1809 let arms = "return 1; return 2;";
1810 let signed = [("==", "jne"), ("!=", "je"), ("<", "jge"), ("<=", "jg"), (">", "jle")];
1811 for (operator, jump) in signed.into_iter().chain([(">=", "jl")]) {
1812 let text = asm(&format!("int f(int a, int b) {{ if (a {operator} b) {arms} }}\n"));
1813 assert!(
1814 text.contains(&format!("\tcmpl\t%esi, %edi\n\t{jump}\t")),
1815 "{operator}: {text}"
1816 );
1817 assert!(!text.contains("\tset"), "{operator}: {text}");
1818 assert!(!text.contains("\ttest"), "{operator}: {text}");
1819 }
1820 let unsigned = [("<", "jae"), ("<=", "ja"), (">", "jbe"), (">=", "jb")];
1821 for (operator, jump) in unsigned {
1822 let source =
1823 format!("int f(unsigned a, unsigned b) {{ if (a {operator} b) {arms} }}\n");
1824 let text = asm(&source);
1825 assert!(
1826 text.contains(&format!("\tcmpl\t%esi, %edi\n\t{jump}\t")),
1827 "{operator}: {text}"
1828 );
1829 }
1830
1831 let text = asm("int f(int a) { if (a < 7) return 1; return 2; }\n");
1834 assert!(text.contains("\tcmpl\t$7, %edi\n\tjge\t"), "{text}");
1835 }
1836
1837 #[test]
1843 fn a_comparison_whose_answer_the_program_wanted_still_writes_a_byte() {
1844 let text = asm("int f(int a, int b) { return a < b; }\n");
1845 assert!(text.contains("\tsetl\t"), "{text}");
1846 }
1847
1848 #[test]
1850 fn a_cast_between_a_pointer_and_an_integer_leaves_the_value_where_it_is() {
1851 let text = asm("long f(void *p) { return (long)p; }\n");
1852 for line in text.lines().filter(|line| line.starts_with('\t') && !line.contains('.')) {
1857 let mnemonic = line.split_whitespace().next().unwrap_or("");
1858 assert!(matches!(mnemonic, "movq" | "ret"), "{line} in\n{text}");
1859 }
1860 }
1861
1862 #[test]
1866 fn an_argument_past_the_last_register_is_read_out_of_the_caller_s_stack() {
1867 let six = "long a, long b, long c, long d, long e, long f";
1868 let text = asm(&format!("long f({six}, long g, long h) {{ return g + h; }}\n"));
1869
1870 assert!(text.contains("\tmovq\t8(%rsp), "), "{text}");
1874 assert!(text.contains("\tmovq\t16(%rsp), "), "{text}");
1875
1876 let narrow = asm(&format!("int f({six}, int g) {{ return g; }}\n"));
1880 assert!(narrow.contains("\tmovl\t8(%rsp), "), "{narrow}");
1881 let eight =
1882 "double a, double b, double c, double d, double e, double f, double g, double h";
1883 let float = asm(&format!("double f({eight}, double i) {{ return i; }}\n"));
1884 assert!(float.contains("\tmovsd\t8(%rsp), "), "{float}");
1885 }
1886
1887 #[test]
1890 fn a_call_writes_the_arguments_with_no_register_left_at_the_stack_pointer() {
1891 let six = "1, 2, 3, 4, 5, 6";
1892 let decl = "long g(long, long, long, long, long, long, long, long);\n";
1893 let text = asm(&format!("{decl}long f(void) {{ return g({six}, 7, 8); }}\n"));
1894
1895 assert!(text.contains("\tmovq\t%"), "{text}");
1896 assert!(text.contains(", (%rsp)\n"), "{text}");
1897 assert!(text.contains(", 8(%rsp)\n"), "{text}");
1898 assert!(text.contains("\tsubq\t$"), "{text}");
1900
1901 let narrow = "int g(int, int, int, int, int, int, int);\n";
1903 let text = asm(&format!("{narrow}int f(void) {{ return g({six}, 7); }}\n"));
1904 assert!(text.contains("\tmovl\t%"), "{text}");
1905 assert!(text.contains(", (%rsp)\n"), "{text}");
1906 }
1907
1908 #[test]
1911 fn a_variadic_call_counts_registers_and_not_arguments() {
1912 let nine = "1., 2., 3., 4., 5., 6., 7., 8., 9.";
1913 let decl = "int g(int, ...);\n";
1914 let text = asm(&format!("{decl}int f(void) {{ return g(0, {nine}); }}\n"));
1915
1916 assert!(text.contains("\tmovl\t$8, "), "eight registers, not nine: {text}");
1917 assert!(text.contains("\tmovsd\t%"), "{text}");
1918 assert!(text.contains(", (%rsp)\n"), "{text}");
1919 }
1920
1921 #[test]
1926 fn a_variadic_function_writes_the_argument_registers_it_was_handed_into_its_frame() {
1927 let body =
1928 "__builtin_va_list ap; __builtin_va_start(ap, n); __builtin_va_end(ap); return n;";
1929 let text = asm(&format!("int f(int n, ...) {{ {body} }}\n"));
1930
1931 let stores = |mnemonic: &str| text.matches(&format!("\t{mnemonic}\t%")).count();
1934 assert!(text.contains(", 8(%r"), "the second slot, not the first: {text}");
1935 assert!(!text.contains(", 0(%r"), "{text}");
1936 assert_eq!(stores("movsd"), 8, "every vector register: {text}");
1937
1938 assert!(text.contains("\tsubq\t$"), "{text}");
1940 }
1941
1942 #[test]
1945 fn va_start_writes_the_four_fields_the_psabi_describes() {
1946 let start = "__builtin_va_list ap; __builtin_va_start(ap, d);";
1947 let params = "int a, int b, int c, double d";
1948 let text = asm(&format!("int f({params}, ...) {{ {start} return a; }}\n"));
1949
1950 assert!(text.contains(" movl $24, "), "{text}");
1954 assert!(text.contains(" movl $64, "), "{text}");
1955 assert!(text.contains(", 8(%r"), "{text}");
1959 assert!(text.contains(", 16(%r"), "{text}");
1960 let frame: u32 = text
1961 .lines()
1962 .find_map(|line| line.trim().strip_prefix("subq $")?.split(',').next()?.parse().ok())
1963 .expect("a variadic function takes a frame for the save area");
1964 let above = |line: &str| {
1965 let at: u32 = line.trim().strip_prefix("leaq ")?.split('(').next()?.parse().ok()?;
1966 Some(at > frame)
1967 };
1968 assert!(text.lines().filter_map(above).any(|it| it), "{frame}: {text}");
1969 }
1970
1971 #[test]
1974 fn va_arg_branches_on_whether_the_argument_is_still_in_the_save_area() {
1975 let read = "__builtin_va_list ap; __builtin_va_start(ap, n);";
1976 let ints = format!("int f(int n, ...) {{ {read} return __builtin_va_arg(ap, int); }}\n");
1977 let text = asm(&ints);
1978
1979 assert!(text.contains("$40, "), "{text}");
1982 assert!(text.contains(" cmpl "), "{text}");
1983 assert!(text.contains(" ja "), "{text}");
1987
1988 let arg = "__builtin_va_arg(ap, double)";
1989 let text = asm(&format!("double f(int n, ...) {{ {read} return {arg}; }}\n"));
1990 assert!(text.contains("$160, "), "the last vector slot: {text}");
1991 }
1992
1993 #[test]
1996 fn a_structure_assignment_is_a_move_for_each_word_of_it() {
1997 let decl = "struct pair { long a, b; };\n";
1998 let body = "struct pair p = *q; return p.a + p.b;";
1999 let text = asm(&format!("{decl}long f(struct pair *q) {{ {body} }}\n"));
2000
2001 assert!(!text.contains("memcpy"), "nothing calls the library: {text}");
2002 assert!(!text.contains("\tcall"), "{text}");
2003 assert!(text.matches("\tmovq\t").count() >= 4, "two words each way: {text}");
2005 }
2006
2007 #[test]
2010 fn how_wide_a_word_of_a_copy_is_follows_the_alignment() {
2011 let decl = "struct bytes { char a[8]; };\n";
2012 let body = "struct bytes p = *q; return p.a[0];";
2013 let text = asm(&format!("{decl}int f(struct bytes *q) {{ {body} }}\n"));
2014
2015 assert!(text.matches("\tmovb\t").count() >= 16, "a byte at a time: {text}");
2017 }
2018
2019 #[test]
2022 fn the_part_of_an_initialiser_that_names_nothing_is_stored_as_zero() {
2023 let decl = "struct wide { long a, b, c; };\n";
2024 let text = asm(&format!("{decl}long f(void) {{ struct wide w = {{ 7 }}; return w.c; }}\n"));
2025
2026 assert!(!text.contains("memset"), "nothing calls the library: {text}");
2027 assert!(text.contains("\tmovq\t$0, ") || text.contains("$0, %"), "the zero: {text}");
2028 }
2029
2030 #[test]
2033 fn a_copy_too_large_to_unroll_calls_the_runtime() {
2034 let decl = "struct huge { char a[4096]; };\n";
2035 let mut opts = options();
2036 opts.emit = EmitKind::Asm;
2037 let source = format!("{decl}void f(struct huge *p, struct huge *q) {{ *p = *q; }}\n");
2038 let result = run(&opts, &source);
2039 assert!(!result.failed(), "{:?}", result.messages);
2040 let text = result.text();
2041 assert!(text.contains("call") && text.contains("memcpy"), "{text}");
2042 assert!(text.contains("4096"), "the size travels: {text}");
2045 }
2046
2047 #[test]
2050 fn a_realigned_frame_reads_them_through_the_frame_pointer() {
2051 let six = "long a, long b, long c, long d, long e, long f";
2052 let body = "_Alignas(32) long wide[4]; wide[0] = g; return wide[0];";
2053 let text = asm(&format!("long f({six}, long g) {{ {body} }}\n"));
2054
2055 assert!(text.contains("\tandq\t$-32, %rsp"), "{text}");
2059 assert!(text.contains("\tmovq\t16(%rbp), "), "{text}");
2060 assert!(!text.contains("\tmovq\t16(%rsp), "), "{text}");
2061 }
2062
2063 #[test]
2065 fn the_target_decides_how_the_assembly_is_spelled() {
2066 let mut opts = options();
2067 opts.emit = EmitKind::Asm;
2068 opts.target = "x86_64-apple-darwin".parse::<Triple>().unwrap();
2069 let text = run(&opts, "int f(void) { return 0; }\n").text().to_owned();
2070 assert!(text.contains("__TEXT,__text"), "{text}");
2071 assert!(text.contains("\n_f:\n"), "{text}");
2072 assert!(!text.contains(".note.GNU-stack"), "{text}");
2073 }
2074
2075 fn obj(source: &str) -> Vec<u8> {
2077 let mut opts = options();
2078 opts.emit = EmitKind::Object;
2079 let result = run(&opts, source);
2080 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
2081 match result.artifact {
2082 Artifact::Object(bytes) => bytes,
2083 other => panic!("expected an object, got {other:?}"),
2084 }
2085 }
2086
2087 #[test]
2093 fn a_function_goes_from_c_to_an_object_a_linker_would_take() {
2094 let bytes = obj("int add(int a, int b) { return a + b; }\n");
2095 assert_eq!(&bytes[..4], b"\x7fELF", "an object file starts by saying it is one");
2096 let text = asm("int add(int a, int b) { return a + b; }\n");
2097 assert!(
2098 text.contains("\taddl\t"),
2099 "and the listing of it is the same instructions:\n{text}"
2100 );
2101 }
2102
2103 #[test]
2105 fn a_variable_goes_from_c_to_the_section_it_belongs_in() {
2106 let text = asm("int counter = 42;\nstatic int hidden;\nconst int fixed = 7;\n");
2107 assert!(text.contains("\t.data\n\t.globl\tcounter\n"), "{text}");
2108 assert!(text.contains("\ncounter:\n\t.long\t42\n"), "{text}");
2109 assert!(text.contains("\t.size\tcounter, .-counter\n"), "{text}");
2110 assert!(text.contains("\t.bss\n\t.p2align\t2\n"), "{text}");
2113 assert!(text.contains("\nhidden:\n\t.space\t4\n"), "{text}");
2114 assert!(!text.contains(".globl\thidden"), "{text}");
2115 assert!(text.contains("\t.section\t.rodata\n"), "{text}");
2118 }
2119
2120 #[test]
2127 fn a_bit_field_initializer_writes_every_byte_of_the_value_and_not_only_the_ones_that_are_set() {
2128 let text = asm("struct s { unsigned f : 20; } x = { 0x12300 };\n");
2129 assert!(text.contains("\t.data\n"), "there is something to write: {text}");
2130 assert!(text.contains("\nx:\n\t.ascii\t\"\\000#\\001\"\n"), "and it is the value: {text}");
2131
2132 let text = asm("struct s { unsigned a : 8; unsigned b : 8; } x = { 0, 3 };\n");
2135 assert!(text.contains("\nx:\n\t.ascii\t\"\\000\\003\"\n"), "{text}");
2136
2137 let text = asm("struct s { unsigned long long f : 40; } x = { 0x100000 };\n");
2140 assert!(text.contains("\nx:\n\t.ascii\t\"\\000\\000\\020\"\n\t.space\t5\n"), "{text}");
2141
2142 let text = asm("struct s { unsigned f : 20; } x = { 0 };\n");
2144 assert!(text.contains("\t.bss\n"), "an object of zeroes is zeroes: {text}");
2145 assert!(text.contains("\nx:\n\t.space\t4\n"), "{text}");
2146 }
2147
2148 #[test]
2150 fn a_string_literal_is_a_variable_with_a_name_no_program_could_write() {
2151 let text = asm("const char *f(void) { return \"hi\"; }\n");
2152 assert!(text.contains("\t.ascii\t\"hi\\000\"\n"), "{text}");
2153 assert!(text.contains("\t.section\t.rodata\n"), "{text}");
2154 let label = text
2155 .lines()
2156 .find(|line| line.starts_with(".Lstr"))
2157 .unwrap_or_else(|| panic!("a label for the literal in\n{text}"));
2158 assert!(!text.contains(&format!(".globl\t{}", label.trim_end_matches(':'))), "{text}");
2159 }
2160
2161 #[test]
2163 fn an_address_in_an_initializer_is_left_to_the_linker() {
2164 let source = "int counter;\nint *p = &counter;\n";
2165 let text = asm(source);
2166 assert!(text.contains("\np:\n\t.quad\tcounter\n"), "{text}");
2167 let bytes = obj(source);
2170 assert!(bytes.windows(8).any(|w| w == b"counter\0"), "the object has to name it");
2171 }
2172
2173 #[test]
2182 fn a_constant_holding_an_address_goes_in_the_section_the_loader_may_write_once() {
2183 let text = asm("static void a(void) {}\nstatic void b(void) {}\n\
2186 struct m { void (*x)(void); void (*y)(void); };\n\
2187 const struct m t = { a, b };\n");
2188 assert!(text.contains("\t.section\t.data.rel.ro.local,\"aw\",@progbits\n"), "{text}");
2189 assert!(text.contains("\nt:\n\t.quad\ta\n\t.quad\tb\n"), "{text}");
2190
2191 let text =
2194 asm("void a(void);\nstruct m { void (*x)(void); };\nconst struct m t = { a };\n");
2195 assert!(text.contains("\t.section\t.data.rel.ro,\"aw\",@progbits\n"), "{text}");
2196
2197 let text = asm("const int fixed = 7;\n");
2199 assert!(text.contains("\t.section\t.rodata\n"), "{text}");
2200 }
2201
2202 #[test]
2204 fn a_thread_local_variable_is_reported_as_work_that_is_not_done() {
2205 let mut opts = options();
2206 opts.emit = EmitKind::Asm;
2207 let result = run(&opts, "_Thread_local int x = 1;\n");
2208 assert!(result.failed(), "every thread sharing one variable is worse than a message");
2209 assert!(result.messages.iter().any(|m| m.contains("thread-local")), "{:?}", result);
2210 assert!(!result.messages.iter().any(|m| m.contains("internal")), "{:?}", result);
2212 }
2213
2214 #[test]
2216 fn the_object_and_the_listing_are_two_spellings_of_one_compilation() {
2217 let source = "int callee(void); int g(void) { return callee(); }\n";
2221 let bytes = obj(source);
2222 assert!(
2223 bytes.windows(7).any(|w| w == b"callee\0"),
2224 "the object has to name the callee for the linker to find it"
2225 );
2226 let text = asm(source);
2227 assert!(text.contains("\tcall\tcallee\n"), "{text}");
2228 }
2229
2230 #[test]
2236 fn compiling_for_an_executable_produces_an_object_and_not_a_dump() {
2237 let mut opts = options();
2238 opts.emit = EmitKind::Executable;
2240 let result = run(&opts, "int main(void) { return 0; }\n");
2241 assert_eq!(result.messages, Vec::<String>::new());
2242 match result.artifact {
2243 Artifact::Object(bytes) => assert_eq!(&bytes[..4], b"\x7fELF"),
2244 other => panic!("expected an object, got {other:?}"),
2245 }
2246 }
2247
2248 #[test]
2250 fn a_platform_with_no_object_writer_is_said_so_rather_than_written_as_elf() {
2251 let mut opts = options();
2252 opts.emit = EmitKind::Object;
2253 opts.target = "x86_64-apple-darwin".parse::<Triple>().unwrap();
2254 let result = run(&opts, "int f(void) { return 0; }\n");
2255 assert!(result.failed(), "an object nobody can read is worse than a message");
2256 assert!(
2257 result.messages.iter().any(|m| m.contains("no object writer")),
2258 "{:?}",
2259 result.messages
2260 );
2261 }
2262
2263 fn ir(source: &str) -> String {
2265 let mut opts = options();
2266 opts.emit = EmitKind::Ir;
2267 let result = run(&opts, source);
2268 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
2269 result.text().to_owned()
2270 }
2271
2272 fn errors(source: &str) -> Vec<String> {
2274 let mut opts = options();
2275 opts.emit = EmitKind::Ir;
2276 let result = run(&opts, source);
2277 assert!(result.failed(), "expected this to be refused:\n{source}");
2278 result.messages
2279 }
2280
2281 fn body(source: &str) -> String {
2283 let text = ir(source);
2284 let (_, rest) = text.split_once("{\n").expect("a function definition");
2285 let (body, _) = rest.rsplit_once("}\n").expect("a function definition");
2286 body.to_owned()
2287 }
2288
2289 #[test]
2297 fn gnu89_inline_is_what_decides_whether_a_bare_inline_definition_reaches_the_module() {
2298 let source = "inline int f(int x) { return x + 1; }\n";
2299 let with = |flag: bool| {
2300 let mut opts = options();
2301 opts.emit = EmitKind::Ir;
2302 opts.gnu89_inline = flag;
2303 let result = run(&opts, source);
2304 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile");
2305 result.text().to_owned()
2306 };
2307
2308 assert!(!with(false).contains("block0"), "no body: {}", with(false));
2311
2312 assert!(with(true).contains("block0"), "a body: {}", with(true));
2315 }
2316
2317 #[test]
2331 fn lowering_says_nothing_about_the_type_an_access_went_through() {
2332 let source = "\
2335struct s { int a; float b; };\n\
2336union u { int i; float f; };\n\
2337int scalar(int *p) { return *p; }\n\
2338float member(struct s *p) { p->a = 1; return p->b; }\n\
2339int element(int *a, long i) { return a[i]; }\n\
2340float through_a_union(union u *p) { p->i = 1; return p->f; }\n";
2341 assert!(!ir(source).contains("tbaa"), "{}", ir(source));
2342 }
2343
2344 #[test]
2352 fn a_bare_return_from_a_function_that_promised_a_value_gives_back_a_zero() {
2353 let mut opts = options();
2354 opts.emit = EmitKind::Ir;
2355 opts.std = Std::C89;
2356 let compiled = |source: &str| {
2357 let result = run(&opts, source);
2358 assert_eq!(result.messages, Vec::<String>::new(), "C89 has nothing to say about this");
2359 result.text().to_owned()
2360 };
2361
2362 let text = compiled("int f(int x) { if (x) return; return 3; }\n");
2363 assert!(text.contains("iconst.i32 0\n return"), "zero goes back: {text}");
2364 assert!(!text.contains("unreachable"), "the branch that reached it is kept: {text}");
2365
2366 let text = compiled("double f(int x) { if (x) return; return 1.0; }\n");
2368 assert!(text.contains("fconst.f64 0x0\n return"), "a float zero goes back: {text}");
2369 }
2370
2371 #[test]
2379 fn a_call_to_a_name_nothing_declared_declares_it_as_c89_said_to() {
2380 let mut opts = options();
2381 opts.emit = EmitKind::Ir;
2382 opts.std = Std::C89;
2383 let compiled = |source: &str| {
2384 let result = run(&opts, source);
2385 assert_eq!(result.messages, Vec::<String>::new(), "C89 has nothing to say about this");
2386 result.text().to_owned()
2387 };
2388
2389 let text = compiled("int f(void) { return g(); }\n");
2391 assert!(text.contains("call @g"), "the call is to the name that was written: {text}");
2392 assert!(text.contains("i32"), "and it gives back an int: {text}");
2393
2394 let text = compiled("int f(char c) { return g(c); }\n");
2397 assert!(text.contains("sext.i32"), "the argument is promoted: {text}");
2398
2399 let mut opts = options();
2402 opts.std = Std::C89;
2403 let said = run(&opts, "int f(void) { return h; }\n").messages.join("\n");
2404 assert!(said.contains("'h' undeclared"), "not a call, so not declared: {said}");
2405 }
2406
2407 #[test]
2417 fn a_name_called_before_it_is_defined_still_gets_its_definition() {
2418 let mut opts = options();
2419 opts.emit = EmitKind::Ir;
2420 opts.std = Std::C89;
2421 let text = run(&opts, "int f(void) { return dummy(); }\ndummy () { return 7; }\n")
2422 .text()
2423 .to_owned();
2424 assert!(text.contains("func @f()"), "the caller is there: {text}");
2425 assert!(text.contains("func @dummy"), "and so is what it calls: {text}");
2426 assert!(text.contains("iconst.i32 7"), "with the body it was given: {text}");
2427 }
2428
2429 #[test]
2437 fn an_old_style_parameter_is_converted_from_what_the_call_promoted_it_to() {
2438 let mut opts = options();
2439 opts.emit = EmitKind::Ir;
2440 opts.std = Std::C89;
2441 let compiled = |source: &str| run(&opts, source).text().to_owned();
2442
2443 let text = compiled("f (c) unsigned char c; { return c; }\n");
2444 assert!(text.contains("func @f(i32"), "an int arrives: {text}");
2445 assert!(text.contains("trunc.i8"), "and is cut down to what was declared: {text}");
2446 assert!(text.contains("zext.i32"), "then read back unsigned: {text}");
2447
2448 let text = compiled("f (s) short s; { return s; }\n");
2450 assert!(text.contains("trunc.i16"), "cut down: {text}");
2451 assert!(text.contains("sext.i32"), "and read back signed: {text}");
2452
2453 let text = compiled("f (x) float x; { return x * 2; }\n");
2456 assert!(text.contains("func @f(f64"), "a double arrives: {text}");
2457 assert!(text.contains("fptrunc.f32"), "and is narrowed to the float: {text}");
2458
2459 let text = compiled("int f(unsigned char c) { return c; }\n");
2462 assert!(text.contains("func @f(i8)"), "the declared type arrives: {text}");
2463 assert!(!text.contains("trunc"), "so there is nothing to cut down: {text}");
2464 }
2465
2466 #[test]
2475 fn the_rules_gcc_promoted_are_decided_by_the_dialect_and_by_fpermissive() {
2476 let modes = [(Std::C89, false), (Std::C17, false), (Std::C17, true), (Std::C23, false)];
2478 let cases = [
2479 ("static counted;\n", ["", "error", "warning", "error"]),
2480 ("int f(void) { return g(); }\n", ["", "error", "warning", "error"]),
2481 ("int f(x) { return x; }\n", ["", "error", "warning", "error"]),
2482 ("int *p;\nvoid h(void) { p = 1; }\n", ["warning", "error", "warning", "error"]),
2483 (
2484 "char *q;\nint *r;\nvoid k(void) { r = q; }\n",
2485 ["warning", "error", "warning", "error"],
2486 ),
2487 ("int f(void) { return; }\n", ["", "error", "warning", "error"]),
2488 ("void g(void) { return 1; }\n", ["warning", "error", "warning", "error"]),
2489 ];
2490
2491 for (source, wanted) in cases {
2492 for (&(std, permissive), wanted) in modes.iter().zip(wanted) {
2493 let mut opts = options();
2494 opts.std = std;
2495 opts.permissive = permissive;
2496 let said = run(&opts, source).messages.join("\n");
2497 let severity = if said.contains(": error: ") {
2498 "error"
2499 } else if said.contains(": warning: ") {
2500 "warning"
2501 } else {
2502 ""
2503 };
2504 let how = if permissive { " -fpermissive" } else { "" };
2505 assert_eq!(
2506 severity,
2507 wanted,
2508 "under -std={}{how}, {source} was answered with `{said}`",
2509 std.as_str()
2510 );
2511 if wanted.is_empty() {
2512 assert!(said.is_empty(), "nothing to say, but said `{said}`");
2513 }
2514 }
2515 }
2516 }
2517
2518 #[test]
2527 fn the_three_variadic_builtins_answer_a_bad_list_the_way_a_call_answers_a_bad_argument() {
2528 let modes = [(Std::C89, false), (Std::C17, false), (Std::C17, true), (Std::C23, false)];
2529 let cases = [
2530 (
2531 "int f(int n, ...) { char *p; return __builtin_va_arg(p, int); }\n",
2532 "first argument to 'va_arg' not of type 'va_list'",
2533 ["error", "error", "error", "error"],
2534 ),
2535 (
2536 "void f(int n, ...) { char *p; __builtin_va_start(p, n); }\n",
2537 "passing argument 1 of '__builtin_va_start' from incompatible pointer type",
2538 ["warning", "error", "warning", "error"],
2539 ),
2540 (
2541 "void f(int n, ...) { int x; __builtin_va_end(x); }\n",
2542 "passing argument 1 of '__builtin_va_end' makes pointer from integer without a \
2543 cast",
2544 ["warning", "error", "warning", "error"],
2545 ),
2546 (
2547 "void f(int n, ...) { __builtin_va_list a; char *p; __builtin_va_copy(a, p); }\n",
2548 "passing argument 2 of '__builtin_va_copy' from incompatible pointer type",
2549 ["warning", "error", "warning", "error"],
2550 ),
2551 ];
2552
2553 for (source, message, wanted) in cases {
2554 for (&(std, permissive), wanted) in modes.iter().zip(wanted) {
2555 let mut opts = options();
2556 opts.std = std;
2557 opts.permissive = permissive;
2558 let said = run(&opts, source).messages.join("\n");
2559 let how = if permissive { " -fpermissive" } else { "" };
2560 assert!(
2561 said.contains(&format!(": {wanted}: {message}")),
2562 "under -std={}{how}, {source} was answered with `{said}`",
2563 std.as_str()
2564 );
2565 }
2566 }
2567 }
2568
2569 fn safe_ir(tier: rucc_session::Safety, source: &str) -> String {
2571 let mut opts = options();
2572 opts.emit = EmitKind::Ir;
2573 opts.safety = tier;
2574 let result = run(&opts, source);
2575 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
2576 result.text().to_owned()
2577 }
2578
2579 const READS_THROUGH_A_POINTER: &str = "int read(int *p) { return p[1]; }\n";
2580
2581 #[test]
2582 fn a_build_that_did_not_ask_for_the_monitor_is_compiled_the_way_it_always_was() {
2583 let text = ir(READS_THROUGH_A_POINTER);
2587 assert!(!text.contains("check_"), "{text}");
2588 assert!(!text.contains("cap_of"), "{text}");
2589 }
2590
2591 #[test]
2592 fn asking_for_a_tier_puts_the_checks_in_before_the_optimizer_sees_them() {
2593 let text = safe_ir(rucc_session::Safety::Detect, READS_THROUGH_A_POINTER);
2594 assert!(text.contains("cap_of"), "{text}");
2595 assert!(text.contains("check_bounds"), "{text}");
2596 assert!(text.contains("check_live"), "{text}");
2597 assert!(text.contains("check_deriv"), "{text}");
2599 }
2600
2601 #[test]
2602 fn the_three_tiers_that_are_not_off_all_check_the_same_accesses_so_far() {
2603 let detect = safe_ir(rucc_session::Safety::Detect, READS_THROUGH_A_POINTER);
2607 for tier in [rucc_session::Safety::Enforce, rucc_session::Safety::Kernel] {
2608 assert_eq!(safe_ir(tier, READS_THROUGH_A_POINTER), detect, "{tier}");
2609 }
2610 }
2611
2612 fn summary(tier: rucc_session::Safety, source: &str) -> String {
2614 let mut opts = options();
2615 opts.emit = EmitKind::SafetySummary;
2616 opts.safety = tier;
2617 let result = run(&opts, source);
2618 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
2619 result.text().to_owned()
2620 }
2621
2622 #[test]
2623 fn the_summary_counts_the_checks_that_went_in_and_the_ones_still_standing() {
2624 let text = summary(rucc_session::Safety::Detect, READS_THROUGH_A_POINTER);
2625 assert!(text.contains("\"tier\": \"detect\""), "{text}");
2626 assert!(
2628 text.contains("\"bounds\": { \"emitted\": 1, \"remaining\": 1, \"discharged\": 0 }"),
2629 "{text}"
2630 );
2631 assert!(
2632 text.contains(
2633 "\"derivation\": { \"emitted\": 1, \"remaining\": 1, \"discharged\": 0 }"
2634 ),
2635 "{text}"
2636 );
2637 }
2638
2639 #[test]
2640 fn a_build_without_the_monitor_summarises_as_a_build_with_no_checks_in_it() {
2641 let text = summary(rucc_session::Safety::Off, READS_THROUGH_A_POINTER);
2645 assert!(text.contains("\"tier\": \"off\""), "{text}");
2646 assert!(
2647 text.contains("\"bounds\": { \"emitted\": 0, \"remaining\": 0, \"discharged\": 0 }"),
2648 "{text}"
2649 );
2650 }
2651
2652 #[test]
2653 fn a_call_the_boundary_models_is_counted_apart_from_one_it_does_not() {
2654 let text = summary(
2655 rucc_session::Safety::Detect,
2656 "void *memcpy(void *, const void *, unsigned long);\n\
2657 int puts(const char *);\n\
2658 void f(char *d, char *s) { memcpy(d, s, 4); puts(d); }\n",
2659 );
2660 assert!(text.contains("\"interposed\": 1"), "{text}");
2661 assert!(text.contains("\"puts\""), "{text}");
2662 assert!(!text.contains("__rucc_wrap_memcpy\""), "{text}");
2666 }
2667
2668 #[test]
2669 fn the_two_directions_a_pointer_crosses_the_boundary_are_counted_apart() {
2670 let text = summary(
2674 rucc_session::Safety::Detect,
2675 "void *notes_open(void);\n\
2676 char *f(char *p) { char *q = notes_open(); return q ? q : p; }\n",
2677 );
2678 assert!(text.contains("\"crossings\": { \"entered\": 1, \"returned\": 1 }"), "{text}");
2679 assert!(text.contains("\"notes_open\""), "{text}");
2680 }
2681
2682 #[test]
2683 fn a_static_function_nobody_takes_the_address_of_is_not_a_crossing() {
2684 let text = summary(
2687 rucc_session::Safety::Detect,
2688 "static int len(const char *p) { return p ? 1 : 0; }\n\
2689 int f(void) { return len(\"x\"); }\n",
2690 );
2691 assert!(text.contains("\"crossings\": { \"entered\": 0, \"returned\": 0 }"), "{text}");
2692 }
2693
2694 fn granules(source: &str) -> String {
2696 let mut opts = options();
2697 opts.emit = EmitKind::TypeGranules;
2698 let result = run(&opts, source);
2699 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
2700 result.text().to_owned()
2701 }
2702
2703 #[test]
2704 fn the_granule_report_names_every_record_and_both_keyings() {
2705 let text = granules(
2706 "struct hot { char *p; int a; int b; };\n\
2707 int f(struct hot *h) { return h->a; }\n",
2708 );
2709 assert!(text.contains("struct hot"), "{text}");
2710 assert!(text.contains("every type distinct"), "{text}");
2713 assert!(text.contains("every pointer one type"), "{text}");
2714 assert!(text.contains("budget"), "{text}");
2715 }
2716
2717 #[test]
2718 fn a_record_nothing_uses_is_still_measured() {
2719 let text = granules("struct unused { long a; double b; };\nint f(void) { return 0; }\n");
2722 assert!(text.contains("struct unused"), "{text}");
2723 }
2724
2725 #[test]
2726 fn the_granule_report_stops_before_anything_is_lowered() {
2727 let text = granules(
2731 "struct wide { long double d; };\n\
2732 long double f(long double x) { return x * x; }\n",
2733 );
2734 assert!(text.contains("struct wide"), "{text}");
2735 }
2736
2737 #[test]
2738 fn a_witness_reaches_the_assembler_as_a_call_to_the_runtime() {
2739 let text = safe_asm(rucc_session::Safety::Detect, "char *f(char *p) { return p; }\n");
2742 assert!(text.contains("\tcall\t__rucc_cap_witness\n"), "{text}");
2743 }
2744
2745 #[test]
2746 fn a_pointer_turned_into_an_integer_is_on_the_trust_set() {
2747 let text = summary(
2748 rucc_session::Safety::Detect,
2749 "unsigned long f(int *p) { return (unsigned long) p; }\n",
2750 );
2751 assert!(text.contains("\"exposed\": 1"), "{text}");
2752 }
2753
2754 fn safe_asm(tier: rucc_session::Safety, source: &str) -> String {
2756 let mut opts = options();
2757 opts.emit = EmitKind::Asm;
2758 opts.safety = tier;
2759 let result = run(&opts, source);
2760 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
2761 result.text().to_owned()
2762 }
2763
2764 #[test]
2765 fn a_check_reaches_the_assembler_as_a_call_to_the_runtime() {
2766 let text = safe_asm(rucc_session::Safety::Detect, READS_THROUGH_A_POINTER);
2767 assert!(text.contains("\tcall\t__rucc_check_bounds\n"), "{text}");
2768 assert!(text.contains("\tcall\t__rucc_check_live\n"), "{text}");
2769 assert!(text.contains("\tcall\t__rucc_check_deriv\n"), "{text}");
2770 }
2771
2772 #[test]
2773 fn every_check_that_reached_the_assembler_has_a_row_describing_it() {
2774 let text = safe_asm(rucc_session::Safety::Detect, READS_THROUGH_A_POINTER);
2778 let section = format!("\t.section\t{},", rucc_safety::SECTION);
2779 assert_eq!(text.matches(§ion).count(), 3, "{text}");
2780 for index in 0..3 {
2781 let name = format!("__rucc_safety_desc_{index}");
2782 assert!(text.contains(&format!("{name}:\n")), "{text}");
2785 assert!(text.contains(&format!("{name}(%rip)")), "{text}");
2786 }
2787 assert!(!text.contains("__rucc_safety_desc_3"), "{text}");
2788 }
2789
2790 #[test]
2798 fn builtin_constant_p_is_folded_where_it_is_written_rather_than_called() {
2799 let text = ir(concat!(
2800 "int g;\n",
2801 "int a = __builtin_constant_p(1);\n",
2802 "int b = __builtin_constant_p(g);\n",
2803 "int c = __builtin_constant_p(\"abc\");\n",
2804 "int d = __builtin_constant_p(&g);\n",
2805 "int e = __builtin_constant_p(1.5);\n",
2806 "int h = __builtin_choose_expr(__builtin_constant_p(3), 11, 22);\n",
2807 ));
2808 assert!(text.contains("global @a : i32 = 1,"), "{text}");
2809 assert!(text.contains("global @b : i32 = 0,"), "{text}");
2810 assert!(text.contains("global @c : i32 = 1,"), "{text}");
2811 assert!(text.contains("global @d : i32 = 0,"), "{text}");
2812 assert!(text.contains("global @e : i32 = 1,"), "{text}");
2813 assert!(text.contains("global @h : i32 = 11,"), "{text}");
2814 assert!(!text.contains("__builtin_constant_p"), "it is not a call to anything:\n{text}");
2815
2816 let text = body("int f(void) { int i = 0; __builtin_constant_p(i++); return i; }\n");
2820 assert_eq!(text, "block0:\n %0 = iconst.i32 0\n %1 = iconst.i32 0\n return %0\n");
2821 }
2822
2823 #[test]
2832 fn a_call_to_a_library_builtin_reaches_the_library_function() {
2833 let text = body("void f(void) { __builtin_abort(); }\n");
2834 assert_eq!(text, "block0:\n call @abort() : ()\n return\n");
2835
2836 let text = ir("int f(const char *s) { return __builtin_puts(s) + __builtin_strlen(s); }\n");
2839 assert!(text.contains("call @puts(%0) : (ptr) -> i32"), "{text}");
2840 assert!(text.contains("call @strlen(%0) : (ptr) -> i64"), "{text}");
2841 assert!(!text.contains("__builtin_"), "the prefix is not part of any name here:\n{text}");
2842 }
2843
2844 #[test]
2855 fn the_absolute_value_family_is_the_magnitude_and_not_a_call() {
2856 let text = body(concat!(
2857 "long long llabs(long long);\n",
2858 "long long f(long long x) { return llabs(x); }\n",
2859 ));
2860 assert!(text.contains("%1 = iconst.i64 63"), "{text}");
2861 assert!(text.contains("%2 = ashr %0, %1"), "{text}");
2862 assert!(text.contains("%3 = xor %0, %2"), "{text}");
2863 assert!(text.contains("%4 = sub %3, %2"), "{text}");
2864 assert!(!text.contains("call"), "the call does not happen:\n{text}");
2865
2866 let text = body("int abs(int);\nint f(int x) { return abs(x); }\n");
2869 assert!(text.contains("iconst.i32 31"), "{text}");
2870 let text = body("long labs(long);\nlong f(long x) { return labs(x); }\n");
2871 assert!(text.contains("iconst.i64 63"), "{text}");
2872
2873 let text = body("long long f(long long x) { return __builtin_llabs(x); }\n");
2876 assert!(!text.contains("call"), "{text}");
2877
2878 let text = ir(concat!(
2880 "long long llabs(long long b);\n",
2881 "long long g(long long x) { return llabs(x); }\n",
2882 "long long llabs(long long b) { return 7; }\n",
2883 ));
2884 assert!(!text.contains("call @llabs"), "{text}");
2885 }
2886
2887 #[test]
2894 fn a_byte_swap_is_arithmetic_and_not_a_call() {
2895 let text = body("unsigned f(unsigned x) { return __builtin_bswap32(x); }\n");
2896 assert_eq!(text, "block0(%0: i32):\n %1 = bswap %0\n return %1\n");
2897
2898 let text = body("unsigned f(unsigned char c) { return __builtin_bswap32(c); }\n");
2901 assert!(text.contains("zext.i32 %0"), "widened first: {text}");
2902 assert!(text.contains("bswap %1"), "and swapped at four bytes: {text}");
2903 }
2904
2905 #[test]
2911 fn the_byte_swaps_reverse_at_the_width_their_name_says() {
2912 for (name, ty, width) in [
2913 ("__builtin_bswap16", "unsigned short", "i16"),
2914 ("__builtin_bswap32", "unsigned", "i32"),
2915 ("__builtin_bswap64", "unsigned long long", "i64"),
2916 ] {
2917 let source = format!("{ty} f({ty} x) {{ return {name}(x); }}\n");
2918 let text = body(&source);
2919 assert_eq!(
2920 text,
2921 format!("block0(%0: {width}):\n %1 = bswap %0\n return %1\n"),
2922 "{name}"
2923 );
2924 }
2925 }
2926
2927 #[test]
2934 fn the_bit_counts_are_instructions_and_not_calls() {
2935 let text = body("int f(unsigned x) { return __builtin_clz(x); }\n");
2936 assert_eq!(text, "block0(%0: i32):\n %1 = ctlz %0\n return %1\n");
2937
2938 let text = body("int f(unsigned x) { return __builtin_ctz(x); }\n");
2939 assert_eq!(text, "block0(%0: i32):\n %1 = cttz %0\n return %1\n");
2940
2941 let text = body("int f(unsigned x) { return __builtin_popcount(x); }\n");
2942 assert_eq!(text, "block0(%0: i32):\n %1 = ctpop %0\n return %1\n");
2943 }
2944
2945 #[test]
2954 fn the_bit_counts_ask_about_the_width_their_name_says() {
2955 let text = body("int f(unsigned long long x) { return __builtin_clzll(x); }\n");
2956 assert!(text.starts_with("block0(%0: i64):"), "counted at eight bytes: {text}");
2957 assert!(text.contains("%1 = ctlz %0"), "{text}");
2958 assert!(text.contains("trunc.i32 %1"), "and answered in an int: {text}");
2959
2960 let text = body("int f(unsigned long long x) { return __builtin_clz(x); }\n");
2963 assert!(text.contains("trunc.i32 %0"), "narrowed to what was asked about: {text}");
2964 assert!(text.contains("ctlz %1"), "and counted there: {text}");
2965
2966 let text = body("int f(unsigned long x) { return __builtin_popcountl(x); }\n");
2967 assert!(text.contains("%1 = ctpop %0"), "{text}");
2968 assert!(!text.contains("call"), "{text}");
2969 }
2970
2971 #[test]
2976 fn a_parity_is_the_low_bit_of_the_set_bit_count() {
2977 let text = body("int f(unsigned x) { return __builtin_parity(x); }\n");
2978 assert!(text.contains("%1 = ctpop %0"), "{text}");
2979 assert!(text.contains("iconst.i32 1"), "{text}");
2980 assert!(text.contains("and %1, %2"), "the low bit of it: {text}");
2981 }
2982
2983 #[test]
2989 fn the_first_set_bit_is_one_based_and_zero_for_a_zero() {
2990 let text = body("int f(int x) { return __builtin_ffs(x); }\n");
2991 assert!(text.contains("%1 = cttz %0"), "{text}");
2992 assert!(text.contains("%4 = add %1, %2"), "one more than the count: {text}");
2993 assert!(text.contains("%5 = icmp ne %0, %3"), "whether there was a bit at all: {text}");
2994 assert!(text.contains("%7 = sub %3, %6"), "spread to a mask: {text}");
2995 assert!(text.contains("%8 = and %4, %7"), "and kept only then: {text}");
2996 assert!(!text.contains("br_if"), "no branch: {text}");
2997 }
2998
2999 #[test]
3009 fn an_overflow_check_is_arithmetic_and_not_a_call() {
3010 let text =
3011 body("int f(int a, int b, int *r) { return __builtin_add_overflow(a, b, r); }\n");
3012 assert!(text.contains("%3, %4 = sadd_overflow.(i32, i1) %0, %1"), "{text}");
3013 assert!(text.contains("store %3 -> %2"), "{text}");
3014 assert!(!text.contains("call"), "{text}");
3015
3016 let text =
3017 body("int f(int a, int b, int *r) { return __builtin_sub_overflow(a, b, r); }\n");
3018 assert!(text.contains("ssub_overflow.(i32, i1) %0, %1"), "{text}");
3019
3020 let text =
3021 body("int f(int a, int b, int *r) { return __builtin_mul_overflow(a, b, r); }\n");
3022 assert!(text.contains("smul_overflow.(i32, i1) %0, %1"), "{text}");
3023
3024 let text = body(
3027 "int f(unsigned a, unsigned b, unsigned *r) { return __builtin_add_overflow(a, b, r); }\n",
3028 );
3029 assert!(text.contains("uadd_overflow.(i32, i1) %0, %1"), "{text}");
3030 }
3031
3032 #[test]
3040 fn an_overflow_check_is_done_at_a_type_that_holds_every_operand() {
3041 let text = body(
3042 "int f(unsigned a, int b, long long *r) { return __builtin_add_overflow(a, b, r); }\n",
3043 );
3044 assert!(text.contains("%3 = zext.i64 %0"), "the unsigned operand keeps its value: {text}");
3045 assert!(text.contains("%4 = sext.i64 %1"), "and so does the signed one: {text}");
3046 assert!(text.contains("sadd_overflow.(i64, i1) %3, %4"), "{text}");
3047
3048 let text = body(
3051 "int f(long long a, long long b, long long *r) { return __builtin_mul_overflow(a, b, r); }\n",
3052 );
3053 assert!(text.contains("smul_overflow.(i64, i1) %0, %1"), "{text}");
3054 assert!(!text.contains("sext."), "{text}");
3055 assert!(!text.contains("zext.i64"), "{text}");
3057 }
3058
3059 #[test]
3067 fn an_overflow_check_writes_the_wrapped_answer_whether_or_not_it_fit() {
3068 let text =
3069 body("int f(int a, int b, char *r) { return __builtin_sub_overflow(a, b, r); }\n");
3070 assert!(text.contains("%3, %4 = ssub_overflow.(i32, i1) %0, %1"), "{text}");
3071 assert!(text.contains("%5 = trunc.i8 %3"), "narrowed to where it goes: {text}");
3072 assert!(text.contains("%6 = sext.i32 %5"), "and back: {text}");
3073 assert!(text.contains("%7 = icmp ne %6, %3"), "which is whether it fit: {text}");
3074 assert!(text.contains("store %5 -> %2"), "the narrowed value is stored either way: {text}");
3075 assert!(text.contains("%8 = or %4, %7"), "and either bit is an overflow: {text}");
3076 }
3077
3078 #[test]
3085 fn a_call_needing_more_than_sixty_four_bits_says_so() {
3086 let refused = concat!(
3087 "int f(unsigned long long a, long long b, long long *r) {\n",
3088 " return __builtin_add_overflow(a, b, r);\n",
3089 "}\n",
3090 );
3091 let messages = errors(refused);
3092 assert_eq!(messages.len(), 1, "{messages:?}");
3093 assert!(messages[0].contains("E0694"), "{messages:?}");
3094 assert!(messages[0].contains("wider than 64 bits"), "{messages:?}");
3095 }
3096
3097 #[test]
3100 fn an_overflow_check_over_something_that_is_not_an_integer_says_so() {
3101 let messages =
3102 errors("int f(double a, int b, int *r) { return __builtin_add_overflow(a, b, r); }\n");
3103 assert!(messages.iter().any(|line| line.contains("E0671")), "{messages:?}");
3104
3105 let messages =
3106 errors("int f(int a, int b, double *r) { return __builtin_add_overflow(a, b, r); }\n");
3107 assert!(messages.iter().any(|line| line.contains("E0671")), "{messages:?}");
3108 }
3109
3110 #[test]
3121 fn an_ordered_access_is_ordered_in_the_ir() {
3122 let text = body("int f(int *p) { return __atomic_load_n(p, 0); }\n");
3123 assert!(text.contains("atomic_load.i32 %0, align 4, relaxed"), "{text}");
3124
3125 let text = body("long f(long *p) { return __atomic_load_n(p, 2); }\n");
3126 assert!(text.contains("atomic_load.i64 %0, align 8, acquire"), "{text}");
3127
3128 let text = body("void f(int *p, int v) { __atomic_store_n(p, v, 3); }\n");
3129 assert!(text.contains("atomic_store %1 -> %0, align 4, release"), "{text}");
3130
3131 let text = body("void f(int *p, int v) { __atomic_store_n(p, v, 5); }\n");
3132 assert!(text.contains("atomic_store %1 -> %0, align 4, seq_cst"), "{text}");
3133
3134 let text = body("void f(char *p, int v) { __atomic_store_n(p, v, 0); }\n");
3137 assert!(text.contains("trunc.i8 %1"), "{text}");
3138 assert!(text.contains("atomic_store %2 -> %0, align 1, relaxed"), "{text}");
3139 }
3140
3141 #[test]
3150 fn an_ordered_access_is_the_plain_instruction_on_this_machine() {
3151 let text = asm("int f(int *p) { return __atomic_load_n(p, 5); }\n");
3152 assert!(text.contains("movl\t(%rdi), %eax"), "{text}");
3153 assert!(!text.contains("mfence"), "a load needs no barrier here: {text}");
3154
3155 let text = asm("void f(int *p, int v) { __atomic_store_n(p, v, 3); }\n");
3156 assert!(text.contains("movl\t%esi, (%rdi)"), "{text}");
3157 assert!(!text.contains("mfence"), "a release store needs no barrier here: {text}");
3158
3159 let text = asm("void f(int *p, int v) { __atomic_store_n(p, v, 5); }\n");
3160 let (before, after) = text.split_once("mfence").expect("a barrier: {text}");
3161 assert!(before.contains("movl\t%esi, (%rdi)"), "the store comes first: {text}");
3162 assert!(!after.contains("movl"), "and nothing else is between them: {text}");
3163 }
3164
3165 #[test]
3175 fn a_barrier_is_one_instruction_at_the_strongest_ordering_and_none_below_it() {
3176 assert!(asm("void f(void) { __atomic_thread_fence(5); }\n").contains("mfence"));
3177 assert!(asm("void f(void) { __sync_synchronize(); }\n").contains("mfence"));
3178
3179 for weaker in ["1", "2", "3", "4"] {
3180 let source = format!("void f(void) {{ __atomic_thread_fence({weaker}); }}\n");
3181 assert!(!asm(&source).contains("mfence"), "{weaker} costs nothing here");
3182 }
3183 }
3184
3185 #[test]
3191 fn a_compare_and_exchange_is_one_instruction_answering_two_things() {
3192 let text =
3195 body("int f(int *p, int e, int d) { return __sync_val_compare_and_swap(p, e, d); }\n");
3196 assert!(text.contains("%3, %4 = cmpxchg.(i32, i1) %0, %1, %2, align 4, seq_cst"), "{text}");
3197 assert!(text.contains("return %3"), "the value it found: {text}");
3198
3199 let text =
3200 body("int f(int *p, int e, int d) { return __sync_bool_compare_and_swap(p, e, d); }\n");
3201 assert!(text.contains("%3, %4 = cmpxchg.(i32, i1) %0, %1, %2, align 4, seq_cst"), "{text}");
3202 assert!(text.contains("zext.i32 %4"), "whether it happened: {text}");
3203
3204 let text = body(
3207 "int f(int *p, int *e, int d) { return __atomic_compare_exchange_n(p, e, d, 0, 4, 2); }\n",
3208 );
3209 assert!(text.contains("%3 = load.i32 %1, align 4"), "{text}");
3210 assert!(text.contains("%4, %5 = cmpxchg.(i32, i1) %0, %3, %2, align 4, acq_rel"), "{text}");
3211 assert!(text.contains("br_if %5, block2, block1"), "{text}");
3212 assert!(text.contains("store %4 -> %1, align 4"), "{text}");
3213
3214 let text = body(
3217 "int f(int *p, int *e, int *d) { return __atomic_compare_exchange(p, e, d, 0, 5, 5); }\n",
3218 );
3219 assert!(text.contains("%3 = load.i32 %1, align 4"), "{text}");
3220 assert!(text.contains("%4 = load.i32 %2, align 4"), "{text}");
3221 assert!(text.contains("%5, %6 = cmpxchg.(i32, i1) %0, %3, %4, align 4, seq_cst"), "{text}");
3222 }
3223
3224 #[test]
3231 fn a_compare_and_exchange_is_a_locked_instruction_at_the_width_of_the_object() {
3232 let widths = [("char", "b", "%dl"), ("short", "w", "%dx"), ("int", "l", "%edx")];
3233 for (ty, suffix, reg) in widths {
3234 let source = format!(
3235 "int f({ty} *p, {ty} e, {ty} d) {{ return __sync_bool_compare_and_swap(p, e, d); }}\n"
3236 );
3237 let text = asm(&source);
3238 assert!(text.contains("\tlock\n"), "{ty}: {text}");
3239 assert!(text.contains(&format!("cmpxchg{suffix}\t{reg}, (%rdi)")), "{ty}: {text}");
3240 assert!(text.contains("sete\t"), "{ty}: {text}");
3241 }
3242 let source =
3243 "int f(long *p, long e, long d) { return __sync_bool_compare_and_swap(p, e, d); }\n";
3244 assert!(asm(source).contains("cmpxchgq\t%rdx, (%rdi)"), "{}", asm(source));
3245
3246 for order in ["0", "2", "3", "4", "5"] {
3250 let call = format!("__atomic_compare_exchange_n(p, e, d, 0, {order}, 0)");
3251 let source = format!("int f(int *p, int *e, int d) {{ return {call}; }}\n");
3252 let text = asm(&source);
3253 assert!(text.contains("cmpxchgl\t"), "{order}: {text}");
3254 assert!(!text.contains("mfence"), "{order} needs no barrier here: {text}");
3255 }
3256 }
3257
3258 #[test]
3270 fn a_read_modify_write_is_one_instruction_and_the_arithmetic_a_name_asks_for() {
3271 let text = body("int f(int *p, int v) { return __atomic_fetch_add(p, v, 5); }\n");
3272 assert!(text.contains("%2 = atomic_rmw.i32 add %0, %1, align 4, seq_cst"), "{text}");
3273 assert!(text.contains("return %2"), "the value that was there: {text}");
3274
3275 let text = body("int f(int *p, int v) { return __atomic_add_fetch(p, v, 5); }\n");
3276 assert!(text.contains("%2 = atomic_rmw.i32 add %0, %1, align 4, seq_cst"), "{text}");
3277 assert!(text.contains("%3 = add %2, %1"), "and the value afterwards: {text}");
3278
3279 let text = body("int f(int *p, int v) { return __atomic_sub_fetch(p, v, 5); }\n");
3280 assert!(text.contains("%2 = atomic_rmw.i32 sub %0, %1, align 4, seq_cst"), "{text}");
3281 assert!(text.contains("%3 = sub %2, %1"), "{text}");
3282
3283 let text = body("int f(int *p, int v) { return __sync_fetch_and_sub(p, v); }\n");
3285 assert!(text.contains("%2 = atomic_rmw.i32 sub %0, %1, align 4, seq_cst"), "{text}");
3286
3287 let text = body("int f(int *p, int v) { return __atomic_exchange_n(p, v, 5); }\n");
3290 assert!(text.contains("%2 = atomic_rmw.i32 xchg %0, %1, align 4, seq_cst"), "{text}");
3291
3292 let text = body("int f(int *p, int v) { return __sync_lock_test_and_set(p, v); }\n");
3293 assert!(text.contains("%2 = atomic_rmw.i32 xchg %0, %1, align 4, acquire"), "{text}");
3294
3295 let text = body("void f(int *p) { __sync_lock_release(p); }\n");
3298 assert!(text.contains("release"), "{text}");
3299 assert!(text.contains("%1 = iconst.i32 0"), "{text}");
3300
3301 let text = body("void f(int *p, int guard) { __sync_lock_release(p, guard); }\n");
3305 assert!(text.contains("%2 = iconst.i32 0"), "{text}");
3306 assert!(text.contains("atomic_store %2 -> %0, align 4, release"), "{text}");
3307
3308 let text = body("int f(int *p, int v) { return __atomic_fetch_and(p, v, 5); }\n");
3311 assert!(text.contains("%2 = atomic_rmw.i32 and %0, %1, align 4, seq_cst"), "{text}");
3312
3313 let text = body("int f(int *p, int v) { return __sync_or_and_fetch(p, v); }\n");
3314 assert!(text.contains("%2 = atomic_rmw.i32 or %0, %1, align 4, seq_cst"), "{text}");
3315 assert!(text.contains("%3 = or %2, %1"), "and the value afterwards: {text}");
3316
3317 let text = body("int f(int *p, int v) { return __atomic_nand_fetch(p, v, 5); }\n");
3320 assert!(text.contains("%2 = atomic_rmw.i32 nand %0, %1, align 4, seq_cst"), "{text}");
3321 assert!(text.contains("%3 = and %2, %1"), "{text}");
3322 assert!(text.contains("%4 = iconst.i32 -1"), "{text}");
3323 assert!(text.contains("%5 = xor %3, %4"), "{text}");
3324 }
3325
3326 #[test]
3337 fn a_bitwise_read_modify_write_is_a_loop_around_the_compare_and_exchange() {
3338 let widths = [("char", "b", "%dl"), ("short", "w", "%dx"), ("int", "l", "%edx")];
3339 for (ty, suffix, reg) in widths {
3340 for (name, call, insn) in [
3341 ("and", "__atomic_fetch_and(p, v, 5)", "and"),
3342 ("or", "__sync_fetch_and_or(p, v)", "or"),
3343 ("xor", "__atomic_xor_fetch(p, v, 5)", "xor"),
3344 ] {
3345 let source = format!("{ty} f({ty} *p, {ty} v) {{ return {call}; }}\n");
3346 let text = asm(&source);
3347 assert!(text.contains("\tlock\n"), "{ty} {name}: {text}");
3348 assert!(
3349 text.contains(&format!("cmpxchg{suffix}\t{reg}, (%rdi)")),
3350 "{ty} {name}: {text}"
3351 );
3352 assert!(text.contains(&format!("{insn}{suffix}\t")), "{ty} {name}: {text}");
3353 assert!(!text.contains("\txadd"), "{ty} {name} is not an add: {text}");
3355 assert!(!text.contains("\txchg"), "{ty} {name} is not an exchange: {text}");
3356 }
3357 }
3358 let source = "long f(long *p, long v) { return __atomic_fetch_or(p, v, 5); }\n";
3359 assert!(asm(source).contains("cmpxchgq\t%rdx, (%rdi)"), "{}", asm(source));
3360
3361 let text = asm("int f(int *p, int v) { return __sync_fetch_and_nand(p, v); }\n");
3365 assert!(text.contains("cmpxchgl\t"), "{text}");
3366 assert!(text.contains("andl\t"), "{text}");
3367 assert!(text.contains("notl\t"), "{text}");
3368 }
3369
3370 #[test]
3379 fn an_access_through_a_second_pointer_is_the_same_access_and_one_more() {
3380 let text = body("void f(int *p, int *r) { __atomic_load(p, r, 5); }\n");
3381 assert!(text.contains("%2 = atomic_load.i32 %0, align 4, seq_cst"), "{text}");
3382 assert!(text.contains("store %2 -> %1, align 4"), "and out through the place: {text}");
3383
3384 let text = body("void f(int *p, int *v) { __atomic_store(p, v, 3); }\n");
3385 assert!(text.contains("%2 = load.i32 %1, align 4"), "in through the place: {text}");
3386 assert!(text.contains("atomic_store %2 -> %0, align 4, release"), "{text}");
3387
3388 let text = body("void f(int *p, int *v, int *r) { __atomic_exchange(p, v, r, 5); }\n");
3391 assert!(text.contains("%3 = load.i32 %1, align 4"), "{text}");
3392 assert!(text.contains("%4 = atomic_rmw.i32 xchg %0, %3, align 4, seq_cst"), "{text}");
3393 assert!(text.contains("store %4 -> %2, align 4"), "{text}");
3394 }
3395
3396 #[test]
3407 fn a_flag_is_an_exchange_of_one_byte_and_a_store_of_a_zero_over_the_same_byte() {
3408 for pointer in ["char", "int", "void"] {
3409 let source = format!("int f({pointer} *p) {{ return __atomic_test_and_set(p, 5); }}\n");
3410 let text = body(&source);
3411 assert!(text.contains("%1 = iconst.i8 1"), "{pointer}: {text}");
3412 assert!(
3413 text.contains("%2 = atomic_rmw.i8 xchg %0, %1, align 1, seq_cst"),
3414 "{pointer}: {text}"
3415 );
3416 assert!(text.contains("%4 = icmp ne %2, %3"), "{pointer}: {text}");
3417
3418 let source = format!("void f({pointer} *p) {{ __atomic_clear(p, 3); }}\n");
3419 let text = body(&source);
3420 assert!(text.contains("atomic_store %2 -> %0, align 1, release"), "{pointer}: {text}");
3421 }
3422
3423 let text = asm("int f(int *p) { return __atomic_test_and_set(p, 5); }\n");
3426 assert!(text.contains("xchgb\t%al, (%rdi)"), "{text}");
3427 assert!(text.contains("setne\t"), "{text}");
3428 }
3429
3430 #[test]
3438 fn a_read_modify_write_is_an_exchange_or_a_locked_add_at_the_width_of_the_object() {
3439 let widths = [("char", "b", "%sil"), ("short", "w", "%si"), ("int", "l", "%esi")];
3440 for (ty, suffix, reg) in widths {
3441 let source =
3442 format!("{ty} f({ty} *p, {ty} v) {{ return __atomic_fetch_add(p, v, 5); }}\n");
3443 let text = asm(&source);
3444 assert!(text.contains("\tlock\n"), "{ty}: {text}");
3445 assert!(text.contains(&format!("xadd{suffix}\t{reg}, (%rdi)")), "{ty}: {text}");
3446
3447 let source =
3448 format!("{ty} f({ty} *p, {ty} v) {{ return __atomic_exchange_n(p, v, 5); }}\n");
3449 let text = asm(&source);
3450 assert!(text.contains(&format!("xchg{suffix}\t{reg}, (%rdi)")), "{ty}: {text}");
3451 assert!(!text.contains("\tlock\n"), "an exchange is locked already: {ty}: {text}");
3452 }
3453 let source = "long f(long *p, long v) { return __atomic_fetch_add(p, v, 5); }\n";
3454 assert!(asm(source).contains("xaddq\t%rsi, (%rdi)"), "{}", asm(source));
3455
3456 let source = "int f(int *p, int v) { return __atomic_fetch_sub(p, v, 5); }\n";
3459 let text = asm(source);
3460 assert!(text.contains("negl\t"), "{text}");
3461 assert!(text.contains("xaddl\t"), "{text}");
3462
3463 for order in ["0", "2", "3", "4", "5"] {
3466 let source =
3467 format!("int f(int *p, int v) {{ return __atomic_fetch_add(p, v, {order}); }}\n");
3468 let text = asm(&source);
3469 assert!(text.contains("xaddl\t"), "{order}: {text}");
3470 assert!(!text.contains("mfence"), "{order} needs no barrier here: {text}");
3471 }
3472
3473 let text = asm("int f(int *p, int v) { return __sync_lock_test_and_set(p, v); }\n");
3477 assert!(text.contains("xchgl\t%esi, (%rdi)"), "{text}");
3478 let text = asm("void f(int *p) { __sync_lock_release(p); }\n");
3483 assert!(text.contains("movl\t$0, %eax"), "{text}");
3484 assert!(text.contains("movl\t%eax, (%rdi)"), "{text}");
3485 assert!(!text.contains("mfence"), "a release store needs no barrier here: {text}");
3486 }
3487
3488 #[test]
3500 fn the_lock_free_questions_are_answered_as_constants() {
3501 for size in ["1", "2", "4", "8"] {
3502 let source =
3503 format!("int f(void) {{ return __atomic_always_lock_free({size}, 0); }}\n");
3504 let text = asm(&source);
3505 assert!(text.contains("movb\t$1, %al"), "{size} bytes is lock free: {text}");
3506 assert!(!text.contains("call"), "and is not a call: {text}");
3507 }
3508 for size in ["3", "16", "sizeof(long double)"] {
3509 let source = format!("int f(void) {{ return __atomic_is_lock_free({size}, 0); }}\n");
3510 let text = asm(&source);
3511 assert!(text.contains("movb\t$0, %al"), "{size} bytes is not: {text}");
3512 assert!(!text.contains("call"), "and is not a call either: {text}");
3513 }
3514
3515 let text = asm("int f(int n) { return __atomic_is_lock_free(n, 0); }\n");
3519 assert!(text.contains("movb\t$0, %al"), "a size nobody knows is not lock free: {text}");
3520 let text = asm("int f(int *p) { return __atomic_always_lock_free(8, p); }\n");
3521 assert!(text.contains("movb\t$0, %al"), "eight bytes at four is not: {text}");
3522 let text = asm("int f(long *p) { return __atomic_always_lock_free(8, p); }\n");
3523 assert!(text.contains("movb\t$1, %al"), "and at eight it is: {text}");
3524 }
3525
3526 #[test]
3538 fn a_memory_order_an_operation_cannot_carry_is_read_as_the_strongest() {
3539 let mut opts = options();
3540 opts.emit = EmitKind::Ir;
3541
3542 let acquire_store = run(&opts, "void f(int *p, int v) { __atomic_store_n(p, v, 2); }\n");
3543 assert!(acquire_store.text().contains("seq_cst"), "{:?}", acquire_store.text());
3544 assert!(acquire_store.messages[0].contains("[W0333]"), "{:?}", acquire_store.messages);
3545
3546 let nonsense = run(&opts, "int f(int *p) { return __atomic_load_n(p, 99); }\n");
3547 assert!(nonsense.text().contains("seq_cst"), "{:?}", nonsense.text());
3548 assert!(nonsense.messages[0].contains("[W0333]"), "{:?}", nonsense.messages);
3549
3550 let computed = run(&opts, "int f(int *p, int n) { return __atomic_load_n(p, n); }\n");
3551 assert!(computed.text().contains("seq_cst"), "{:?}", computed.text());
3552 assert_eq!(computed.messages, Vec::<String>::new(), "a computed order is not a mistake");
3553 }
3554
3555 #[test]
3567 fn a_conversion_between_a_float_and_the_widest_unsigned_integer_is_written_without_a_branch() {
3568 let text = asm("double f(unsigned long long x) { return (double)x; }\n");
3569 assert!(text.contains("cvtsi2sdq"), "the signed conversion is what runs: {text}");
3570 assert!(text.contains("shrq"), "with the value halved first: {text}");
3571 assert!(text.contains("addsd"), "and doubled after: {text}");
3572 assert!(!text.contains("\tj"), "and no branch anywhere: {text}");
3573
3574 let text = asm("unsigned long long f(double d) { return (unsigned long long)d; }\n");
3575 assert!(text.contains("cvttsd2siq"), "the signed conversion is what runs: {text}");
3576 assert!(text.contains("subsd"), "with half the range taken off first: {text}");
3577 assert!(text.contains("shlq\t$63"), "and the top bit put back: {text}");
3578 assert!(!text.contains("\tj"), "and no branch anywhere: {text}");
3579 }
3580
3581 #[test]
3592 fn a_plain_name_the_program_took_is_the_programs_own_function() {
3593 let taken = concat!(
3594 "static long long llabs(long long b) { return 7; }\n",
3595 "long long f(long long x) { return llabs(x); }\n",
3596 );
3597 assert!(ir(taken).contains("call @llabs"), "a static definition is the program's own");
3598
3599 let retyped = concat!("int llabs(int b);\n", "int f(int x) { return llabs(x); }\n",);
3600 assert!(ir(retyped).contains("call @llabs"), "another type is another function");
3601
3602 let plain = concat!(
3603 "long long llabs(long long b);\n",
3604 "long long f(long long x) { return llabs(x); }\n",
3605 );
3606 let mut opts = options();
3607 opts.emit = EmitKind::Ir;
3608 assert!(!run(&opts, plain).text().contains("call @llabs"), "the library's by default");
3609
3610 opts.builtins = false;
3611 assert!(run(&opts, plain).text().contains("call @llabs"), "-fno-builtin");
3612
3613 opts.builtins = true;
3614 opts.no_builtin = vec!["llabs".to_owned()];
3615 assert!(run(&opts, plain).text().contains("call @llabs"), "-fno-builtin-llabs");
3616 let one = "long labs(long b);\nlong f(long x) { return labs(x); }\n";
3617 assert!(!run(&opts, one).text().contains("call @labs"), "one name and not the family");
3618
3619 opts.no_builtin = Vec::new();
3622 opts.builtins = false;
3623 let prefixed = "long long f(long long x) { return __builtin_llabs(x); }\n";
3624 assert!(!run(&opts, prefixed).text().contains("call @llabs"), "the prefix is a promise");
3625 }
3626
3627 #[test]
3640 fn the_hint_builtins_are_their_first_argument_and_the_hint_leaves_no_trace() {
3641 let text = ir(concat!(
3642 "long a = __builtin_expect(7, 1);\n",
3643 "long b = __builtin_expect_with_probability(9, 1, 0.9);\n",
3644 "unsigned long c = sizeof(__builtin_expect((char)1, 1));\n",
3645 ));
3646 assert!(text.contains("global @a : i64 = 7,"), "{text}");
3647 assert!(text.contains("global @b : i64 = 9,"), "{text}");
3648 assert!(text.contains("global @c : i64 = 8,"), "{text}");
3649 assert!(!text.contains("__builtin_expect"), "it is not a call to anything:\n{text}");
3650
3651 let text = body("long f(char c) { return __builtin_expect(c, 1); }\n");
3654 assert!(text.contains("sext"), "{text}");
3655
3656 let one = "block0:\n %0 = iconst.i32 0\n %1 = iconst.i32 1\n %2 = sext.i64 %1\n return %0\n";
3660 assert_eq!(body("int f(void) { int i = 0; __builtin_expect(1, i++); return i; }\n"), one);
3661 let source = "int g(void) { int i = 0; __builtin_expect_with_probability(1, i++, 0.5); return i; }\n";
3662 assert_eq!(body(source), one);
3663
3664 let kept = body("int f(int n) { int i = 0; __builtin_expect(n, i++); return i; }\n");
3669 assert!(kept.contains("add.nsw"), "the hint still runs: {kept}");
3670 assert!(kept.ends_with("return %3\n"), "and the answer is what it left behind: {kept}");
3671 let both = "int g(int n) { int i = 0; __builtin_expect_with_probability(n, i++, 0.5); return i; }\n";
3672 assert!(body(both).contains("add.nsw"), "and so does the one with three arguments");
3673 }
3674
3675 #[test]
3687 fn a_promise_that_control_does_not_arrive_writes_no_instruction() {
3688 let promised = "int f(int x) { if (x) return 1; __builtin_unreachable(); }\n";
3689 let text = ir(promised);
3690 assert!(text.contains(" unreachable_hint\n"), "{text}");
3691 assert!(!text.contains("call"), "it is not a call to anything:\n{text}");
3692
3693 let after = body("int g(int x) { __builtin_unreachable(); return x; }\n");
3697 assert!(after.contains("return"), "{after}");
3698
3699 let text = asm(promised);
3702 let mine = text.split_once("\nf:\n").expect("a definition").1;
3703 let mine = mine.split_once("\t.size").expect("a definition").0;
3704 let plain = asm("int f(int x) { if (x) return 1; }\n");
3705 let plain = plain.split_once("\nf:\n").expect("a definition").1;
3706 let plain = plain.split_once("\t.size").expect("a definition").0;
3707 assert_eq!(mine, plain);
3708 let last = mine.lines().rfind(|line| !line.trim_start().starts_with('.'));
3711 assert_eq!(last.map(str::trim), Some("ret"), "{mine}");
3712 assert!(!mine.contains("ud2"), "{mine}");
3713 }
3714
3715 #[test]
3722 fn a_library_builtin_is_diagnosed_under_the_name_the_program_wrote() {
3723 let mut opts = options();
3724 opts.emit = EmitKind::Ir;
3725 let messages = run(&opts, "void f(void) { __builtin_abort(1); }\n").messages;
3726 assert!(
3727 messages.iter().any(|m| m.contains("__builtin_abort")),
3728 "expected the written name in {messages:?}"
3729 );
3730 }
3731
3732 #[test]
3740 fn a_builtin_nothing_lowers_is_refused_by_name() {
3741 let mut opts = options();
3742 opts.emit = EmitKind::Ir;
3743 for (builtin, call) in [
3744 ("__builtin_return_address", "(int)(long)__builtin_return_address(0)"),
3745 ("__builtin_alloca", "(int)(long)__builtin_alloca(8)"),
3746 ("__atomic_signal_fence", "(__atomic_signal_fence(5), 0)"),
3747 ] {
3748 let source = format!("int counter;\nint f(void) {{ return {call}; }}\n");
3749 let messages = run(&opts, &source).messages;
3750 let named = messages.iter().any(|m| m.contains(builtin) && m.contains("E0686"));
3751 assert!(named, "expected {builtin} to be refused by name in {messages:?}");
3752 }
3753 }
3754
3755 #[test]
3763 fn what_is_refused_is_the_call_and_not_the_name() {
3764 let text = ir("unsigned long n = sizeof(__builtin_return_address(0));\n");
3765 assert!(text.contains("global @n : i64 = 8,"), "{text}");
3766
3767 let text = ir(concat!(
3768 "void *__builtin_return_address(unsigned x) { return 0; }\n",
3769 "void *f(void) { return __builtin_return_address(0); }\n",
3770 ));
3771 assert!(text.contains("call @__builtin_return_address"), "{text}");
3772 }
3773
3774 #[test]
3779 fn a_static_function_nothing_refers_to_is_not_emitted() {
3780 let text = ir("static int dropped(void) { return 1; }\n\
3781 static int kept(void) { return 2; }\n\
3782 int main(void) { return kept(); }\n");
3783 assert!(text.contains("func @kept"), "{text}");
3784 assert!(!text.contains("dropped"), "{text}");
3785 }
3786
3787 #[test]
3793 fn two_static_functions_that_only_call_each_other_are_both_dropped() {
3794 let text = ir("static int ping(void);\n\
3795 static int pong(void) { return ping(); }\n\
3796 static int ping(void) { return pong(); }\n\
3797 int main(void) { return 0; }\n");
3798 assert!(!text.contains("ping"), "{text}");
3799 assert!(!text.contains("pong"), "{text}");
3800 }
3801
3802 #[test]
3808 fn naming_a_static_function_anywhere_keeps_it() {
3809 let text = ir("static int by_address(void) { return 1; }\n\
3810 static int in_an_image(void) { return 2; }\n\
3811 static int deeper(void) { return 3; }\n\
3812 static int reaches_deeper(void) { return deeper(); }\n\
3813 static int (*table[1])(void) = {in_an_image};\n\
3814 int main(void) {\n\
3815 int (*p)(void) = by_address;\n\
3816 return p() + table[0]() + reaches_deeper();\n\
3817 }\n");
3818 for kept in ["by_address", "in_an_image", "deeper", "reaches_deeper"] {
3819 assert!(text.contains(&format!("func @{kept}")), "expected {kept} in:\n{text}");
3820 }
3821 }
3822
3823 #[test]
3829 fn an_attribute_keeps_a_static_function_nothing_refers_to() {
3830 for attribute in ["used", "retain", "constructor", "destructor", "__used__"] {
3831 let source = format!(
3832 "__attribute__(({attribute})) static int kept(void) {{ return 1; }}\n\
3833 int main(void) {{ return 0; }}\n"
3834 );
3835 let text = ir(&source);
3836 assert!(text.contains("func @kept"), "for {attribute}:\n{text}");
3837 }
3838 }
3839
3840 #[test]
3843 fn a_function_anything_could_call_is_emitted_without_being_called() {
3844 let text =
3845 ir("int nobody_here_calls_it(void) { return 1; }\nint main(void) { return 0; }\n");
3846 assert!(text.contains("func @nobody_here_calls_it"), "{text}");
3847 }
3848
3849 #[test]
3856 fn a_classification_c_has_an_operator_for_is_that_operator() {
3857 for (builtin, operator) in [
3858 ("__builtin_isgreater", "binary >"),
3859 ("__builtin_isgreaterequal", "binary >="),
3860 ("__builtin_isless", "binary <"),
3861 ("__builtin_islessequal", "binary <="),
3862 ] {
3863 let source = format!("int f(double x, double y) {{ return {builtin}(x, y); }}\n");
3864 let text = tast(&source);
3865 assert!(text.contains(&format!("{operator} : int")), "for {builtin}:\n{text}");
3866 }
3867 }
3868
3869 #[test]
3878 fn the_classification_builtins_are_comparisons_and_not_calls() {
3879 let text = body("int f(double x, double y) { return __builtin_isunordered(x, y); }\n");
3880 assert_eq!(
3881 text,
3882 "block0(%0: f64, %1: f64):\n %2 = fcmp uno %0, %1\n %3 = zext.i32 \
3883 %2\n return %3\n"
3884 );
3885
3886 let text = body("int f(double x, double y) { return __builtin_islessgreater(x, y); }\n");
3888 assert!(text.contains("fcmp one %0, %1"), "{text}");
3889
3890 let text = body("int f(double x) { return __builtin_isnan(x); }\n");
3891 assert!(text.contains("fcmp uno %0, %0"), "{text}");
3892
3893 let text = body("int f(double x) { return __builtin_isinf(x); }\n");
3894 assert!(text.contains("fconst.f64 0x7ff0000000000000"), "{text}");
3895 assert!(text.contains("fconst.f64 0xfff0000000000000"), "{text}");
3896 assert!(text.contains("%3 = fcmp oeq %0, %1"), "{text}");
3897 assert!(text.contains("%4 = fcmp oeq %0, %2"), "{text}");
3898 assert!(text.contains("%5 = or %3, %4"), "{text}");
3899
3900 let text = body("int f(double x) { return __builtin_isfinite(x); }\n");
3903 assert!(text.contains("%3 = fcmp olt %2, %0"), "{text}");
3904 assert!(text.contains("%4 = fcmp olt %0, %1"), "{text}");
3905 assert!(text.contains("%5 = and %3, %4"), "{text}");
3906
3907 let text = body("int f(double x) { return __builtin_signbit(x); }\n");
3908 assert!(text.contains("%1 = bitcast.i64 %0"), "{text}");
3909 assert!(text.contains("icmp slt %1, %2"), "{text}");
3910
3911 let text = body("int f(long double x) { return __builtin_signbitl(x); }\n");
3914 assert!(text.contains("%1 = bitcast.i80 %0"), "{text}");
3915
3916 let text = body("double g(void);\nint f(void) { return __builtin_isnan(g()); }\n");
3919 assert_eq!(text.matches("call @g()").count(), 1, "{text}");
3920 }
3921
3922 #[test]
3929 fn a_classification_spelling_that_names_a_width_converts_before_it_asks() {
3930 let text = ir(concat!(
3931 "int a = __builtin_isinff(1e300);\n",
3932 "int b = __builtin_isinf(1e300);\n",
3933 "int c = __builtin_isnan(0.0);\n",
3937 "int d = __builtin_signbit(-0.0);\n",
3938 "int e = __builtin_islessgreater(1.0, 2.0);\n",
3939 ));
3940 assert!(text.contains("global @a : i32 = 1,"), "{text}");
3941 assert!(text.contains("global @b : i32 = 0,"), "{text}");
3942 assert!(text.contains("global @c : i32 = 0,"), "{text}");
3943 assert!(text.contains("global @d : i32 = 1,"), "{text}");
3944 assert!(text.contains("global @e : i32 = 1,"), "{text}");
3945 }
3946
3947 #[test]
3949 fn a_classification_builtin_refuses_an_argument_that_is_not_floating_point() {
3950 let mut opts = options();
3951 opts.emit = EmitKind::Ir;
3952 let source = concat!(
3953 "int a(int x) { return __builtin_isnan(x); }\n",
3954 "int b(int x, int y) { return __builtin_isunordered(x, y); }\n",
3955 "int c(double x) { return __builtin_isnan(x, x); }\n",
3956 );
3957 let messages = run(&opts, source).messages;
3958 assert_eq!(
3959 messages,
3960 [
3961 "/main.c:1:23: error: non-floating-point argument in call to function \
3962 '__builtin_isnan' [E0685]",
3963 "/main.c:2:30: error: non-floating-point arguments in call to function \
3964 '__builtin_isunordered' [E0685]",
3965 "/main.c:3:26: error: too many arguments to function '__builtin_isnan' [E0511]",
3966 ]
3967 );
3968 }
3969
3970 #[test]
3979 fn the_last_three_classification_builtins_are_comparisons_and_not_calls() {
3980 let text = body("int f(double x) { return __builtin_isnormal(x); }\n");
3981 assert!(text.contains("%1 = bitcast.i64 %0"), "{text}");
3985 assert!(text.contains("%2 = iconst.i64 9223372036854775807"), "{text}");
3986 assert!(text.contains("%3 = and %1, %2"), "{text}");
3987 assert!(text.contains("%4 = iconst.i64 4503599627370496"), "{text}");
3988 assert!(text.contains("%5 = iconst.i64 9218868437227405312"), "{text}");
3989 assert!(text.contains("%6 = icmp uge %3, %4"), "{text}");
3990 assert!(text.contains("%7 = icmp ult %3, %5"), "{text}");
3991 assert!(text.contains("%8 = and %6, %7"), "{text}");
3992
3993 let text = body("int f(long double x) { return __builtin_isnormal(x); }\n");
3997 assert!(text.contains("%4 = iconst.i80 27670116110564327424"), "{text}");
3998 assert!(text.contains("%5 = iconst.i80 604453686435277732577280"), "{text}");
3999
4000 let text = body("int f(double x) { return __builtin_isinf_sign(x); }\n");
4001 assert!(text.contains("%3 = fcmp oeq %0, %1"), "{text}");
4002 assert!(text.contains("%4 = fcmp oeq %0, %2"), "{text}");
4003 assert!(text.contains("%7 = sub %5, %6"), "{text}");
4004
4005 let text = body("int f(double x) { return __builtin_fpclassify(0, 1, 2, 3, 4, x); }\n");
4006 assert!(text.contains("fcmp uno %0, %0"), "{text}");
4007 assert!(text.contains("fcmp oeq %0, %6"), "{text}");
4008 assert_eq!(text.matches(" = zext.i32 ").count(), 4, "{text}");
4012 assert_eq!(text.matches(" = xor ").count(), 4, "{text}");
4013 assert!(!text.contains("call"), "{text}");
4014
4015 let text = body(concat!(
4018 "double g(void);\n",
4019 "int f(void) { return __builtin_fpclassify(0, 1, 2, 3, 4, g()); }\n",
4020 ));
4021 assert_eq!(text.matches("call @g()").count(), 1, "{text}");
4022 }
4023
4024 #[test]
4031 fn the_last_three_classification_builtins_fold_where_their_operand_is_a_constant() {
4032 let text = ir(concat!(
4033 "int a = __builtin_isnormal(1.0);\n",
4034 "int b = __builtin_isnormal(0.0);\n",
4035 "int c = __builtin_isnormal(1.0 / 0.0);\n",
4036 "int d = __builtin_isinf_sign(-1.0 / 0.0);\n",
4037 "int e = __builtin_isinf_sign(1.0);\n",
4038 "int g = __builtin_fpclassify(0, 1, 2, 3, 4, 0.0);\n",
4039 "int h = __builtin_fpclassify(0, 1, 2, 3, 4, 1.0);\n",
4040 "int i = __builtin_fpclassify(0, 1, 2, 3, 4, 1.0 / 0.0);\n",
4041 ));
4042 assert!(text.contains("global @a : i32 = 1,"), "{text}");
4043 assert!(text.contains("global @b : i32 = 0,"), "{text}");
4044 assert!(text.contains("global @c : i32 = 0,"), "{text}");
4045 assert!(text.contains("global @d : i32 = -1,"), "{text}");
4046 assert!(text.contains("global @e : i32 = 0,"), "{text}");
4047 assert!(text.contains("global @g : i32 = 4,"), "{text}");
4048 assert!(text.contains("global @h : i32 = 2,"), "{text}");
4049 assert!(text.contains("global @i : i32 = 1,"), "{text}");
4050 }
4051
4052 #[test]
4058 fn fpclassify_refuses_an_answer_that_is_not_an_integer_constant() {
4059 let mut opts = options();
4060 opts.emit = EmitKind::Ir;
4061 let source = concat!(
4062 "int a(double x, int n) { return __builtin_fpclassify(0, 1, n, 3, 4, x); }\n",
4063 "int b(double x) { return __builtin_fpclassify(0, 1, 2, 3, x); }\n",
4064 "int c(int x) { return __builtin_fpclassify(0, 1, 2, 3, 4, x); }\n",
4065 );
4066 let messages = run(&opts, source).messages;
4067 assert_eq!(
4068 messages,
4069 [
4070 "/main.c:1:60: error: non-const integer argument 3 in call to function \
4071 '__builtin_fpclassify' [E0687]",
4072 "/main.c:2:26: error: too few arguments to function '__builtin_fpclassify' \
4073 [E0511]",
4074 "/main.c:3:23: error: non-floating-point argument in call to function \
4075 '__builtin_fpclassify' [E0685]",
4076 ]
4077 );
4078 }
4079
4080 #[test]
4088 fn a_builtin_whose_answer_is_a_constant_is_one_and_not_a_call() {
4089 let text = ir(concat!(
4090 "double a = __builtin_inf();\n",
4091 "float b = __builtin_huge_valf();\n",
4092 "long double c = __builtin_infl();\n",
4093 "double d = __builtin_huge_val();\n",
4094 ));
4095 assert!(text.contains("global @a : f64 = 0x7ff0000000000000,"), "{text}");
4096 assert!(text.contains("global @b : f32 = 0x7f800000,"), "{text}");
4097 assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
4098 assert!(text.contains("global @d : f64 = 0x7ff0000000000000,"), "{text}");
4099 assert!(!text.contains("call"), "{text}");
4100 }
4101
4102 #[test]
4111 fn a_nan_is_written_with_the_payload_the_program_asked_for() {
4112 let text = ir(concat!(
4113 "double a = __builtin_nan(\"\");\n",
4114 "double b = __builtin_nan(\"0x1\");\n",
4115 "double c = __builtin_nan(\"010\");\n",
4117 "double d = __builtin_nans(\"\");\n",
4118 "double e = __builtin_nans(\"0x1\");\n",
4119 "float f = __builtin_nanf(\"0x1\");\n",
4120 "float g = __builtin_nansf(\"\");\n",
4121 "long double h = __builtin_nansl(\"\");\n",
4122 ));
4123 assert!(text.contains("global @a : f64 = 0x7ff8000000000000,"), "{text}");
4124 assert!(text.contains("global @b : f64 = 0x7ff8000000000001,"), "{text}");
4125 assert!(text.contains("global @c : f64 = 0x7ff8000000000008,"), "{text}");
4126 assert!(text.contains("global @d : f64 = 0x7ff4000000000000,"), "{text}");
4127 assert!(text.contains("global @e : f64 = 0x7ff0000000000001,"), "{text}");
4128 assert!(text.contains("global @f : f32 = 0x7fc00001,"), "{text}");
4129 assert!(text.contains("global @g : f32 = 0x7fa00000,"), "{text}");
4130 assert!(text.contains("f80 0x7fffa000000000000000"), "{text}");
4131
4132 let text = ir(concat!(
4135 "double f(const char *p) { return __builtin_nan(p); }\n",
4136 "double g(void) { return __builtin_nans(\"1x\"); }\n",
4137 ));
4138 assert_eq!(text.matches("call @nan(").count(), 1, "{text}");
4139 assert_eq!(text.matches("call @nans(").count(), 1, "{text}");
4140 }
4141
4142 #[test]
4150 fn the_length_and_the_order_of_a_string_literal_are_known_here() {
4151 let text = ir(concat!(
4152 "unsigned long a = __builtin_strlen(\"hello\");\n",
4153 "unsigned long b = __builtin_strlen(\"a\\0bc\");\n",
4154 "int c = __builtin_strcmp(\"X\", \"X\\376\") < 0;\n",
4155 "int d = __builtin_strcmp(\"abc\", \"abc\");\n",
4156 "int e = __builtin_strcmp(\"abc\", \"ab\") > 0;\n",
4157 ));
4158 assert!(text.contains("global @a : i64 = 5,"), "{text}");
4159 assert!(text.contains("global @b : i64 = 1,"), "{text}");
4160 assert!(text.contains("global @c : i32 = 1,"), "{text}");
4161 assert!(text.contains("global @d : i32 = 0,"), "{text}");
4162 assert!(text.contains("global @e : i32 = 1,"), "{text}");
4163 assert!(!text.contains("call"), "{text}");
4164
4165 let text = ir("unsigned long f(const char *p) { return __builtin_strlen(p); }\n");
4167 assert!(text.contains("call @strlen("), "{text}");
4168 }
4169
4170 #[test]
4177 fn a_sign_builtin_is_a_mask_over_the_bits_and_not_a_call() {
4178 let text = body("double f(double x) { return __builtin_fabs(x); }\n");
4179 assert!(text.contains("bitcast.i64 %0"), "{text}");
4180 assert!(text.contains("iconst.i64 9223372036854775807"), "{text}");
4181 assert!(text.contains("and %1, %2"), "{text}");
4182 assert!(text.contains("bitcast.f64 %3"), "{text}");
4183 assert!(!text.contains("call"), "{text}");
4184
4185 let text = body("double f(double x, double y) { return __builtin_copysign(x, y); }\n");
4186 assert!(text.contains("iconst.i64 -9223372036854775808"), "{text}");
4187 assert!(text.contains("%8 = or %4, %7"), "{text}");
4188 assert!(!text.contains("call"), "{text}");
4189
4190 let text = body("long double f(long double x) { return __builtin_fabsl(x); }\n");
4193 assert!(text.contains("bitcast.i80 %0"), "{text}");
4194 assert!(text.contains("bitcast.f80"), "{text}");
4195
4196 let text = body("double f(float x) { return __builtin_fabs(x); }\n");
4199 assert!(text.contains("fpext.f64 %0"), "{text}");
4200 assert!(text.contains("bitcast.i64 %1"), "{text}");
4201 }
4202
4203 #[test]
4212 fn the_sign_builtins_answer_a_zero_and_a_nan_the_way_the_bits_say() {
4213 let text = ir(concat!(
4214 "double a = __builtin_fabs(-3.5);\n",
4215 "double b = __builtin_copysign(1.0, -0.0);\n",
4216 "double c = __builtin_copysign(0.0, -2.0);\n",
4217 "double d = __builtin_copysign(-__builtin_nan(\"\"), 1.0);\n",
4219 "double e = __builtin_fabs(-__builtin_nan(\"0x1\"));\n",
4220 "float g = __builtin_copysignf(-0.0f, 2.0f);\n",
4221 "long double h = __builtin_copysignl(1.0L, -1.0L);\n",
4222 "long double i = __builtin_fabsl(-__builtin_infl());\n",
4223 ));
4224 assert!(text.contains("global @a : f64 = 0x400c000000000000,"), "{text}");
4225 assert!(text.contains("global @b : f64 = 0xbff0000000000000,"), "{text}");
4226 assert!(text.contains("global @c : f64 = 0x8000000000000000,"), "{text}");
4227 assert!(text.contains("global @d : f64 = 0x7ff8000000000000,"), "{text}");
4228 assert!(text.contains("global @e : f64 = 0x7ff8000000000001,"), "{text}");
4229 assert!(text.contains("global @g : f32 = 0x0,"), "{text}");
4230 assert!(text.contains("f80 0xbfff8000000000000000"), "{text}");
4231 assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
4232 }
4233
4234 #[test]
4241 fn a_constexpr_object_is_a_constant_wherever_one_is_required() {
4242 let text = ir(concat!(
4243 "constexpr int side = 4;\n",
4244 "constexpr int wider = side + 1;\n",
4245 "constexpr double half = 1.5;\n",
4246 "struct point { int x; int y; };\n",
4247 "constexpr struct point origin = { 5, 6 };\n",
4248 "int square[side * side];\n",
4249 "int rectangle[wider];\n",
4250 "int rounded[(int)half * 2];\n",
4251 "int across[origin.y];\n",
4252 "enum named { four = side };\n",
4253 "int e = four;\n",
4254 ));
4255 assert!(text.contains("global @square : bytes 64 ="), "{text}");
4256 assert!(text.contains("global @rectangle : bytes 20 ="), "{text}");
4257 assert!(text.contains("global @rounded : bytes 8 ="), "{text}");
4258 assert!(text.contains("global @across : bytes 24 ="), "{text}");
4259 assert!(text.contains("global @e : i32 = 4,"), "{text}");
4260
4261 let mut opts = options();
4264 opts.emit = EmitKind::Ir;
4265 let konst = "const int n = 1;\nint a[n];\n";
4266 let message = "/main.c:2:5: error: variably modified 'a' at file scope [E0538]";
4267 assert_eq!(run(&opts, konst).messages, [message]);
4268
4269 let subscript = "constexpr int t[3] = { 1, 2, 3 };\nint a[t[1]];\n";
4271 assert_eq!(run(&opts, subscript).messages, [message]);
4272
4273 let address = "constexpr int c = 3;\nint *p = &c;\n";
4275 let warning = "/main.c:2:6: warning: initialization discards 'const' qualifier from \
4276 pointer target type [E0514]";
4277 assert_eq!(run(&opts, address).messages, [warning]);
4278 }
4279
4280 #[test]
4289 fn an_old_style_definition_takes_its_types_from_the_declarations_under_its_list() {
4290 let mut opts = options();
4293 opts.std = Std::C17;
4294 let source = concat!(
4295 "int add(a, b)\n",
4296 "int a;\n",
4297 "int b;\n",
4298 "{ return a + b; }\n",
4299 "int promoted(c)\n",
4300 "char c;\n",
4301 "{ return c; }\n",
4302 "int narrow(char);\n",
4303 "int narrow(c)\n",
4304 "char c;\n",
4305 "{ return c; }\n",
4306 "int first(a)\n",
4307 "int a[4];\n",
4308 "{ return a[0]; }\n",
4309 );
4310 let result = run(&opts, source);
4311 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
4312 let text = result.text();
4313 assert!(text.contains("add : int(int, int) function external defined"), "{text}");
4314 assert!(text.contains("promoted : int(int) function external defined"), "{text}");
4315 assert!(text.contains("c : char object automatic defined"), "{text}");
4317 assert!(text.contains("narrow : int(char) function external defined"), "{text}");
4318 assert!(text.contains("first : int(int *) function external defined"), "{text}");
4320 }
4321
4322 #[test]
4329 fn the_two_halves_of_an_old_style_parameter_list_have_to_agree() {
4330 let mut opts = options();
4331 opts.std = Std::C17;
4332 for (source, message) in [
4333 ("int f(a, a)\nint a;\n{ return a; }\n", "1:10: error: multiple parameters named 'a'"),
4334 (
4335 "int f(a)\nint a;\nint b;\n{ return a; }\n",
4336 "3:5: error: declaration for parameter 'b' but no such parameter",
4337 ),
4338 ("int f(a)\nint a;\nint a;\n{ return a; }\n", "3:5: error: redefinition of parameter"),
4339 ("int f(a)\nint a = 1;\n{ return a; }\n", "2:5: error: parameter 'a' is initialized"),
4340 (
4341 "int f(a)\nstatic int a;\n{ return a; }\n",
4342 "2:12: error: storage class specified for parameter 'a'",
4343 ),
4344 (
4345 "int f(char);\nint f(a)\nshort a;\n{ return a; }\n",
4346 "2:7: error: argument 'a' doesn't match prototype",
4347 ),
4348 ] {
4349 let result = run(&opts, source);
4350 assert!(result.failed(), "expected this to fail:\n{source}");
4351 assert!(result.messages[0].contains(message), "{:?}", result.messages);
4352 }
4353
4354 let implicit = "int f(a, b)\nint a;\n{ return a + b; }\n";
4357 let mut older = options();
4358 older.std = Std::C89;
4359 assert!(!run(&older, implicit).failed(), "{:?}", run(&older, implicit).messages);
4360 let result = run(&opts, implicit);
4361 assert!(
4362 result.messages[0].contains("1:10: error: type of 'b' defaults to 'int'"),
4363 "{:?}",
4364 result.messages
4365 );
4366
4367 let mut newer = options();
4371 newer.std = Std::C23;
4372 let plain = "int f(a)\nint a;\n{ return a; }\n";
4373 let result = run(&newer, plain);
4374 assert!(!result.failed(), "{:?}", result.messages);
4375 assert_eq!(
4376 result.messages,
4377 ["/main.c:1:5: warning: old-style function definition [E0412]"]
4378 );
4379 assert!(run(&opts, plain).messages.is_empty(), "and nothing to say in the dialects before");
4380 }
4381
4382 #[test]
4389 fn the_obsolete_designators_are_taken_and_are_pedantic_warnings() {
4390 let array = "int a[8] = { [3] 7 };\n";
4391 let member = "struct s { int x; } v = { x: 7 };\n";
4392 for source in [array, member] {
4393 let result = run(&options(), source);
4394 assert!(!result.failed(), "{:?}", result.messages);
4395 assert!(result.messages.is_empty(), "nothing to say: {:?}", result.messages);
4396 }
4397
4398 let mut asked = options();
4399 asked.pedantic = true;
4400 assert_eq!(
4401 run(&asked, array).messages,
4402 ["/main.c:1:18: warning: obsolete designator, write `[i] =` instead [E0415]"]
4403 );
4404 assert_eq!(
4405 run(&asked, member).messages,
4406 ["/main.c:1:27: warning: obsolete designator, write `.field =` instead [E0413]"]
4407 );
4408 }
4409
4410 #[test]
4417 fn a_type_is_refused_when_it_passes_the_largest_object_and_not_before() {
4418 let text = ir(concat!(
4419 "struct huge_struct { short buf[(1L << 62) - 256]; int a, b, c, d; };\n",
4420 "struct brim { char buf[9223372036854775807L]; };\n",
4421 "struct bitty { char buf[9223372036854775800L]; int x : 1; };\n",
4422 "unsigned long h = sizeof(struct huge_struct);\n",
4423 "unsigned long b = sizeof(struct brim);\n",
4424 "unsigned long y = sizeof(struct bitty);\n",
4425 ));
4426 assert!(text.contains("global @h : i64 = 9223372036854775312,"), "{text}");
4427 assert!(text.contains("global @b : i64 = 9223372036854775807,"), "{text}");
4428 assert!(text.contains("global @y : i64 = 9223372036854775804,"), "{text}");
4429
4430 let mut opts = options();
4431 opts.emit = EmitKind::Ir;
4432 let over = "struct over { char buf[9223372036854775800L]; char x[8]; };\n";
4433 let message = "/main.c:1:1: error: type 'struct over' is too large [E0560]";
4434 assert_eq!(run(&opts, over).messages, [message]);
4435 let array = "struct wide { short buf[1L << 62]; };\n";
4436 let message = "/main.c:1:25: error: size of array 'buf' exceeds \
4437 maximum object size '9223372036854775807' [E0537]";
4438 assert_eq!(run(&opts, array).messages[0], message);
4439 }
4440
4441 fn compile_bytes(source: &[u8]) -> Compiled {
4446 let mut opts = options();
4447 opts.emit = EmitKind::Ir;
4448 let mut fs = MemoryFileSystem::new();
4449 fs.insert("/main.c", source.to_vec());
4450 compile(&opts, "/main.c", &fs)
4451 }
4452
4453 #[test]
4460 fn a_byte_that_is_not_a_character_is_kept_in_a_literal_and_refused_outside_one() {
4461 let mut source = b"char s[] = \"a".to_vec();
4462 source.push(0xff);
4463 source.extend_from_slice(b"b\";\nchar c = '");
4464 source.push(0xff);
4465 source.extend_from_slice(b"';\n");
4466 let result = compile_bytes(&source);
4467 assert_eq!(result.messages, Vec::<String>::new(), "a raw byte in a literal is that byte");
4468 assert!(result.text().contains(r#"bytes "a\ffb\00""#), "{}", result.text());
4469 assert!(result.text().contains("global @c : i8 = -1,"), "{}", result.text());
4471
4472 let mut stray = b"int a".to_vec();
4473 stray.push(0xff);
4474 stray.extend_from_slice(b" = 1;\n");
4475 let result = compile_bytes(&stray);
4476 assert!(
4477 result.messages.iter().any(|m| m.contains("source is not valid UTF-8 here")),
4478 "{:?}",
4479 result.messages
4480 );
4481 }
4482
4483 #[test]
4484 fn an_object_becomes_a_global_with_an_image_and_a_function_becomes_a_func() {
4485 let text = ir("int x = 7;\nint add(int a, int b) { return a + b; }\n");
4486 assert!(text.contains("global @x : i32 = 7, align 4, linkage(external)\n"), "{text}");
4487 let expected = "\
4488func @add(i32, i32) -> i32, linkage(external) {
4489block0(%0: i32, %1: i32):
4490 %2 = add.nsw %0, %1
4491 return %2
4492}
4493";
4494 assert!(text.contains(expected), "{text}");
4495 }
4496
4497 #[test]
4498 fn a_local_nothing_takes_the_address_of_is_a_value_and_never_a_stack_slot() {
4499 let text = body("int f(int n) { int a = n + 1; int b = a * 2; return a + b; }\n");
4500 assert!(!text.contains("alloca"), "{text}");
4501 assert!(!text.contains("load"), "{text}");
4502 assert!(!text.contains("store"), "{text}");
4503 }
4504
4505 #[test]
4506 fn a_local_whose_address_is_taken_gets_a_slot_in_the_entry_block() {
4507 let text = body("int g(int *);\nint f(void) { int a = 1; return g(&a); }\n");
4508 let expected = "\
4509block0:
4510 %0 = alloca, size 4, align 4
4511 %1 = iconst.i32 1
4512 store %1 -> %0, align 4
4513 %2 = call @g(%0) : (ptr) -> i32
4514 return %2
4515";
4516 assert_eq!(text, expected);
4517 }
4518
4519 #[test]
4520 fn a_loop_carries_what_it_changes_as_block_parameters() {
4521 let text = body(
4524 "int f(int n) {\n int total = 0;\n for (int i = 0; i < n; i++) total += i;\n \
4525 return total;\n}\n",
4526 );
4527 assert!(!text.contains("alloca"), "{text}");
4528 assert!(text.contains("block1(%3: i32, %4: i32):"), "{text}");
4529 assert!(text.contains("jump block1("), "{text}");
4530 }
4531
4532 #[test]
4533 fn a_comparison_used_as_a_condition_is_not_widened_and_narrowed_again() {
4534 let text = body("int f(int a, int b) { if (a < b) return 1; return 0; }\n");
4535 assert!(text.contains("icmp slt %0, %1"), "{text}");
4536 assert!(!text.contains("zext"), "{text}");
4537 }
4538
4539 #[test]
4540 fn the_right_side_of_a_short_circuit_is_in_a_block_of_its_own() {
4541 let text = body("int f(int a, int b) { return a && b; }\n");
4542 let expected = "\
4543block0(%0: i32, %1: i32):
4544 %2 = iconst.i32 0
4545 %3 = icmp ne %0, %2
4546 %4 = iconst.i1 0
4547 br_if %3, block1, block2(%4)
4548
4549block1:
4550 %5 = iconst.i32 0
4551 %6 = icmp ne %1, %5
4552 jump block2(%6)
4553
4554block2(%7: i1):
4555 %8 = zext.i32 %7
4556 return %8
4557";
4558 assert_eq!(text, expected);
4559 }
4560
4561 #[test]
4562 fn code_after_a_return_is_not_built_and_does_not_leave_an_empty_block_behind() {
4563 let text = body("int f(int a) { if (a) return 1; else return 2; return 3; }\n");
4564 assert!(!text.contains("block3"), "{text}");
4567 assert!(!text.contains("iconst.i32 3"), "{text}");
4568 }
4569
4570 #[test]
4571 fn falling_off_the_end_returns_zero_from_main_and_nothing_from_a_void_function() {
4572 assert!(body("int main(void) { }\n").contains("iconst.i32 0\n return"));
4573 assert_eq!(body("void f(void) { }\n"), "block0:\n return\n");
4574 assert!(body("int f(void) { }\n").contains("unreachable"));
4575 }
4576
4577 #[test]
4578 fn a_structure_is_copied_rather_than_held_in_a_value() {
4579 let text = body(
4580 "struct point { int x, y; };\n\
4581 int f(void) { struct point p = { 1, 2 }; struct point q = p; return q.x; }\n",
4582 );
4583 assert!(text.contains("memcpy"), "{text}");
4584 }
4585
4586 #[test]
4587 fn an_initializer_that_leaves_part_of_an_object_unwritten_zeroes_it_first() {
4588 let text = body("int f(void) { int a[4] = { 1 }; return a[3]; }\n");
4589 assert!(text.contains("memset"), "{text}");
4590 }
4591
4592 #[test]
4593 fn a_switch_is_one_branch_and_a_case_that_falls_through_carries_what_it_wrote() {
4594 let text = body(
4595 "int f(int x) { int r = 0; switch (x) { case 1: r = 1; case 2: r += 2; break; \
4596 default: r = 4; } return r; }\n",
4597 );
4598 let expected = "\
4599block0(%0: i32):
4600 %1 = iconst.i32 0
4601 switch %0, block1, [1 => block2, 2 => block3(%1)]
4602
4603block1:
4604 %2 = iconst.i32 4
4605 jump block4(%2)
4606
4607block2:
4608 %3 = iconst.i32 1
4609 jump block3(%3)
4610
4611block3(%4: i32):
4612 %5 = iconst.i32 2
4613 %6 = add.nsw %4, %5
4614 jump block4(%6)
4615
4616block4(%7: i32):
4617 return %7
4618";
4619 assert_eq!(text, expected);
4620 }
4621
4622 #[test]
4623 fn a_case_range_is_tested_for_rather_than_put_in_the_table() {
4624 let text = body("int f(int x) { switch (x) { case 1 ... 9: return 1; } return 0; }\n");
4627 assert!(text.contains("%2 = sub %0, %1"), "{text}");
4628 assert!(text.contains("icmp ule"), "{text}");
4629 assert!(!text.contains("switch"), "{text}");
4630 }
4631
4632 #[test]
4633 fn break_leaves_the_switch_and_continue_leaves_the_loop_around_it() {
4634 let text = body(
4635 "int f(int n) { int t = 0; for (int i = 0; i < n; i++) { switch (i) { \
4636 case 0: continue; case 1: break; default: t += i; } t++; } return t; }\n",
4637 );
4638 assert!(text.contains("switch %3, block4, [0 => block5, 1 => block6]"), "{text}");
4641 assert!(text.contains("block5:\n jump block7("), "{text}");
4642 assert!(text.contains("block6:\n jump block8("), "{text}");
4643 }
4644
4645 #[test]
4646 fn a_switch_with_nothing_to_branch_on_still_runs_what_comes_after_it() {
4647 assert_eq!(body("void f(int x) { switch (x) { } }\n"), "block0(%0: i32):\n return\n");
4648 }
4649
4650 #[test]
4651 fn a_label_a_loop_is_only_entered_through_builds_the_loop_around_it() {
4652 let text = body(
4657 "int f(int x, int n) { switch (x) { case 1: break; while (n) { case 2: n--; } } \
4658 return n; }\n",
4659 );
4660 assert!(text.contains("switch %0, block1(%1), [1 => block2, 2 => block3(%1)]"), "{text}");
4663 assert!(text.contains("block3(%3: i32):\n %4 = iconst.i32 1"), "{text}");
4664 assert!(text.contains("block4:\n jump block3("), "{text}");
4665 }
4666
4667 #[test]
4668 fn a_goto_into_a_loop_body_enters_it_without_the_test() {
4669 let text = body("int f(int x, int n) { goto in; while (n) { in: n--; } return n; }\n");
4672 assert!(text.starts_with("block0(%0: i32, %1: i32):\n jump block1(%1)"), "{text}");
4673 assert!(text.contains("block1(%2: i32):\n %3 = iconst.i32 1"), "{text}");
4674 assert!(text.contains("br_if %6, block2, block3"), "{text}");
4675 }
4676
4677 #[test]
4678 fn a_goto_is_a_jump_to_the_block_the_label_starts() {
4679 let text = body("int f(int x) { int r = 0; if (x) goto out; r = 1; out: return r; }\n");
4680 assert!(!text.contains("alloca"), "{text}");
4684 assert!(text.contains("block2(%4: i32):\n return %4"), "{text}");
4685 assert_eq!(text.matches("jump block2(").count(), 2, "{text}");
4686 }
4687
4688 #[test]
4689 fn a_backward_goto_is_a_loop_and_carries_what_it_changes() {
4690 let text =
4691 body("int f(int n) { int i = 0; again: if (i < n) { i++; goto again; } return i; }\n");
4692 assert!(!text.contains("alloca"), "{text}");
4693 assert!(text.contains("block1(%2: i32):"), "{text}");
4694 assert!(text.contains("jump block1(%5)"), "{text}");
4695 }
4696
4697 #[test]
4698 fn a_label_nothing_reaches_is_taken_out_rather_than_left_for_the_verifier() {
4699 assert_eq!(
4702 body("int f(int x) { return x; spare: return 0; }\n"),
4703 "block0(%0: i32):\n return %0\n"
4704 );
4705 }
4706
4707 #[test]
4708 fn a_bit_field_is_read_by_loading_the_bytes_it_lies_in_and_shifting() {
4709 let text = body(
4710 "struct s { unsigned a : 3; signed b : 5; };\nint f(struct s *p) { return p->b; }\n",
4711 );
4712 assert_eq!(
4715 text,
4716 "\
4717block0(%0: ptr):
4718 %1 = load.i8 %0, align 1
4719 %2 = iconst.i8 3
4720 %3 = ashr %1, %2
4721 %4 = sext.i32 %3
4722 return %4
4723"
4724 );
4725 }
4726
4727 #[test]
4728 fn a_store_to_a_bit_field_does_not_write_a_byte_it_has_no_bit_in() {
4729 let text =
4733 body("struct s { int a : 24; char c; };\nvoid f(struct s *p, int v) { p->a = v; }\n");
4734 assert_eq!(
4735 text,
4736 "\
4737block0(%0: ptr, %1: i32):
4738 %2 = iconst.i32 16777215
4739 %3 = and %1, %2
4740 %4 = trunc.i16 %3
4741 store %4 -> %0, align 2
4742 %5 = iconst.i32 16
4743 %6 = lshr %3, %5
4744 %7 = trunc.i8 %6
4745 %8 = iconst.i64 2
4746 %9 = ptr_add %0, %8
4747 store %7 -> %9, align 1
4748 return
4749"
4750 );
4751 }
4752
4753 #[test]
4754 fn what_an_assignment_to_a_bit_field_is_worth_is_what_fits_in_it() {
4755 let text =
4756 body("struct s { unsigned b : 5; };\nunsigned f(struct s *p) { return p->b = 33; }\n");
4757 assert!(text.contains("%3 = iconst.i8 31\n %4 = and %2, %3"), "{text}");
4760 assert!(text.ends_with("%9 = zext.i32 %4\n return %9\n"), "{text}");
4761 }
4762
4763 #[test]
4764 fn an_assignment_a_statement_throws_away_builds_none_of_what_it_is_worth() {
4765 let text = body("struct s { signed b : 5; };\nvoid f(struct s *p) { p->b = 3; }\n");
4768 assert_eq!(text.matches("ashr").count(), 0, "{text}");
4769 assert!(text.ends_with("store %8 -> %0, align 1\n return\n"), "{text}");
4770 }
4771
4772 #[test]
4773 fn a_bit_field_in_an_initializer_goes_in_over_bytes_that_were_zeroed_first() {
4774 let text = body(
4778 "struct s { int a : 3; int b; };\nint f(void) { struct s v = { 1 }; return v.b; }\n",
4779 );
4780 assert!(text.contains("memset %0, %1, size 8, align 4"), "{text}");
4781 }
4782
4783 #[test]
4784 fn the_image_of_a_static_bit_field_is_the_bytes_the_fields_share() {
4785 let text = ir("struct s { unsigned a : 3; unsigned b : 5; } g = { 1, 2 };\n");
4788 assert!(
4789 text.contains("global @g : bytes 4 = { bytes \"\\11\", zero 3 }, align 4"),
4790 "{text}"
4791 );
4792 }
4793
4794 #[test]
4795 fn an_initialized_flexible_array_member_makes_the_object_larger_than_its_type() {
4796 let text = ir(concat!(
4801 "struct a { int i; int j[]; } x = { 1, { 2, 0, 2, 3 } };\n",
4802 "struct b { char c; char p[]; } y = { 'o', \"wx\" };\n",
4803 "struct c { char c; char p[]; } z = { '9', { 'e', 'b' } };\n",
4804 "char s[2] = \"hi\";\n",
4805 ));
4806 assert!(
4807 text.contains("global @x : bytes 20 = { i32 1, i32 2, i32 0, i32 2, i32 3 }"),
4808 "{text}"
4809 );
4810 assert!(text.contains("global @y : bytes 4 = { i8 111, bytes \"wx\\00\" }"), "{text}");
4811 assert!(text.contains("global @z : bytes 3 = { i8 57, i8 101, i8 98 }"), "{text}");
4812 assert!(text.contains("global @s : bytes 2 = { bytes \"hi\" }"), "{text}");
4815 }
4816
4817 #[test]
4818 fn a_definition_takes_a_parameter_it_left_unnamed() {
4819 let text = ir("int f(int a, int) { return a; }\n");
4823 assert!(text.contains("func @f(i32, i32) -> i32"), "{text}");
4824 assert!(text.contains("block0(%0: i32, %1: i32):"), "{text}");
4825
4826 let text = ir("int g(int, int n) { return n; }\n");
4829 assert!(text.contains("block0(%0: i32, %1: i32):\n return %1\n"), "{text}");
4830 }
4831
4832 #[test]
4833 fn an_assignment_of_a_structure_is_the_object_it_wrote() {
4834 let text = body(concat!(
4839 "struct s { int f; int g; };\n",
4840 "void h(struct s *a, struct s *c, struct s *d, struct s *e)\n",
4841 "{ *d = *e = a[0] = *c; }\n",
4842 ));
4843 assert_eq!(text.matches("memcpy").count(), 3, "{text}");
4844 assert!(text.contains("memcpy %8, %1, size 8, align 4\n"), "{text}");
4845 assert!(text.contains("memcpy %3, %8, size 8, align 4\n"), "{text}");
4846 assert!(text.contains("memcpy %2, %3, size 8, align 4\n"), "{text}");
4847 }
4848
4849 #[test]
4850 fn a_string_literal_stops_at_the_end_of_the_array_it_is_filling() {
4851 let mut opts = options();
4856 opts.emit = EmitKind::Ir;
4857 let result = run(
4858 &opts,
4859 concat!(
4860 "const char a[2][3] = { \"1234\", \"xyz\" };\n",
4861 "static const char b[3][5] = { \"12345\", \"678\", \"9\" };\n",
4862 "union u { struct { char x[4]; char y[4]; }; struct { char z[8]; }; };\n",
4863 "const union u c = { { \"1234\", \"567\" } };\n",
4864 ),
4865 );
4866 let text = result.text();
4867 assert_eq!(
4868 result.messages,
4869 ["/main.c:1:24: warning: initializer-string for array of 'const char' is too long \
4870 (5 chars into 3 available) [E0637]"]
4871 );
4872 assert!(text.contains("global @a : bytes 6 = { bytes \"123\", bytes \"xyz\" }"), "{text}");
4873 assert!(
4874 text.contains(
4875 "global @b : bytes 15 = { bytes \"12345\", bytes \"678\\00\", zero 1, \
4876 bytes \"9\\00\", zero 3 }"
4877 ),
4878 "{text}"
4879 );
4880 assert!(
4883 text.contains("global @c : bytes 8 = { bytes \"1234\", bytes \"567\\00\" }"),
4884 "{text}"
4885 );
4886 }
4887
4888 #[test]
4889 fn a_cast_of_a_record_to_its_own_type_is_the_object_that_was_cast() {
4890 let text = body(concat!(
4894 "struct s { int a, b; };\nstruct v { struct s s; int t; };\n",
4895 "void g(struct v *);\n",
4896 "void f(struct s *p) { struct v w = { (struct s)*p, 5 }; g(&w); }\n",
4897 ));
4898 assert_eq!(text.matches("memcpy").count(), 1, "{text}");
4899 }
4900
4901 #[test]
4902 fn a_compound_literal_read_in_a_static_initializer_lays_its_bytes_into_the_image() {
4903 let text = ir(concat!(
4908 "struct s { int x; };\n",
4909 "struct t { struct s s; int o; } a = { (struct s){ 2 }, 3 };\n",
4910 "int n = (int){ 7 };\n",
4911 "struct u { struct s p; struct s q; } b = { (struct s){ 1 }, (struct s){ } };\n",
4912 ));
4913 assert!(text.contains("global @a : bytes 8 = { i32 2, i32 3 }"), "{text}");
4914 assert!(text.contains("global @n : i32 = 7,"), "{text}");
4915 assert!(text.contains("global @b : bytes 8 = { i32 1, zero 4 }"), "{text}");
4918 }
4919
4920 #[test]
4921 fn the_address_of_a_compound_literal_asks_for_the_object_it_points_at() {
4922 let text = ir("struct s { int x; };\nstruct s *q = &(struct s){ 9 };\n");
4926 assert!(text.contains("global @.Lanon.0 : i32 = 9, align 4, linkage(internal)"), "{text}");
4927 assert!(text.contains("global @q : bytes 8 = { addr.8 @.Lanon.0 }"), "{text}");
4928 }
4929
4930 #[test]
4931 fn an_object_of_no_size_at_all_has_an_image_with_nothing_in_it() {
4932 let text = ir("unsigned char foo[1][0];\n");
4936 assert!(text.contains("global @foo : bytes 0 = {}, align 1"), "{text}");
4937 }
4938
4939 #[test]
4940 fn a_null_pointer_in_an_image_is_the_bits_an_address_has_room_for() {
4941 let text = ir("void *p = 0;\nchar *q = (char *) 4096;\n");
4944 assert!(text.contains("global @p : i64 = 0, align 8"), "{text}");
4945 assert!(text.contains("global @q : i64 = 4096, align 8"), "{text}");
4946 }
4947
4948 #[test]
4949 fn an_object_another_module_defines_may_be_one_that_cannot_be_written_through() {
4950 let text = ir("extern const int limit;\nint f(void) { return limit; }\n");
4954 assert!(
4955 text.contains("global @limit : bytes 4, align 4, linkage(external), constant"),
4956 "{text}"
4957 );
4958 }
4959
4960 #[test]
4961 fn a_conditional_whose_value_is_an_object_answers_where_the_object_is() {
4962 let text = body(
4967 "\
4968struct s { int a, b; };
4969struct s pick(int c, struct s x, struct s y) { return c ? x : y; }
4970",
4971 );
4972 assert!(text.contains("block3(%7: ptr)"), "{text}");
4974 assert!(text.contains("jump block3(%3)") && text.contains("jump block3(%4)"), "{text}");
4975 assert!(!text.contains("memcpy"), "the arms are joined rather than copied: {text}");
4976 }
4977
4978 #[test]
4986 fn the_left_side_of_a_conditional_with_no_middle_is_evaluated_once() {
4987 let text = body("int f(int i) { return ++i ?: 10; }\n");
4988 assert!(text.contains("jump block3(%2)"), "the arm is the value that was tested: {text}");
4989 assert_eq!(text.matches("add.nsw").count(), 1, "incremented once: {text}");
4990
4991 let text = body("long f(int i) { return ++i ?: 10L; }\n");
4994 assert!(text.contains("%5 = sext.i64 %2"), "the arm widens what was tested: {text}");
4995 assert_eq!(text.matches("add.nsw").count(), 1, "incremented once: {text}");
4996
4997 let text = body("int g(void);\nint f(void) { return g() ?: 10; }\n");
4999 assert_eq!(text.matches("call @g").count(), 1, "called once: {text}");
5000
5001 let text = body("int f(int i) { return ++i ? ++i : 10; }\n");
5004 assert_eq!(text.matches("add.nsw").count(), 2, "incremented twice: {text}");
5005 }
5006
5007 #[test]
5008 fn a_structure_that_fits_in_registers_travels_as_the_registers_it_fits_in() {
5009 let text = ir("\
5013struct pair { int a, b; };
5014struct pair make(int a, int b);
5015struct pair twice(struct pair p) { return make(p.a, p.b); }
5016");
5017 assert!(text.contains("func @make(i32, i32) -> i64"), "{text}");
5018 assert!(text.contains("func @twice(i64) -> i64"), "{text}");
5019 }
5020
5021 #[test]
5022 fn a_structure_too_large_for_the_registers_travels_as_where_its_bytes_are() {
5023 let text = ir("\
5027struct big { double v[8]; };
5028struct big grow(struct big b);
5029struct big twice(struct big b) { return grow(grow(b)); }
5030");
5031 assert!(
5032 text.contains("func @grow(ptr sret(64, align 8), ptr byval(64, align 8))"),
5033 "{text}"
5034 );
5035 assert!(text.contains("block0(%0: ptr, %1: ptr):"), "{text}");
5036 assert_eq!(text.matches("call @grow").count(), 2, "{text}");
5039 }
5040
5041 #[test]
5042 fn a_structure_passed_to_a_variadic_function_says_so_at_the_call() {
5043 let text = ir("\
5048struct big { double v[8]; };
5049struct pair { int a, b; };
5050int p(const char *, ...);
5051int f(struct big b, struct pair q) { return p(\"\", 1, b, q); }
5052");
5053 assert!(
5054 text.contains("call @p(%4, %5, %2 byval(64, align 8), %6) : (ptr, ...) -> i32"),
5055 "{text}"
5056 );
5057 }
5058
5059 #[test]
5060 fn what_a_call_produced_is_somewhere_before_anything_is_read_out_of_it() {
5061 let body = body(
5064 "\
5065struct pair { int a, b; };
5066struct pair make(int a, int b);
5067int second(void) { return make(1, 2).b; }
5068",
5069 );
5070 assert!(body.starts_with("block0:\n %0 = alloca, size 8, align 4\n"), "{body}");
5071 assert!(body.contains("store %3 -> %0, align 4\n"), "{body}");
5072 }
5073
5074 #[test]
5075 fn a_structure_of_floats_travels_in_floating_point_registers_on_aarch64() {
5076 let source = "\
5080struct hfa { float x, y, z; };
5081int take(struct hfa h);
5082int give(struct hfa h) { return take(h); }
5083";
5084 assert!(ir(source).contains("func @take(f64, f32) -> i32"), "{}", ir(source));
5085 let mut opts = options();
5086 opts.emit = EmitKind::Ir;
5087 opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
5088 let result = run(&opts, source);
5089 assert_eq!(result.messages, Vec::<String>::new());
5090 assert!(result.text().contains("func @take(f32, f32, f32) -> i32"), "{}", result.text());
5091 }
5092
5093 #[test]
5094 fn an_array_whose_length_is_not_a_constant_is_a_slot_made_where_its_declaration_is() {
5095 let source = "\
5098int use(int *);
5099void f(int n) {
5100 {
5101 int a[n];
5102 use(a);
5103 }
5104 use(0);
5105}
5106";
5107 let body = body(source);
5108 assert!(body.contains("mul.nsw"), "{body}");
5109 assert!(body.contains("stacksave"), "{body}");
5110 assert!(body.contains("alloca %"), "{body}");
5111 assert!(body.contains("stackrestore"), "{body}");
5112 }
5113
5114 #[test]
5115 fn a_goto_out_of_the_scope_of_one_gives_its_stack_back_on_the_way() {
5116 let source = "\
5121int use(int *);
5122int f(int n) {
5123 {
5124 int a[n];
5125 if (use(a)) goto out;
5126 use(0);
5127 }
5128out:
5129 return 0;
5130}
5131";
5132 let body = body(source);
5133 assert_eq!(body.matches("stackrestore").count(), 2, "{body}");
5135 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
5136 assert!(after.starts_with(" %4\n jump block"), "{body}");
5137 }
5138
5139 #[test]
5140 fn a_goto_to_a_label_the_array_is_still_alive_at_leaves_the_stack_alone() {
5141 let source = "\
5145int use(int *);
5146int f(int n) {
5147 int a[n];
5148again:
5149 if (use(a)) goto again;
5150 return 0;
5151}
5152";
5153 let body = body(source);
5154 assert!(body.contains("stacksave"), "{body}");
5155 assert!(!body.contains("stackrestore"), "{body}");
5156 }
5157
5158 #[test]
5159 fn a_goto_back_to_a_label_in_front_of_one_gives_it_back_every_time_round() {
5160 let source = "\
5165int use(int *);
5166int f(int n) {
5167again:
5168 {
5169 int a[n];
5170 if (use(a)) goto again;
5171 }
5172 return 0;
5173}
5174";
5175 let body = body(source);
5176 assert_eq!(body.matches("stacksave").count(), 1, "{body}");
5177 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
5178 assert!(after.starts_with(" %4\n jump block1\n"), "{body}");
5179 }
5180
5181 #[test]
5182 fn the_head_of_a_for_loop_is_a_scope_that_closes_where_the_loop_is_left() {
5183 let source = "\
5189int f(void);
5190void t(void) {
5191 int count = 10;
5192 for (; count--;) {
5193 int b[f()];
5194 int i;
5195 for (i = 0; i < f(); i++) {
5196 b[i] = count;
5197 }
5198 }
5199}
5200";
5201 let body = body(source);
5202 assert_eq!(body.matches("stacksave").count(), 1, "{body}");
5206 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
5207 let next = after.split("\n\n").next().expect("the block the restore is in");
5210 assert!(next.contains("jump block1("), "{body}");
5211 }
5212
5213 #[test]
5214 fn how_long_one_of_those_is_was_decided_where_it_was_declared_and_not_where_it_is_asked() {
5215 let source = "\
5218unsigned long f(int n) {
5219 int a[n];
5220 n = 0;
5221 return sizeof a;
5222}
5223";
5224 let body = body(source);
5225 assert_eq!(body.matches("sext.i64 %0").count(), 2, "{body}");
5227 }
5228
5229 #[test]
5230 fn a_block_in_the_middle_of_an_expression_is_walked_where_the_expression_is() {
5231 let source = "\
5234int use(int);
5235int f(int x) {
5236 return ({
5237 int t = use(x);
5238 t * t;
5239 });
5240}
5241";
5242 let expected = "\
5243block0(%0: i32):
5244 %1 = call @use(%0) : (i32) -> i32
5245 %2 = mul.nsw %1, %1
5246 return %2
5247";
5248 assert_eq!(body(source), expected);
5249 }
5250
5251 #[test]
5252 fn one_of_those_that_control_never_leaves_is_lowered_and_what_follows_it_is_dropped() {
5253 let source = "int f(int x) { return ({ return x; 0; }); }\n";
5257 assert_eq!(body(source), "block0(%0: i32):\n return %0\n");
5258 }
5259
5260 #[test]
5261 fn one_argument_off_a_variable_argument_list_stays_an_intrinsic() {
5262 let source = "double f(__builtin_va_list ap) { return __builtin_va_arg(ap, double) + __builtin_va_arg(ap, double); }\n";
5266 let expected = "\
5267block0(%0: ptr):
5268 %1 = va_arg.f64 %0
5269 %2 = va_arg.f64 %0
5270 %3 = fadd %1, %2
5271 return %3
5272";
5273 assert_eq!(body(source), expected);
5274 }
5275
5276 #[test]
5277 fn one_that_reads_a_structure_answers_where_the_object_is() {
5278 let source = "\
5292struct s { int a; long b; };
5293long f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.b; }
5294";
5295 let expected = "\
5296block0(%0: ptr):
5297 %1 = alloca, size 16, align 16
5298 %2 = va_object %0, size 16, align 8, in(int 8 at 0, int 8 at 8)
5299 memcpy %1, %2, size 16, align 8
5300 %3 = iconst.i64 8
5301 %4 = ptr_add %1, %3
5302 %5 = load.i64 %4, align 8
5303 return %5
5304";
5305 assert_eq!(body(source), expected);
5306 }
5307
5308 #[test]
5312 fn the_classification_says_which_registers_the_object_arrived_in() {
5313 let source = "\
5314struct s { double a; double b; };
5315double f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.a; }
5316";
5317 assert!(
5318 body(source)
5319 .contains("va_object %0, size 16, align 8, in(float f64 at 0, float f64 at 8)"),
5320 "{}",
5321 body(source)
5322 );
5323
5324 let big = "\
5325struct s { long a[4]; };
5326long f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.a[0]; }
5327";
5328 assert!(body(big).contains("va_object %0, size 32, align 8\n"), "{}", body(big));
5329 }
5330
5331 #[test]
5332 fn a_jump_to_an_address_branches_to_every_label_the_function_takes_the_address_of() {
5333 let source = "\
5337int f(int c) {
5338 void *p = c ? &&one : &&two;
5339 goto *p;
5340one:
5341 return 1;
5342two:
5343 return 2;
5344}
5345";
5346 let expected = "\
5347block0(%0: i32):
5348 %1 = iconst.i32 0
5349 %2 = icmp ne %0, %1
5350 br_if %2, block1, block2
5351
5352block1:
5353 %3 = block_addr block3
5354 jump block4(%3)
5355
5356block2:
5357 %4 = block_addr block5
5358 jump block4(%4)
5359
5360block3:
5361 %5 = iconst.i32 1
5362 return %5
5363
5364block4(%6: ptr):
5365 indirect_br %6, block3, block5
5366
5367block5:
5368 %7 = iconst.i32 2
5369 return %7
5370";
5371 assert_eq!(body(source), expected);
5372 }
5373
5374 #[test]
5375 fn a_jump_to_an_address_no_label_in_the_function_has_arrives_nowhere() {
5376 let source = "void **next(void);
5379void f(void) { goto *next(); }
5380";
5381 let expected = "\
5382block0:
5383 %0 = call @next() : () -> ptr
5384 unreachable
5385";
5386 assert_eq!(body(source), expected);
5387 }
5388
5389 #[test]
5390 fn an_asm_with_no_operands_is_volatile_and_the_clobbers_are_the_whole_of_what_it_says() {
5391 let source = "void f(void) { __asm__(\"mfence\" ::: \"memory\"); }\n";
5394 let expected = "\
5395block0:
5396 inline_asm.volatile \"mfence\", \"\", \"memory\"()
5397 return
5398";
5399 assert_eq!(body(source), expected);
5400 }
5401
5402 #[test]
5403 fn the_constraints_are_one_list_in_the_order_the_template_counts_the_operands() {
5404 let source = "\
5407int f(int x, int y) {
5408 int r;
5409 __asm__(\"addl %2, %0\" : \"=r\"(r), \"+r\"(y) : \"r\"(x));
5410 return r + y;
5411}
5412";
5413 let expected = "\
5414block0(%0: i32, %1: i32):
5415 %2, %3 = inline_asm.(i32, i32) \"addl %2, %0\", \"=r,+r,r\", \"\"(%1, %0)
5416 %4 = add.nsw %2, %3
5417 return %4
5418";
5419 assert_eq!(body(source), expected);
5420 }
5421
5422 #[test]
5423 fn a_memory_operand_travels_as_the_address_of_an_object_that_is_given_a_slot() {
5424 let source = "\
5429struct pair { int a, b; };
5430int f(int x) {
5431 int slot = x;
5432 struct pair p = { x, x };
5433 __asm__(\"incl %0\" : \"+m\"(slot), \"=m\"(p));
5434 return slot + p.a;
5435}
5436";
5437 let text = body(source);
5438 assert!(text.contains("inline_asm \"incl %0\", \"+m,=m\", \"\"(%1, %2)\n"), "{text}");
5439 assert!(text.contains("%1 = alloca, size 4, align 4\n"), "{text}");
5440 assert!(text.contains("%2 = alloca, size 8, align 4\n"), "{text}");
5441 }
5442
5443 #[test]
5444 fn an_asm_goto_falls_through_to_its_first_target_and_writes_its_outputs_there() {
5445 let source = "\
5450int f(int x) {
5451 int r = 7;
5452 __asm__ goto(\"cbnz %0, %l1\" : \"=r\"(r) : \"r\"(x) :: away);
5453 return r;
5454away:
5455 return r;
5456}
5457";
5458 let expected = "\
5459block0(%0: i32):
5460 %1 = iconst.i32 7
5461 %2 = inline_asm.volatile \"cbnz %0, %l1\", \"=r,r\", \"\"(%0), labels [block1, block2]
5462
5463block1:
5464 return %2
5465
5466block2:
5467 return %1
5468";
5469 assert_eq!(body(source), expected);
5470 }
5471
5472 #[test]
5473 fn an_asm_statement_that_is_not_well_formed_is_reported_in_the_words_gcc_uses() {
5474 let mut opts = options();
5478 opts.emit = EmitKind::Ir;
5479 for (source, expected) in [
5480 (
5481 "void f(int x) { __asm__(\"\" : \"r\"(x)); }\n",
5482 "output operand constraint lacks '='",
5483 ),
5484 (
5485 "void f(int x) { __asm__(\"\" : \"=r\"(x + 1)); }\n",
5486 "lvalue required in 'asm' statement",
5487 ),
5488 (
5489 "const int g = 1;\nvoid f(void) { __asm__(\"\" : \"=r\"(g)); }\n",
5490 "read-only variable 'g' used as 'asm' output",
5491 ),
5492 (
5493 "void f(int x) { __asm__(\"\" : : \"=r\"(x)); }\n",
5494 "input operand constraint contains '='",
5495 ),
5496 (
5497 "void f(void) { __asm__(\"\" : : \"m\"(1)); }\n",
5498 "memory input 0 is not directly addressable",
5499 ),
5500 ("void f(void) { __asm__(L\"\"); }\n", "wide string literal in 'asm'"),
5501 (
5502 "void f(int x, int y) { __asm__(\"\" : [a] \"=r\"(x) : [a] \"r\"(y)); }\n",
5503 "duplicate asm operand name 'a'",
5504 ),
5505 ("void f(int x) { __asm__(\"%[in]\" : \"=r\"(x)); }\n", "undefined named operand 'in'"),
5506 ] {
5507 let result = run(&opts, source);
5508 assert!(result.failed(), "expected this to be reported:\n{source}");
5509 assert!(
5510 result.messages.iter().any(|m| m.contains(expected)),
5511 "{expected}\n{:?}",
5512 result.messages
5513 );
5514 }
5515 }
5516
5517 #[test]
5518 fn what_the_walk_cannot_build_yet_is_reported_rather_than_mislowered() {
5519 let mut opts = options();
5520 opts.emit = EmitKind::Ir;
5521 for source in [
5522 "int f(int n) { void *p = &&out; if (n) goto *p; { int a[n]; out: return 1; } }\n",
5523 "int f(int n) { int a[n]; __asm__ goto(\"\" ::::out); out: return a[0]; }\n",
5524 ] {
5525 let result = run(&opts, source);
5526 assert!(result.failed(), "expected this to be reported:\n{source}");
5527 assert!(
5528 result.messages.iter().any(|m| m.contains("not supported yet")),
5529 "{:?}",
5530 result.messages
5531 );
5532 }
5533 }
5534
5535 fn round_trip(source: &str) -> (String, String) {
5537 let printed = ir(source);
5538 let mut opts = options();
5539 opts.emit = EmitKind::Ir;
5540 let mut fs = MemoryFileSystem::new();
5541 fs.insert("/main.ir", printed.clone().into_bytes());
5542 let result = compile_ir(&opts, "/main.ir", &fs);
5543 assert_eq!(result.messages, Vec::<String>::new(), "expected this to read back:\n{printed}");
5544 (printed, result.text().to_owned())
5545 }
5546
5547 #[test]
5548 fn ir_that_arrives_as_an_input_is_read_back_and_written_out_the_same() {
5549 let (printed, again) = round_trip(
5553 "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",
5554 );
5555 assert_eq!(printed, again);
5556 }
5557
5558 #[test]
5559 fn ir_that_is_not_ir_says_which_line_stopped_it() {
5560 let mut opts = options();
5561 opts.emit = EmitKind::Ir;
5562 let mut fs = MemoryFileSystem::new();
5563 let text = "\
5564; ModuleID = 'a.c'
5565; format 0
5566target triple = \"x86_64-unknown-linux-gnu\"
5567target datalayout = \"e-p:64:64-i64:64-S128\"
5568
5569func @f(), linkage(external) {
5570block0:
5571 frobnicate
5572}
5573";
5574 fs.insert("/main.ir", text.as_bytes().to_vec());
5575 let result = compile_ir(&opts, "/main.ir", &fs);
5576 assert!(result.failed());
5577 assert!(result.messages[0].contains("/main.ir:8"), "{:?}", result.messages);
5578 }
5579
5580 #[test]
5581 fn ir_that_reads_but_does_not_hold_together_is_reported_by_the_verifier() {
5582 let mut opts = options();
5585 opts.emit = EmitKind::Ir;
5586 let mut fs = MemoryFileSystem::new();
5587 let text = "\
5588; ModuleID = 'a.c'
5589; format 0
5590target triple = \"x86_64-unknown-linux-gnu\"
5591target datalayout = \"e-p:64:64-i64:64-S128\"
5592
5593func @f(), linkage(external) {
5594block0:
5595 %0 = iconst.i32 1
5596 return %0
5597}
5598";
5599 fs.insert("/main.ir", text.as_bytes().to_vec());
5600 let result = compile_ir(&opts, "/main.ir", &fs);
5601 assert!(result.failed());
5602 assert!(result.messages[0].contains("invalid IR"), "{:?}", result.messages);
5603 }
5604
5605 #[test]
5606 fn a_typed_tree_is_not_something_an_input_of_ir_can_produce() {
5607 let mut fs = MemoryFileSystem::new();
5609 fs.insert("/main.ir", Vec::new());
5610 let result = compile_ir(&options(), "/main.ir", &fs);
5611 assert!(result.failed());
5612 assert!(result.messages[0].contains("can only be emitted as IR"), "{:?}", result.messages);
5613 }
5614
5615 #[test]
5616 fn the_printed_ir_reads_back_as_the_same_module() {
5617 let text = ir("\
5620struct point { int x, y; };
5621static const char greeting[] = \"hi\";
5622int table[4] = { 1, 2, 3 };
5623int puts(const char *);
5624double half(double x) { return x / 2.0; }
5625int f(int n) {
5626 int total = 0;
5627 for (int i = 0; i < n; i++) {
5628 if (i == 3) continue;
5629 total += table[i];
5630 }
5631 switch (n) {
5632 case 0: total = 1;
5633 case 1: total++; break;
5634 default: total = -total;
5635 }
5636 struct point p = { total, 1 };
5637 int *q = &p.y;
5638 puts(greeting);
5639 return p.x + *q;
5640}
5641int dispatch(int c) {
5642 void *p = c ? &&one : &&two;
5643 goto *p;
5644one:
5645 return 1;
5646two:
5647 return 2;
5648}
5649int assembly(int x, int *p) {
5650 int r;
5651 __asm__ volatile(\"xadd %0, %2\" : \"=r\"(r), \"+m\"(*p) : \"0\"(x) : \"cc\");
5652 __asm__ goto(\"cbnz %0, %l1\" : : \"r\"(r) : : away);
5653 return r;
5654away:
5655 return 0;
5656}
5657");
5658 let mut names = Interner::new();
5659 let module = rucc_ir::parse(&text, &mut names).expect("the printer writes what it reads");
5660 assert_eq!(rucc_ir::print(&module, &names), text);
5661 }
5662
5663 #[test]
5664 fn what_save_temps_keeps_is_the_text_that_was_compiled_and_the_assembly_that_was_assembled() {
5665 let mut opts = options();
5669 opts.emit = EmitKind::Object;
5670 opts.save_temps = rucc_session::SaveTemps::Object;
5671 let result = run(&opts, "#define N 2\nint a[N];\n");
5672 assert_eq!(result.messages, Vec::<String>::new());
5673 let text = result.temps.preprocessed.expect("the preprocessed text");
5674 assert!(text.contains("int a[2];"), "{text}");
5675 assert!(text.starts_with("# 1 \"/main.c\""), "{text}");
5676 let asm = result.temps.assembly.expect("the assembly");
5677 assert!(asm.contains("a:"), "{asm}");
5678 assert!(matches!(result.artifact, Artifact::Object(_)), "{:?}", result.artifact);
5679 }
5680
5681 #[test]
5682 fn nothing_is_kept_unless_the_flag_asked_for_it() {
5683 let mut opts = options();
5686 opts.emit = EmitKind::Object;
5687 assert_eq!(run(&opts, "int a;\n").temps, Temps::default());
5688 }
5689
5690 #[test]
5691 fn a_compilation_that_stops_before_the_back_end_keeps_the_text_and_no_assembly() {
5692 let mut opts = options();
5695 opts.emit = EmitKind::Ir;
5696 opts.save_temps = rucc_session::SaveTemps::Cwd;
5697 let result = run(&opts, "int a;\n");
5698 assert!(result.temps.preprocessed.is_some());
5699 assert_eq!(result.temps.assembly, None);
5700 }
5701}