Commit a84951465b

Linus Groh <mail@linusgroh.de>
2024-07-27 23:08:05
translate-c: Use mangled name for local extern in condition/loop
1 parent 66b7127
Changed files (3)
lib/compiler/aro_translate_c.zig
@@ -1469,7 +1469,7 @@ pub fn ScopeExtra(comptime ScopeExtraContext: type, comptime ScopeExtraType: typ
 
         pub fn getAlias(scope: *ScopeExtraScope, name: []const u8) []const u8 {
             return switch (scope.id) {
-                .root => return name,
+                .root => name,
                 .block => @as(*Block, @fieldParentPtr("base", scope)).getAlias(name),
                 .loop, .do_loop, .condition => scope.parent.?.getAlias(name),
             };
@@ -1477,11 +1477,12 @@ pub fn ScopeExtra(comptime ScopeExtraContext: type, comptime ScopeExtraType: typ
 
         pub fn getLocalExternAlias(scope: *ScopeExtraScope, name: []const u8) ?[]const u8 {
             return switch (scope.id) {
+                .root => null,
                 .block => ret: {
                     const block = @as(*Block, @fieldParentPtr("base", scope));
                     break :ret block.getLocalExternAlias(name);
                 },
-                .root, .loop, .do_loop, .condition => null,
+                .loop, .do_loop, .condition => scope.parent.?.getLocalExternAlias(name),
             };
         }
 
src/translate_c.zig
@@ -1897,7 +1897,7 @@ fn transDeclRefExpr(
     const name = try c.str(@as(*const clang.NamedDecl, @ptrCast(value_decl)).getName_bytes_begin());
     const mangled_name = scope.getAlias(name);
     const decl_is_var = @as(*const clang.Decl, @ptrCast(value_decl)).getKind() == .Var;
-    const potential_local_extern = if (decl_is_var) ((@as(*const clang.VarDecl, @ptrCast(value_decl)).getStorageClass() == .Extern) and (scope.id == .block)) else false;
+    const potential_local_extern = if (decl_is_var) ((@as(*const clang.VarDecl, @ptrCast(value_decl)).getStorageClass() == .Extern) and (scope.id != .root)) else false;
 
     var confirmed_local_extern = false;
     var ref_expr = val: {
test/cases/run_translated_c/extern_typedef_variables_in_functions.c
@@ -4,6 +4,10 @@ static int func(void)
 {
   typedef int test_type_t;
   extern const test_type_t ev;
+  // Ensure mangled name is also being used for conditions and loops, see #20828
+  if (ev == 0);
+  while (ev == 0);
+  do; while (ev == 0);
   return ev + 2;
 }