From 892cadc8e27a94c6eb794a4d706e0b0c5bd210d0 Mon Sep 17 00:00:00 2001 From: Michael Forney Date: Thu, 10 Mar 2022 22:52:04 -0800 Subject: qbe: Only return 0 from main if it has type int Though C11 5.1.2.2.1 says that main must have a return type of int, we could still encounter a program which declares it as something else. This is undefined behavior, but we should not produce invalid QBE IL in this case. Also, 5.1.2.2.3 specifies that the implicit return 0 should only apply when main's return type is compatible with int. --- qbe.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/qbe.c b/qbe.c index 4b0a767..a675c4e 100644 --- a/qbe.c +++ b/qbe.c @@ -1197,9 +1197,15 @@ emitfunc(struct func *f, bool global) struct block *b; struct inst **inst, **instend; struct param *p; + struct value *v; - if (f->end->jump.kind == JUMP_NONE) - funcret(f, strcmp(f->name, "main") == 0 ? mkintconst(0) : NULL); + if (f->end->jump.kind == JUMP_NONE) { + v = NULL; + /* implicitly return 0 from main if we reach the end of the function */ + if (strcmp(f->name, "main") == 0 && f->type->base == &typeint) + v = mkintconst(0); + funcret(f, v); + } if (global) puts("export"); fputs("function ", stdout); -- cgit v1.2.3