authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2022-10-27 22:09:17-04:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2022-10-27 22:09:17-04:00
log2991e4a454c4d719226fcfc7e8ac8dec44250a7e
tree2d0abcbd613008f7c07aae6bcad1b656bffb1f4f
parentbc72ae5e4e6d8f2253aed1316b053ad1022f9f67
parent648d34d8eacaf2e35e336abd5b0c50c2ab9bfc94
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

Merge pull request #13288 from Vexu/opt-slice

Optimize size of optional slices (+ some fixes)

17 files changed, 260 insertions(+), 186 deletions(-)

lib/std/mem/Allocator.zig+6-3
......@@ -286,7 +286,8 @@ pub fn allocAdvancedWithRetAddr(
286286 } else @alignOf(T);
287287
288288 if (n == 0) {
289 return @as([*]align(a) T, undefined)[0..0];
289 const ptr = comptime std.mem.alignBackward(std.math.maxInt(usize), a);
290 return @intToPtr([*]align(a) T, ptr)[0..0];
290291 }
291292
292293 const byte_count = math.mul(usize, @sizeOf(T), n) catch return Error.OutOfMemory;
......@@ -383,7 +384,8 @@ pub fn reallocAdvancedWithRetAddr(
383384 }
384385 if (new_n == 0) {
385386 self.free(old_mem);
386 return @as([*]align(new_alignment) T, undefined)[0..0];
387 const ptr = comptime std.mem.alignBackward(std.math.maxInt(usize), new_alignment);
388 return @intToPtr([*]align(new_alignment) T, ptr)[0..0];
387389 }
388390
389391 const old_byte_slice = mem.sliceAsBytes(old_mem);
......@@ -462,7 +464,8 @@ pub fn alignedShrinkWithRetAddr(
462464 return old_mem;
463465 if (new_n == 0) {
464466 self.free(old_mem);
465 return @as([*]align(new_alignment) T, undefined)[0..0];
467 const ptr = comptime std.mem.alignBackward(std.math.maxInt(usize), new_alignment);
468 return @intToPtr([*]align(new_alignment) T, ptr)[0..0];
466469 }
467470
468471 assert(new_n < old_mem.len);
src/AstGen.zig+8-1
......@@ -9709,7 +9709,7 @@ fn rvalue(
97099709 const result_index = refToIndex(result) orelse
97109710 return gz.addUnTok(.ref, result, src_token);
97119711 const zir_tags = gz.astgen.instructions.items(.tag);
9712 if (zir_tags[result_index].isParam())
9712 if (zir_tags[result_index].isParam() or astgen.isInferred(result))
97139713 return gz.addUnTok(.ref, result, src_token);
97149714 const gop = try astgen.ref_table.getOrPut(astgen.gpa, result_index);
97159715 if (!gop.found_existing) {
......@@ -12196,6 +12196,13 @@ fn isInferred(astgen: *AstGen, ref: Zir.Inst.Ref) bool {
1219612196 .alloc_inferred_comptime_mut,
1219712197 => true,
1219812198
12199 .extended => {
12200 const zir_data = astgen.instructions.items(.data);
12201 if (zir_data[inst].extended.opcode != .alloc) return false;
12202 const small = @bitCast(Zir.Inst.AllocExtended.Small, zir_data[inst].extended.small);
12203 return !small.has_type;
12204 },
12205
1219912206 else => false,
1220012207 };
1220112208}
src/Sema.zig+45-17
......@@ -5053,6 +5053,7 @@ fn zirBlock(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileErro
50535053 .label = &label,
50545054 .inlining = parent_block.inlining,
50555055 .is_comptime = parent_block.is_comptime,
5056 .is_typeof = parent_block.is_typeof,
50565057 .want_safety = parent_block.want_safety,
50575058 .float_mode = parent_block.float_mode,
50585059 .runtime_cond = parent_block.runtime_cond,
......@@ -5945,7 +5946,7 @@ fn zirCall(
59455946
59465947 const backend_supports_error_return_tracing = sema.mod.comp.bin_file.options.use_llvm;
59475948 if (backend_supports_error_return_tracing and sema.mod.comp.bin_file.options.error_return_tracing and
5948 !block.is_comptime and (input_is_error or pop_error_return_trace))
5949 !block.is_comptime and !block.is_typeof and (input_is_error or pop_error_return_trace))
59495950 {
59505951 const call_inst: Air.Inst.Ref = if (modifier == .always_tail) undefined else b: {
59515952 break :b try sema.analyzeCall(block, func, func_src, call_src, modifier, ensure_result_used, resolved_args, bound_arg_src);
......@@ -6425,7 +6426,7 @@ fn analyzeCall(
64256426 }
64266427
64276428 const new_func_resolved_ty = try Type.Tag.function.create(sema.arena, new_fn_info);
6428 if (!is_comptime_call) {
6429 if (!is_comptime_call and !block.is_typeof) {
64296430 try sema.emitDbgInline(block, parent_func.?, module_fn, new_func_resolved_ty, .dbg_inline_begin);
64306431
64316432 const zir_tags = sema.code.instructions.items(.tag);
......@@ -6463,7 +6464,7 @@ fn analyzeCall(
64636464 break :result try sema.analyzeBlockBody(block, call_src, &child_block, merges);
64646465 };
64656466
6466 if (!is_comptime_call and sema.typeOf(result).zigTypeTag() != .NoReturn) {
6467 if (!is_comptime_call and !block.is_typeof and sema.typeOf(result).zigTypeTag() != .NoReturn) {
64676468 try sema.emitDbgInline(
64686469 block,
64696470 module_fn,
......@@ -6747,6 +6748,8 @@ fn analyzeGenericCallArg(
67476748 try sema.queueFullTypeResolution(param_ty);
67486749 runtime_args[runtime_i.*] = casted_arg;
67496750 runtime_i.* += 1;
6751 } else if (try sema.typeHasOnePossibleValue(block, arg_src, comptime_arg.ty)) |_| {
6752 _ = try sema.coerce(block, comptime_arg.ty, uncasted_arg, arg_src);
67506753 }
67516754}
67526755
......@@ -10220,6 +10223,7 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
1022010223 .label = &label,
1022110224 .inlining = block.inlining,
1022210225 .is_comptime = block.is_comptime,
10226 .is_typeof = block.is_typeof,
1022310227 .switch_else_err_ty = else_error_ty,
1022410228 .runtime_cond = block.runtime_cond,
1022510229 .runtime_loop = block.runtime_loop,
......@@ -16411,7 +16415,7 @@ fn zirSaveErrRetIndex(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileE
1641116415 if (!ok) return;
1641216416
1641316417 // This is only relevant at runtime.
16414 if (block.is_comptime) return;
16418 if (block.is_comptime or block.is_typeof) return;
1641516419
1641616420 // This is only relevant within functions.
1641716421 if (sema.func == null) return;
......@@ -16431,7 +16435,7 @@ fn zirRestoreErrRetIndex(sema: *Sema, start_block: *Block, inst: Zir.Inst.Index)
1643116435 const src = sema.src; // TODO
1643216436
1643316437 // This is only relevant at runtime.
16434 if (start_block.is_comptime) return;
16438 if (start_block.is_comptime or start_block.is_typeof) return;
1643516439
1643616440 const backend_supports_error_return_tracing = sema.mod.comp.bin_file.options.use_llvm;
1643716441 const ok = sema.owner_func.?.calls_or_awaits_errorable_fn and
......@@ -28357,8 +28361,16 @@ fn resolvePeerTypes(
2835728361 const candidate_ty_tag = try candidate_ty.zigTypeTagOrPoison();
2835828362 const chosen_ty_tag = try chosen_ty.zigTypeTagOrPoison();
2835928363
28360 if (candidate_ty.eql(chosen_ty, sema.mod))
28364 // If the candidate can coerce into our chosen type, we're done.
28365 // If the chosen type can coerce into the candidate, use that.
28366 if ((try sema.coerceInMemoryAllowed(block, chosen_ty, candidate_ty, false, target, src, src)) == .ok) {
28367 continue;
28368 }
28369 if ((try sema.coerceInMemoryAllowed(block, candidate_ty, chosen_ty, false, target, src, src)) == .ok) {
28370 chosen = candidate;
28371 chosen_i = candidate_i + 1;
2836128372 continue;
28373 }
2836228374
2836328375 switch (candidate_ty_tag) {
2836428376 .NoReturn, .Undefined => continue,
......@@ -28758,17 +28770,6 @@ fn resolvePeerTypes(
2875828770 else => {},
2875928771 }
2876028772
28761 // If the candidate can coerce into our chosen type, we're done.
28762 // If the chosen type can coerce into the candidate, use that.
28763 if ((try sema.coerceInMemoryAllowed(block, chosen_ty, candidate_ty, false, target, src, src)) == .ok) {
28764 continue;
28765 }
28766 if ((try sema.coerceInMemoryAllowed(block, candidate_ty, chosen_ty, false, target, src, src)) == .ok) {
28767 chosen = candidate;
28768 chosen_i = candidate_i + 1;
28769 continue;
28770 }
28771
2877228773 // At this point, we hit a compile error. We need to recover
2877328774 // the source locations.
2877428775 const chosen_src = candidate_srcs.resolve(
......@@ -29092,6 +29093,33 @@ fn semaBackingIntType(mod: *Module, struct_obj: *Module.Struct) CompileError!voi
2909229093 struct_obj.backing_int_ty = try backing_int_ty.copy(decl_arena_allocator);
2909329094 try wip_captures.finalize();
2909429095 } else {
29096 if (fields_bit_sum > std.math.maxInt(u16)) {
29097 var sema: Sema = .{
29098 .mod = mod,
29099 .gpa = gpa,
29100 .arena = undefined,
29101 .perm_arena = decl_arena_allocator,
29102 .code = zir,
29103 .owner_decl = decl,
29104 .owner_decl_index = decl_index,
29105 .func = null,
29106 .fn_ret_ty = Type.void,
29107 .owner_func = null,
29108 };
29109 defer sema.deinit();
29110
29111 var block: Block = .{
29112 .parent = null,
29113 .sema = &sema,
29114 .src_decl = decl_index,
29115 .namespace = &struct_obj.namespace,
29116 .wip_capture_scope = undefined,
29117 .instructions = .{},
29118 .inlining = null,
29119 .is_comptime = true,
29120 };
29121 return sema.fail(&block, LazySrcLoc.nodeOffset(0), "size of packed struct '{d}' exceeds maximum bit width of 65535", .{fields_bit_sum});
29122 }
2909529123 var buf: Type.Payload.Bits = .{
2909629124 .base = .{ .tag = .int_unsigned },
2909729125 .data = @intCast(u16, fields_bit_sum),
src/codegen/c.zig+9-5
......@@ -730,7 +730,11 @@ pub const DeclGen = struct {
730730 }
731731
732732 if (ty.optionalReprIsPayload()) {
733 return dg.renderValue(writer, payload_ty, val, location);
733 if (val.castTag(.opt_payload)) |payload| {
734 return dg.renderValue(writer, payload_ty, payload.data, location);
735 } else {
736 return dg.renderValue(writer, payload_ty, val, location);
737 }
734738 }
735739
736740 try writer.writeByte('(');
......@@ -3267,11 +3271,9 @@ fn airIsNull(
32673271 try f.writeCValue(writer, operand);
32683272
32693273 const ty = f.air.typeOf(un_op);
3274 const opt_ty = if (deref_suffix[0] != 0) ty.childType() else ty;
32703275 var opt_buf: Type.Payload.ElemType = undefined;
3271 const payload_ty = if (deref_suffix[0] != 0)
3272 ty.childType().optionalChild(&opt_buf)
3273 else
3274 ty.optionalChild(&opt_buf);
3276 const payload_ty = opt_ty.optionalChild(&opt_buf);
32753277
32763278 if (!payload_ty.hasRuntimeBitsIgnoreComptime()) {
32773279 try writer.print("){s} {s} true;\n", .{ deref_suffix, operator });
......@@ -3280,6 +3282,8 @@ fn airIsNull(
32803282 try writer.print("){s} {s} NULL;\n", .{ deref_suffix, operator });
32813283 } else if (payload_ty.zigTypeTag() == .ErrorSet) {
32823284 try writer.print("){s} {s} 0;\n", .{ deref_suffix, operator });
3285 } else if (payload_ty.isSlice() and opt_ty.optionalReprIsPayload()) {
3286 try writer.print("){s}.ptr {s} NULL;\n", .{ deref_suffix, operator });
32833287 } else {
32843288 try writer.print("){s}.is_null {s} true;\n", .{ deref_suffix, operator });
32853289 }
src/codegen/llvm.zig+22-8
......@@ -1027,7 +1027,9 @@ pub const Object = struct {
10271027 dg.addArgAttr(llvm_func, llvm_arg_i, "noalias");
10281028 }
10291029 }
1030 dg.addArgAttr(llvm_func, llvm_arg_i, "nonnull");
1030 if (param_ty.zigTypeTag() != .Optional) {
1031 dg.addArgAttr(llvm_func, llvm_arg_i, "nonnull");
1032 }
10311033 if (!ptr_info.mutable) {
10321034 dg.addArgAttr(llvm_func, llvm_arg_i, "readonly");
10331035 }
......@@ -1916,7 +1918,7 @@ pub const Object = struct {
19161918
19171919 if (ty.castTag(.@"struct")) |payload| {
19181920 const struct_obj = payload.data;
1919 if (struct_obj.layout == .Packed) {
1921 if (struct_obj.layout == .Packed and struct_obj.haveFieldTypes()) {
19201922 const info = struct_obj.backing_int_ty.intInfo(target);
19211923 const dwarf_encoding: c_uint = switch (info.signedness) {
19221924 .signed => DW.ATE.signed,
......@@ -3117,7 +3119,11 @@ pub const DeclGen = struct {
31173119 .slice => {
31183120 const param_ty = fn_info.param_types[it.zig_index - 1];
31193121 var buf: Type.SlicePtrFieldTypeBuffer = undefined;
3120 const ptr_ty = param_ty.slicePtrFieldType(&buf);
3122 var opt_buf: Type.Payload.ElemType = undefined;
3123 const ptr_ty = if (param_ty.zigTypeTag() == .Optional)
3124 param_ty.optionalChild(&opt_buf).slicePtrFieldType(&buf)
3125 else
3126 param_ty.slicePtrFieldType(&buf);
31213127 const ptr_llvm_ty = try dg.lowerType(ptr_ty);
31223128 const len_llvm_ty = try dg.lowerType(Type.usize);
31233129
......@@ -5438,10 +5444,11 @@ pub const FuncGen = struct {
54385444 const llvm_usize = try self.dg.lowerType(Type.usize);
54395445 const len = llvm_usize.constInt(array_ty.arrayLen(), .False);
54405446 const slice_llvm_ty = try self.dg.lowerType(self.air.typeOfIndex(inst));
5447 const operand = try self.resolveInst(ty_op.operand);
54415448 if (!array_ty.hasRuntimeBitsIgnoreComptime()) {
5442 return self.builder.buildInsertValue(slice_llvm_ty.getUndef(), len, 1, "");
5449 const partial = self.builder.buildInsertValue(slice_llvm_ty.getUndef(), operand, 0, "");
5450 return self.builder.buildInsertValue(partial, len, 1, "");
54435451 }
5444 const operand = try self.resolveInst(ty_op.operand);
54455452 const indices: [2]*llvm.Value = .{
54465453 llvm_usize.constNull(), llvm_usize.constNull(),
54475454 };
......@@ -6320,18 +6327,24 @@ pub const FuncGen = struct {
63206327 const operand_ty = self.air.typeOf(un_op);
63216328 const optional_ty = if (operand_is_ptr) operand_ty.childType() else operand_ty;
63226329 const optional_llvm_ty = try self.dg.lowerType(optional_ty);
6330 var buf: Type.Payload.ElemType = undefined;
6331 const payload_ty = optional_ty.optionalChild(&buf);
63236332 if (optional_ty.optionalReprIsPayload()) {
63246333 const loaded = if (operand_is_ptr)
63256334 self.builder.buildLoad(optional_llvm_ty, operand, "")
63266335 else
63276336 operand;
6337 if (payload_ty.isSlice()) {
6338 const slice_ptr = self.builder.buildExtractValue(loaded, 0, "");
6339 var slice_buf: Type.SlicePtrFieldTypeBuffer = undefined;
6340 const ptr_ty = try self.dg.lowerType(payload_ty.slicePtrFieldType(&slice_buf));
6341 return self.builder.buildICmp(pred, slice_ptr, ptr_ty.constNull(), "");
6342 }
63286343 return self.builder.buildICmp(pred, loaded, optional_llvm_ty.constNull(), "");
63296344 }
63306345
63316346 comptime assert(optional_layout_version == 3);
63326347
6333 var buf: Type.Payload.ElemType = undefined;
6334 const payload_ty = optional_ty.optionalChild(&buf);
63356348 if (!payload_ty.hasRuntimeBitsIgnoreComptime()) {
63366349 const loaded = if (operand_is_ptr)
63376350 self.builder.buildLoad(optional_llvm_ty, operand, "")
......@@ -10355,7 +10368,8 @@ const ParamTypeIterator = struct {
1035510368 .Unspecified, .Inline => {
1035610369 it.zig_index += 1;
1035710370 it.llvm_index += 1;
10358 if (ty.isSlice()) {
10371 var buf: Type.Payload.ElemType = undefined;
10372 if (ty.isSlice() or (ty.zigTypeTag() == .Optional and ty.optionalChild(&buf).isSlice())) {
1035910373 return .slice;
1036010374 } else if (isByRef(ty)) {
1036110375 return .byref;
src/translate_c.zig+79-110
......@@ -224,8 +224,7 @@ const Scope = struct {
224224 }
225225 }
226226
227 fn findBlockReturnType(inner: *Scope, c: *Context) clang.QualType {
228 _ = c;
227 fn findBlockReturnType(inner: *Scope) clang.QualType {
229228 var scope = inner;
230229 while (true) {
231230 switch (scope.id) {
......@@ -833,7 +832,7 @@ fn visitVarDecl(c: *Context, var_decl: *const clang.VarDecl, mangled_name: ?[]co
833832 if (has_init) trans_init: {
834833 if (decl_init) |expr| {
835834 const node_or_error = if (expr.getStmtClass() == .StringLiteralClass)
836 transStringLiteralInitializer(c, scope, @ptrCast(*const clang.StringLiteral, expr), type_node)
835 transStringLiteralInitializer(c, @ptrCast(*const clang.StringLiteral, expr), type_node)
837836 else
838837 transExprCoercing(c, scope, expr, .used);
839838 init_node = node_or_error catch |err| switch (err) {
......@@ -1319,10 +1318,10 @@ fn transStmt(
13191318 .StringLiteralClass => return transStringLiteral(c, scope, @ptrCast(*const clang.StringLiteral, stmt), result_used),
13201319 .ParenExprClass => {
13211320 const expr = try transExpr(c, scope, @ptrCast(*const clang.ParenExpr, stmt).getSubExpr(), .used);
1322 return maybeSuppressResult(c, scope, result_used, expr);
1321 return maybeSuppressResult(c, result_used, expr);
13231322 },
13241323 .InitListExprClass => return transInitListExpr(c, scope, @ptrCast(*const clang.InitListExpr, stmt), result_used),
1325 .ImplicitValueInitExprClass => return transImplicitValueInitExpr(c, scope, @ptrCast(*const clang.Expr, stmt), result_used),
1324 .ImplicitValueInitExprClass => return transImplicitValueInitExpr(c, scope, @ptrCast(*const clang.Expr, stmt)),
13261325 .IfStmtClass => return transIfStmt(c, scope, @ptrCast(*const clang.IfStmt, stmt)),
13271326 .WhileStmtClass => return transWhileLoop(c, scope, @ptrCast(*const clang.WhileStmt, stmt)),
13281327 .DoStmtClass => return transDoWhileLoop(c, scope, @ptrCast(*const clang.DoStmt, stmt)),
......@@ -1332,7 +1331,7 @@ fn transStmt(
13321331 .ContinueStmtClass => return Tag.@"continue".init(),
13331332 .BreakStmtClass => return Tag.@"break".init(),
13341333 .ForStmtClass => return transForLoop(c, scope, @ptrCast(*const clang.ForStmt, stmt)),
1335 .FloatingLiteralClass => return transFloatingLiteral(c, scope, @ptrCast(*const clang.FloatingLiteral, stmt), result_used),
1334 .FloatingLiteralClass => return transFloatingLiteral(c, @ptrCast(*const clang.FloatingLiteral, stmt), result_used),
13361335 .ConditionalOperatorClass => {
13371336 return transConditionalOperator(c, scope, @ptrCast(*const clang.ConditionalOperator, stmt), result_used);
13381337 },
......@@ -1356,9 +1355,9 @@ fn transStmt(
13561355 .OpaqueValueExprClass => {
13571356 const source_expr = @ptrCast(*const clang.OpaqueValueExpr, stmt).getSourceExpr().?;
13581357 const expr = try transExpr(c, scope, source_expr, .used);
1359 return maybeSuppressResult(c, scope, result_used, expr);
1358 return maybeSuppressResult(c, result_used, expr);
13601359 },
1361 .OffsetOfExprClass => return transOffsetOfExpr(c, scope, @ptrCast(*const clang.OffsetOfExpr, stmt), result_used),
1360 .OffsetOfExprClass => return transOffsetOfExpr(c, @ptrCast(*const clang.OffsetOfExpr, stmt), result_used),
13621361 .CompoundLiteralExprClass => {
13631362 const compound_literal = @ptrCast(*const clang.CompoundLiteralExpr, stmt);
13641363 return transExpr(c, scope, compound_literal.getInitializer(), result_used);
......@@ -1369,13 +1368,13 @@ fn transStmt(
13691368 },
13701369 .ConvertVectorExprClass => {
13711370 const conv_vec = @ptrCast(*const clang.ConvertVectorExpr, stmt);
1372 const conv_vec_node = try transConvertVectorExpr(c, scope, stmt.getBeginLoc(), conv_vec);
1373 return maybeSuppressResult(c, scope, result_used, conv_vec_node);
1371 const conv_vec_node = try transConvertVectorExpr(c, scope, conv_vec);
1372 return maybeSuppressResult(c, result_used, conv_vec_node);
13741373 },
13751374 .ShuffleVectorExprClass => {
13761375 const shuffle_vec_expr = @ptrCast(*const clang.ShuffleVectorExpr, stmt);
13771376 const shuffle_vec_node = try transShuffleVectorExpr(c, scope, shuffle_vec_expr);
1378 return maybeSuppressResult(c, scope, result_used, shuffle_vec_node);
1377 return maybeSuppressResult(c, result_used, shuffle_vec_node);
13791378 },
13801379 .ChooseExprClass => {
13811380 const choose_expr = @ptrCast(*const clang.ChooseExpr, stmt);
......@@ -1402,10 +1401,8 @@ fn transStmt(
14021401fn transConvertVectorExpr(
14031402 c: *Context,
14041403 scope: *Scope,
1405 source_loc: clang.SourceLocation,
14061404 expr: *const clang.ConvertVectorExpr,
14071405) TransError!Node {
1408 _ = source_loc;
14091406 const base_stmt = @ptrCast(*const clang.Stmt, expr);
14101407
14111408 var block_scope = try Scope.Block.init(c, scope, true);
......@@ -1521,12 +1518,7 @@ fn transShuffleVectorExpr(
15211518
15221519/// Translate a "simple" offsetof expression containing exactly one component,
15231520/// when that component is of kind .Field - e.g. offsetof(mytype, myfield)
1524fn transSimpleOffsetOfExpr(
1525 c: *Context,
1526 scope: *Scope,
1527 expr: *const clang.OffsetOfExpr,
1528) TransError!Node {
1529 _ = scope;
1521fn transSimpleOffsetOfExpr(c: *Context, expr: *const clang.OffsetOfExpr) TransError!Node {
15301522 assert(expr.getNumComponents() == 1);
15311523 const component = expr.getComponent(0);
15321524 if (component.getKind() == .Field) {
......@@ -1551,13 +1543,12 @@ fn transSimpleOffsetOfExpr(
15511543
15521544fn transOffsetOfExpr(
15531545 c: *Context,
1554 scope: *Scope,
15551546 expr: *const clang.OffsetOfExpr,
15561547 result_used: ResultUsed,
15571548) TransError!Node {
15581549 if (expr.getNumComponents() == 1) {
1559 const offsetof_expr = try transSimpleOffsetOfExpr(c, scope, expr);
1560 return maybeSuppressResult(c, scope, result_used, offsetof_expr);
1550 const offsetof_expr = try transSimpleOffsetOfExpr(c, expr);
1551 return maybeSuppressResult(c, result_used, offsetof_expr);
15611552 }
15621553
15631554 // TODO implement OffsetOfExpr with more than 1 component
......@@ -1613,7 +1604,6 @@ fn transCreatePointerArithmeticSignedOp(
16131604
16141605 return transCreateNodeInfixOp(
16151606 c,
1616 scope,
16171607 if (is_add) .add else .sub,
16181608 lhs_node,
16191609 bitcast_node,
......@@ -1629,7 +1619,7 @@ fn transBinaryOperator(
16291619) TransError!Node {
16301620 const op = stmt.getOpcode();
16311621 const qt = stmt.getType();
1632 const isPointerDiffExpr = cIsPointerDiffExpr(c, stmt);
1622 const isPointerDiffExpr = cIsPointerDiffExpr(stmt);
16331623 switch (op) {
16341624 .Assign => return try transCreateNodeAssign(c, scope, result_used, stmt.getLHS(), stmt.getRHS()),
16351625 .Comma => {
......@@ -1646,7 +1636,7 @@ fn transBinaryOperator(
16461636 });
16471637 try block_scope.statements.append(break_node);
16481638 const block_node = try block_scope.complete(c);
1649 return maybeSuppressResult(c, scope, result_used, block_node);
1639 return maybeSuppressResult(c, result_used, block_node);
16501640 },
16511641 .Div => {
16521642 if (cIsSignedInteger(qt)) {
......@@ -1654,7 +1644,7 @@ fn transBinaryOperator(
16541644 const lhs = try transExpr(c, scope, stmt.getLHS(), .used);
16551645 const rhs = try transExpr(c, scope, stmt.getRHS(), .used);
16561646 const div_trunc = try Tag.div_trunc.create(c.arena, .{ .lhs = lhs, .rhs = rhs });
1657 return maybeSuppressResult(c, scope, result_used, div_trunc);
1647 return maybeSuppressResult(c, result_used, div_trunc);
16581648 }
16591649 },
16601650 .Rem => {
......@@ -1663,7 +1653,7 @@ fn transBinaryOperator(
16631653 const lhs = try transExpr(c, scope, stmt.getLHS(), .used);
16641654 const rhs = try transExpr(c, scope, stmt.getRHS(), .used);
16651655 const rem = try Tag.signed_remainder.create(c.arena, .{ .lhs = lhs, .rhs = rhs });
1666 return maybeSuppressResult(c, scope, result_used, rem);
1656 return maybeSuppressResult(c, result_used, rem);
16671657 }
16681658 },
16691659 .Shl => {
......@@ -1764,7 +1754,7 @@ fn transBinaryOperator(
17641754 else
17651755 rhs_uncasted;
17661756
1767 const infixOpNode = try transCreateNodeInfixOp(c, scope, op_id, lhs, rhs, result_used);
1757 const infixOpNode = try transCreateNodeInfixOp(c, op_id, lhs, rhs, result_used);
17681758 if (isPointerDiffExpr) {
17691759 // @divExact(@bitCast(<platform-ptrdiff_t>, @ptrToInt(lhs) -% @ptrToInt(rhs)), @sizeOf(<lhs target type>))
17701760 const ptrdiff_type = try transQualTypeIntWidthOf(c, qt, true);
......@@ -1843,7 +1833,7 @@ fn transCStyleCastExprClass(
18431833 src_type,
18441834 sub_expr_node,
18451835 ));
1846 return maybeSuppressResult(c, scope, result_used, cast_node);
1836 return maybeSuppressResult(c, result_used, cast_node);
18471837}
18481838
18491839/// The alignment of a variable or field
......@@ -1933,7 +1923,7 @@ fn transDeclStmtOne(
19331923
19341924 var init_node = if (decl_init) |expr|
19351925 if (expr.getStmtClass() == .StringLiteralClass)
1936 try transStringLiteralInitializer(c, scope, @ptrCast(*const clang.StringLiteral, expr), type_node)
1926 try transStringLiteralInitializer(c, @ptrCast(*const clang.StringLiteral, expr), type_node)
19371927 else
19381928 try transExprCoercing(c, scope, expr, .used)
19391929 else if (is_static_local)
......@@ -2051,21 +2041,21 @@ fn transImplicitCastExpr(
20512041 .BitCast, .FloatingCast, .FloatingToIntegral, .IntegralToFloating, .IntegralCast, .PointerToIntegral, .IntegralToPointer => {
20522042 const sub_expr_node = try transExpr(c, scope, sub_expr, .used);
20532043 const casted = try transCCast(c, scope, expr.getBeginLoc(), dest_type, src_type, sub_expr_node);
2054 return maybeSuppressResult(c, scope, result_used, casted);
2044 return maybeSuppressResult(c, result_used, casted);
20552045 },
20562046 .LValueToRValue, .NoOp, .FunctionToPointerDecay => {
20572047 const sub_expr_node = try transExpr(c, scope, sub_expr, .used);
2058 return maybeSuppressResult(c, scope, result_used, sub_expr_node);
2048 return maybeSuppressResult(c, result_used, sub_expr_node);
20592049 },
20602050 .ArrayToPointerDecay => {
20612051 const sub_expr_node = try transExpr(c, scope, sub_expr, .used);
20622052 if (exprIsNarrowStringLiteral(sub_expr) or exprIsFlexibleArrayRef(c, sub_expr)) {
2063 return maybeSuppressResult(c, scope, result_used, sub_expr_node);
2053 return maybeSuppressResult(c, result_used, sub_expr_node);
20642054 }
20652055
20662056 const addr = try Tag.address_of.create(c.arena, sub_expr_node);
20672057 const casted = try transCPtrCast(c, scope, expr.getBeginLoc(), dest_type, src_type, addr);
2068 return maybeSuppressResult(c, scope, result_used, casted);
2058 return maybeSuppressResult(c, result_used, casted);
20692059 },
20702060 .NullToPointer => {
20712061 return Tag.null_literal.init();
......@@ -2076,18 +2066,18 @@ fn transImplicitCastExpr(
20762066 const ptr_to_int = try Tag.ptr_to_int.create(c.arena, ptr_node);
20772067
20782068 const ne = try Tag.not_equal.create(c.arena, .{ .lhs = ptr_to_int, .rhs = Tag.zero_literal.init() });
2079 return maybeSuppressResult(c, scope, result_used, ne);
2069 return maybeSuppressResult(c, result_used, ne);
20802070 },
20812071 .IntegralToBoolean, .FloatingToBoolean => {
20822072 const sub_expr_node = try transExpr(c, scope, sub_expr, .used);
20832073
20842074 // The expression is already a boolean one, return it as-is
20852075 if (isBoolRes(sub_expr_node))
2086 return maybeSuppressResult(c, scope, result_used, sub_expr_node);
2076 return maybeSuppressResult(c, result_used, sub_expr_node);
20872077
20882078 // val != 0
20892079 const ne = try Tag.not_equal.create(c.arena, .{ .lhs = sub_expr_node, .rhs = Tag.zero_literal.init() });
2090 return maybeSuppressResult(c, scope, result_used, ne);
2080 return maybeSuppressResult(c, result_used, ne);
20912081 },
20922082 .BuiltinFnToFnPtr => {
20932083 return transBuiltinFnExpr(c, scope, sub_expr, result_used);
......@@ -2140,13 +2130,13 @@ fn transBoolExpr(
21402130
21412131 var res = try transExpr(c, scope, expr, used);
21422132 if (isBoolRes(res)) {
2143 return maybeSuppressResult(c, scope, used, res);
2133 return maybeSuppressResult(c, used, res);
21442134 }
21452135
21462136 const ty = getExprQualType(c, expr).getTypePtr();
21472137 const node = try finishBoolExpr(c, scope, expr.getBeginLoc(), ty, res, used);
21482138
2149 return maybeSuppressResult(c, scope, used, node);
2139 return maybeSuppressResult(c, used, node);
21502140}
21512141
21522142fn exprIsBooleanType(expr: *const clang.Expr) bool {
......@@ -2299,7 +2289,7 @@ fn transIntegerLiteral(
22992289
23002290 if (suppress_as == .no_as) {
23012291 const int_lit_node = try transCreateNodeAPInt(c, eval_result.Val.getInt());
2302 return maybeSuppressResult(c, scope, result_used, int_lit_node);
2292 return maybeSuppressResult(c, result_used, int_lit_node);
23032293 }
23042294
23052295 // Integer literals in C have types, and this can matter for several reasons.
......@@ -2317,7 +2307,7 @@ fn transIntegerLiteral(
23172307 const ty_node = try transQualType(c, scope, expr_base.getType(), expr_base.getBeginLoc());
23182308 const rhs = try transCreateNodeAPInt(c, eval_result.Val.getInt());
23192309 const as = try Tag.as.create(c.arena, .{ .lhs = ty_node, .rhs = rhs });
2320 return maybeSuppressResult(c, scope, result_used, as);
2310 return maybeSuppressResult(c, result_used, as);
23212311}
23222312
23232313fn transReturnStmt(
......@@ -2329,7 +2319,7 @@ fn transReturnStmt(
23292319 return Tag.return_void.init();
23302320
23312321 var rhs = try transExprCoercing(c, scope, val_expr, .used);
2332 const return_qt = scope.findBlockReturnType(c);
2322 const return_qt = scope.findBlockReturnType();
23332323 if (isBoolRes(rhs) and !qualTypeIsBoolean(return_qt)) {
23342324 rhs = try Tag.bool_to_int.create(c.arena, rhs);
23352325 }
......@@ -2338,7 +2328,6 @@ fn transReturnStmt(
23382328
23392329fn transNarrowStringLiteral(
23402330 c: *Context,
2341 scope: *Scope,
23422331 stmt: *const clang.StringLiteral,
23432332 result_used: ResultUsed,
23442333) TransError!Node {
......@@ -2347,7 +2336,7 @@ fn transNarrowStringLiteral(
23472336
23482337 const str = try std.fmt.allocPrint(c.arena, "\"{}\"", .{std.zig.fmtEscapes(bytes_ptr[0..len])});
23492338 const node = try Tag.string_literal.create(c.arena, str);
2350 return maybeSuppressResult(c, scope, result_used, node);
2339 return maybeSuppressResult(c, result_used, node);
23512340}
23522341
23532342fn transStringLiteral(
......@@ -2358,18 +2347,18 @@ fn transStringLiteral(
23582347) TransError!Node {
23592348 const kind = stmt.getKind();
23602349 switch (kind) {
2361 .Ascii, .UTF8 => return transNarrowStringLiteral(c, scope, stmt, result_used),
2350 .Ascii, .UTF8 => return transNarrowStringLiteral(c, stmt, result_used),
23622351 .UTF16, .UTF32, .Wide => {
23632352 const str_type = @tagName(stmt.getKind());
23642353 const name = try std.fmt.allocPrint(c.arena, "zig.{s}_string_{d}", .{ str_type, c.getMangle() });
23652354
23662355 const expr_base = @ptrCast(*const clang.Expr, stmt);
23672356 const array_type = try transQualTypeInitialized(c, scope, expr_base.getType(), expr_base, expr_base.getBeginLoc());
2368 const lit_array = try transStringLiteralInitializer(c, scope, stmt, array_type);
2357 const lit_array = try transStringLiteralInitializer(c, stmt, array_type);
23692358 const decl = try Tag.var_simple.create(c.arena, .{ .name = name, .init = lit_array });
23702359 try scope.appendNode(decl);
23712360 const node = try Tag.identifier.create(c.arena, name);
2372 return maybeSuppressResult(c, scope, result_used, node);
2361 return maybeSuppressResult(c, result_used, node);
23732362 },
23742363 }
23752364}
......@@ -2384,7 +2373,6 @@ fn getArrayPayload(array_type: Node) ast.Payload.Array.ArrayTypeInfo {
23842373/// the appropriate length, if necessary.
23852374fn transStringLiteralInitializer(
23862375 c: *Context,
2387 scope: *Scope,
23882376 stmt: *const clang.StringLiteral,
23892377 array_type: Node,
23902378) TransError!Node {
......@@ -2403,7 +2391,7 @@ fn transStringLiteralInitializer(
24032391 const init_node = if (num_inits > 0) blk: {
24042392 if (is_narrow) {
24052393 // "string literal".* or string literal"[0..num_inits].*
2406 var str = try transNarrowStringLiteral(c, scope, stmt, .used);
2394 var str = try transNarrowStringLiteral(c, stmt, .used);
24072395 if (str_length != array_size) str = try Tag.string_slice.create(c.arena, .{ .string = str, .end = num_inits });
24082396 break :blk try Tag.deref.create(c.arena, str);
24092397 } else {
......@@ -2440,8 +2428,7 @@ fn transStringLiteralInitializer(
24402428/// determine whether `stmt` is a "pointer subtraction expression" - a subtraction where
24412429/// both operands resolve to addresses. The C standard requires that both operands
24422430/// point to elements of the same array object, but we do not verify that here.
2443fn cIsPointerDiffExpr(c: *Context, stmt: *const clang.BinaryOperator) bool {
2444 _ = c;
2431fn cIsPointerDiffExpr(stmt: *const clang.BinaryOperator) bool {
24452432 const lhs = @ptrCast(*const clang.Stmt, stmt.getLHS());
24462433 const rhs = @ptrCast(*const clang.Stmt, stmt.getRHS());
24472434 return stmt.getOpcode() == .Sub and
......@@ -2748,9 +2735,7 @@ fn transInitListExprVector(
27482735 scope: *Scope,
27492736 loc: clang.SourceLocation,
27502737 expr: *const clang.InitListExpr,
2751 ty: *const clang.Type,
27522738) TransError!Node {
2753 _ = ty;
27542739 const qt = getExprQualType(c, @ptrCast(*const clang.Expr, expr));
27552740 const vector_ty = @ptrCast(*const clang.VectorType, qualTypeCanon(qt));
27562741
......@@ -2829,7 +2814,7 @@ fn transInitListExpr(
28292814 }
28302815
28312816 if (qual_type.isRecordType()) {
2832 return maybeSuppressResult(c, scope, used, try transInitListExprRecord(
2817 return maybeSuppressResult(c, used, try transInitListExprRecord(
28332818 c,
28342819 scope,
28352820 source_loc,
......@@ -2837,7 +2822,7 @@ fn transInitListExpr(
28372822 qual_type,
28382823 ));
28392824 } else if (qual_type.isArrayType()) {
2840 return maybeSuppressResult(c, scope, used, try transInitListExprArray(
2825 return maybeSuppressResult(c, used, try transInitListExprArray(
28412826 c,
28422827 scope,
28432828 source_loc,
......@@ -2845,13 +2830,7 @@ fn transInitListExpr(
28452830 qual_type,
28462831 ));
28472832 } else if (qual_type.isVectorType()) {
2848 return maybeSuppressResult(c, scope, used, try transInitListExprVector(
2849 c,
2850 scope,
2851 source_loc,
2852 expr,
2853 qual_type,
2854 ));
2833 return maybeSuppressResult(c, used, try transInitListExprVector(c, scope, source_loc, expr));
28552834 } else {
28562835 const type_name = try c.str(qual_type.getTypeClassName());
28572836 return fail(c, error.UnsupportedType, source_loc, "unsupported initlist type: '{s}'", .{type_name});
......@@ -2912,9 +2891,7 @@ fn transImplicitValueInitExpr(
29122891 c: *Context,
29132892 scope: *Scope,
29142893 expr: *const clang.Expr,
2915 used: ResultUsed,
29162894) TransError!Node {
2917 _ = used;
29182895 const source_loc = expr.getBeginLoc();
29192896 const qt = getExprQualType(c, expr);
29202897 const ty = qt.getTypePtr();
......@@ -3354,7 +3331,7 @@ fn transConstantExpr(c: *Context, scope: *Scope, expr: *const clang.Expr, used:
33543331 .lhs = try transQualType(c, scope, expr_base.getType(), expr_base.getBeginLoc()),
33553332 .rhs = try transCreateNodeAPInt(c, result.Val.getInt()),
33563333 });
3357 return maybeSuppressResult(c, scope, used, as_node);
3334 return maybeSuppressResult(c, used, as_node);
33583335 },
33593336 else => |kind| {
33603337 return fail(c, error.UnsupportedTranslation, expr.getBeginLoc(), "unsupported constant expression kind '{}'", .{kind});
......@@ -3391,7 +3368,7 @@ fn transCharLiteral(
33913368 try transCreateCharLitNode(c, narrow, val);
33923369
33933370 if (suppress_as == .no_as) {
3394 return maybeSuppressResult(c, scope, result_used, int_lit_node);
3371 return maybeSuppressResult(c, result_used, int_lit_node);
33953372 }
33963373 // See comment in `transIntegerLiteral` for why this code is here.
33973374 // @as(T, x)
......@@ -3400,7 +3377,7 @@ fn transCharLiteral(
34003377 .lhs = try transQualType(c, scope, expr_base.getType(), expr_base.getBeginLoc()),
34013378 .rhs = int_lit_node,
34023379 });
3403 return maybeSuppressResult(c, scope, result_used, as_node);
3380 return maybeSuppressResult(c, result_used, as_node);
34043381}
34053382
34063383fn transStmtExpr(c: *Context, scope: *Scope, stmt: *const clang.StmtExpr, used: ResultUsed) TransError!Node {
......@@ -3426,7 +3403,7 @@ fn transStmtExpr(c: *Context, scope: *Scope, stmt: *const clang.StmtExpr, used:
34263403 });
34273404 try block_scope.statements.append(break_node);
34283405 const res = try block_scope.complete(c);
3429 return maybeSuppressResult(c, scope, used, res);
3406 return maybeSuppressResult(c, used, res);
34303407}
34313408
34323409fn transMemberExpr(c: *Context, scope: *Scope, stmt: *const clang.MemberExpr, result_used: ResultUsed) TransError!Node {
......@@ -3455,7 +3432,7 @@ fn transMemberExpr(c: *Context, scope: *Scope, stmt: *const clang.MemberExpr, re
34553432 if (exprIsFlexibleArrayRef(c, @ptrCast(*const clang.Expr, stmt))) {
34563433 node = try Tag.call.create(c.arena, .{ .lhs = node, .args = &.{} });
34573434 }
3458 return maybeSuppressResult(c, scope, result_used, node);
3435 return maybeSuppressResult(c, result_used, node);
34593436}
34603437
34613438/// ptr[subscr] (`subscr` is a signed integer expression, `ptr` a pointer) becomes:
......@@ -3533,7 +3510,7 @@ fn transSignedArrayAccess(
35333510
35343511 const derefed = try Tag.deref.create(c.arena, block_node);
35353512
3536 return maybeSuppressResult(c, &block_scope.base, result_used, derefed);
3513 return maybeSuppressResult(c, result_used, derefed);
35373514}
35383515
35393516fn transArrayAccess(c: *Context, scope: *Scope, stmt: *const clang.ArraySubscriptExpr, result_used: ResultUsed) TransError!Node {
......@@ -3574,7 +3551,7 @@ fn transArrayAccess(c: *Context, scope: *Scope, stmt: *const clang.ArraySubscrip
35743551 .lhs = container_node,
35753552 .rhs = rhs,
35763553 });
3577 return maybeSuppressResult(c, scope, result_used, node);
3554 return maybeSuppressResult(c, result_used, node);
35783555}
35793556
35803557/// Check if an expression is ultimately a reference to a function declaration
......@@ -3665,7 +3642,7 @@ fn transCallExpr(c: *Context, scope: *Scope, stmt: *const clang.CallExpr, result
36653642 }
36663643 }
36673644
3668 return maybeSuppressResult(c, scope, result_used, node);
3645 return maybeSuppressResult(c, result_used, node);
36693646}
36703647
36713648const ClangFunctionType = union(enum) {
......@@ -3705,14 +3682,13 @@ fn transUnaryExprOrTypeTraitExpr(
37053682 stmt: *const clang.UnaryExprOrTypeTraitExpr,
37063683 result_used: ResultUsed,
37073684) TransError!Node {
3708 _ = result_used;
37093685 const loc = stmt.getBeginLoc();
37103686 const type_node = try transQualType(c, scope, stmt.getTypeOfArgument(), loc);
37113687
37123688 const kind = stmt.getKind();
3713 switch (kind) {
3714 .SizeOf => return Tag.sizeof.create(c.arena, type_node),
3715 .AlignOf => return Tag.alignof.create(c.arena, type_node),
3689 const node = switch (kind) {
3690 .SizeOf => try Tag.sizeof.create(c.arena, type_node),
3691 .AlignOf => try Tag.alignof.create(c.arena, type_node),
37163692 .PreferredAlignOf,
37173693 .VecStep,
37183694 .OpenMPRequiredSimdAlign,
......@@ -3723,7 +3699,8 @@ fn transUnaryExprOrTypeTraitExpr(
37233699 "unsupported type trait kind {}",
37243700 .{kind},
37253701 ),
3726 }
3702 };
3703 return maybeSuppressResult(c, result_used, node);
37273704}
37283705
37293706fn qualTypeHasWrappingOverflow(qt: clang.QualType) bool {
......@@ -3812,7 +3789,7 @@ fn transCreatePreCrement(
38123789 // zig: expr += 1
38133790 const lhs = try transExpr(c, scope, op_expr, .used);
38143791 const rhs = Tag.one_literal.init();
3815 return transCreateNodeInfixOp(c, scope, op, lhs, rhs, .used);
3792 return transCreateNodeInfixOp(c, op, lhs, rhs, .used);
38163793 }
38173794 // worst case
38183795 // c: ++expr
......@@ -3832,7 +3809,7 @@ fn transCreatePreCrement(
38323809
38333810 const lhs_node = try Tag.identifier.create(c.arena, ref);
38343811 const ref_node = try Tag.deref.create(c.arena, lhs_node);
3835 const node = try transCreateNodeInfixOp(c, &block_scope.base, op, ref_node, Tag.one_literal.init(), .used);
3812 const node = try transCreateNodeInfixOp(c, op, ref_node, Tag.one_literal.init(), .used);
38363813 try block_scope.statements.append(node);
38373814
38383815 const break_node = try Tag.break_val.create(c.arena, .{
......@@ -3858,7 +3835,7 @@ fn transCreatePostCrement(
38583835 // zig: expr += 1
38593836 const lhs = try transExpr(c, scope, op_expr, .used);
38603837 const rhs = Tag.one_literal.init();
3861 return transCreateNodeInfixOp(c, scope, op, lhs, rhs, .used);
3838 return transCreateNodeInfixOp(c, op, lhs, rhs, .used);
38623839 }
38633840 // worst case
38643841 // c: expr++
......@@ -3884,7 +3861,7 @@ fn transCreatePostCrement(
38843861 const tmp_decl = try Tag.var_simple.create(c.arena, .{ .name = tmp, .init = ref_node });
38853862 try block_scope.statements.append(tmp_decl);
38863863
3887 const node = try transCreateNodeInfixOp(c, &block_scope.base, op, ref_node, Tag.one_literal.init(), .used);
3864 const node = try transCreateNodeInfixOp(c, op, ref_node, Tag.one_literal.init(), .used);
38883865 try block_scope.statements.append(node);
38893866
38903867 const break_node = try Tag.break_val.create(c.arena, .{
......@@ -3965,7 +3942,7 @@ fn transCreateCompoundAssign(
39653942 else
39663943 try Tag.div_trunc.create(c.arena, operands);
39673944
3968 return transCreateNodeInfixOp(c, scope, .assign, lhs_node, builtin, .used);
3945 return transCreateNodeInfixOp(c, .assign, lhs_node, builtin, .used);
39693946 }
39703947
39713948 if (is_shift) {
......@@ -3974,7 +3951,7 @@ fn transCreateCompoundAssign(
39743951 } else if (requires_int_cast) {
39753952 rhs_node = try transCCast(c, scope, loc, lhs_qt, rhs_qt, rhs_node);
39763953 }
3977 return transCreateNodeInfixOp(c, scope, op, lhs_node, rhs_node, .used);
3954 return transCreateNodeInfixOp(c, op, lhs_node, rhs_node, .used);
39783955 }
39793956 // worst case
39803957 // c: lhs += rhs
......@@ -4005,7 +3982,7 @@ fn transCreateCompoundAssign(
40053982 else
40063983 try Tag.div_trunc.create(c.arena, operands);
40073984
4008 const assign = try transCreateNodeInfixOp(c, &block_scope.base, .assign, ref_node, builtin, .used);
3985 const assign = try transCreateNodeInfixOp(c, .assign, ref_node, builtin, .used);
40093986 try block_scope.statements.append(assign);
40103987 } else {
40113988 if (is_shift) {
......@@ -4015,7 +3992,7 @@ fn transCreateCompoundAssign(
40153992 rhs_node = try transCCast(c, &block_scope.base, loc, lhs_qt, rhs_qt, rhs_node);
40163993 }
40173994
4018 const assign = try transCreateNodeInfixOp(c, &block_scope.base, op, ref_node, rhs_node, .used);
3995 const assign = try transCreateNodeInfixOp(c, op, ref_node, rhs_node, .used);
40193996 try block_scope.statements.append(assign);
40203997 }
40213998
......@@ -4071,7 +4048,7 @@ fn transCPtrCast(
40714048 }
40724049}
40734050
4074fn transFloatingLiteral(c: *Context, scope: *Scope, expr: *const clang.FloatingLiteral, used: ResultUsed) TransError!Node {
4051fn transFloatingLiteral(c: *Context, expr: *const clang.FloatingLiteral, used: ResultUsed) TransError!Node {
40754052 switch (expr.getRawSemantics()) {
40764053 .IEEEhalf, // f16
40774054 .IEEEsingle, // f32
......@@ -4095,7 +4072,7 @@ fn transFloatingLiteral(c: *Context, scope: *Scope, expr: *const clang.FloatingL
40954072 try std.fmt.allocPrint(c.arena, "{d}", .{dbl});
40964073 var node = try Tag.float_literal.create(c.arena, str);
40974074 if (is_negative) node = try Tag.negate.create(c.arena, node);
4098 return maybeSuppressResult(c, scope, used, node);
4075 return maybeSuppressResult(c, used, node);
40994076}
41004077
41014078fn transBinaryConditionalOperator(c: *Context, scope: *Scope, stmt: *const clang.BinaryConditionalOperator, used: ResultUsed) TransError!Node {
......@@ -4151,7 +4128,7 @@ fn transBinaryConditionalOperator(c: *Context, scope: *Scope, stmt: *const clang
41514128 });
41524129 try block_scope.statements.append(break_node);
41534130 const res = try block_scope.complete(c);
4154 return maybeSuppressResult(c, scope, used, res);
4131 return maybeSuppressResult(c, used, res);
41554132}
41564133
41574134fn transConditionalOperator(c: *Context, scope: *Scope, stmt: *const clang.ConditionalOperator, used: ResultUsed) TransError!Node {
......@@ -4191,13 +4168,7 @@ fn transConditionalOperator(c: *Context, scope: *Scope, stmt: *const clang.Condi
41914168 return if_node;
41924169}
41934170
4194fn maybeSuppressResult(
4195 c: *Context,
4196 scope: *Scope,
4197 used: ResultUsed,
4198 result: Node,
4199) TransError!Node {
4200 _ = scope;
4171fn maybeSuppressResult(c: *Context, used: ResultUsed, result: Node) TransError!Node {
42014172 if (used == .used) return result;
42024173 return Tag.discard.create(c.arena, .{ .should_skip = false, .value = result });
42034174}
......@@ -4551,7 +4522,7 @@ fn transCreateNodeAssign(
45514522 if (!exprIsBooleanType(lhs) and isBoolRes(rhs_node)) {
45524523 rhs_node = try Tag.bool_to_int.create(c.arena, rhs_node);
45534524 }
4554 return transCreateNodeInfixOp(c, scope, .assign, lhs_node, rhs_node, .used);
4525 return transCreateNodeInfixOp(c, .assign, lhs_node, rhs_node, .used);
45554526 }
45564527
45574528 // worst case
......@@ -4571,7 +4542,7 @@ fn transCreateNodeAssign(
45714542
45724543 const lhs_node = try transExpr(c, &block_scope.base, lhs, .used);
45734544 const tmp_ident = try Tag.identifier.create(c.arena, tmp);
4574 const assign = try transCreateNodeInfixOp(c, &block_scope.base, .assign, lhs_node, tmp_ident, .used);
4545 const assign = try transCreateNodeInfixOp(c, .assign, lhs_node, tmp_ident, .used);
45754546 try block_scope.statements.append(assign);
45764547
45774548 const break_node = try Tag.break_val.create(c.arena, .{
......@@ -4584,7 +4555,6 @@ fn transCreateNodeAssign(
45844555
45854556fn transCreateNodeInfixOp(
45864557 c: *Context,
4587 scope: *Scope,
45884558 op: Tag,
45894559 lhs: Node,
45904560 rhs: Node,
......@@ -4598,7 +4568,7 @@ fn transCreateNodeInfixOp(
45984568 .rhs = rhs,
45994569 },
46004570 };
4601 return maybeSuppressResult(c, scope, used, Node.initPayload(&payload.base));
4571 return maybeSuppressResult(c, used, Node.initPayload(&payload.base));
46024572}
46034573
46044574fn transCreateNodeBoolInfixOp(
......@@ -4613,7 +4583,7 @@ fn transCreateNodeBoolInfixOp(
46134583 const lhs = try transBoolExpr(c, scope, stmt.getLHS(), .used);
46144584 const rhs = try transBoolExpr(c, scope, stmt.getRHS(), .used);
46154585
4616 return transCreateNodeInfixOp(c, scope, op, lhs, rhs, used);
4586 return transCreateNodeInfixOp(c, op, lhs, rhs, used);
46174587}
46184588
46194589fn transCreateNodeAPInt(c: *Context, int: *const clang.APSInt) !Node {
......@@ -4730,7 +4700,7 @@ fn transCreateNodeShiftOp(
47304700 const rhs = try transExprCoercing(c, scope, rhs_expr, .used);
47314701 const rhs_casted = try Tag.int_cast.create(c.arena, .{ .lhs = rhs_type, .rhs = rhs });
47324702
4733 return transCreateNodeInfixOp(c, scope, op, lhs, rhs_casted, used);
4703 return transCreateNodeInfixOp(c, op, lhs, rhs_casted, used);
47344704}
47354705
47364706fn transType(c: *Context, scope: *Scope, ty: *const clang.Type, source_loc: clang.SourceLocation) TypeError!Node {
......@@ -5681,13 +5651,14 @@ const ParseError = Error || error{ParseError};
56815651
56825652fn parseCExpr(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!Node {
56835653 // TODO parseCAssignExpr here
5684 const node = try parseCCondExpr(c, m, scope);
5654 var block_scope = try Scope.Block.init(c, scope, true);
5655 defer block_scope.deinit();
5656
5657 const node = try parseCCondExpr(c, m, &block_scope.base);
56855658 if (m.next().? != .Comma) {
56865659 m.i -= 1;
56875660 return node;
56885661 }
5689 var block_scope = try Scope.Block.init(c, scope, true);
5690 defer block_scope.deinit();
56915662
56925663 var last = node;
56935664 while (true) {
......@@ -6298,7 +6269,7 @@ fn parseCCastExpr(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!Node {
62986269// allow_fail is set when unsure if we are parsing a type-name
62996270fn parseCTypeName(c: *Context, m: *MacroCtx, scope: *Scope, allow_fail: bool) ParseError!?Node {
63006271 if (try parseCSpecifierQualifierList(c, m, scope, allow_fail)) |node| {
6301 return try parseCAbstractDeclarator(c, m, scope, node);
6272 return try parseCAbstractDeclarator(c, m, node);
63026273 } else {
63036274 return null;
63046275 }
......@@ -6327,7 +6298,7 @@ fn parseCSpecifierQualifierList(c: *Context, m: *MacroCtx, scope: *Scope, allow_
63276298 .Keyword_complex,
63286299 => {
63296300 m.i -= 1;
6330 return try parseCNumericType(c, m, scope);
6301 return try parseCNumericType(c, m);
63316302 },
63326303 .Keyword_enum, .Keyword_struct, .Keyword_union => {
63336304 // struct Foo will be declared as struct_Foo by transRecordDecl
......@@ -6349,8 +6320,7 @@ fn parseCSpecifierQualifierList(c: *Context, m: *MacroCtx, scope: *Scope, allow_
63496320 }
63506321}
63516322
6352fn parseCNumericType(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!Node {
6353 _ = scope;
6323fn parseCNumericType(c: *Context, m: *MacroCtx) ParseError!Node {
63546324 const KwCounter = struct {
63556325 double: u8 = 0,
63566326 long: u8 = 0,
......@@ -6451,8 +6421,7 @@ fn parseCNumericType(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!Node {
64516421 return error.ParseError;
64526422}
64536423
6454fn parseCAbstractDeclarator(c: *Context, m: *MacroCtx, scope: *Scope, node: Node) ParseError!Node {
6455 _ = scope;
6424fn parseCAbstractDeclarator(c: *Context, m: *MacroCtx, node: Node) ParseError!Node {
64566425 switch (m.next().?) {
64576426 .Asterisk => {
64586427 // last token of `node`
src/type.zig+8-38
......@@ -3434,20 +3434,8 @@ pub const Type = extern union {
34343434
34353435 if (!child_type.hasRuntimeBits()) return AbiSizeAdvanced{ .scalar = 1 };
34363436
3437 switch (child_type.zigTypeTag()) {
3438 .Pointer => {
3439 const ptr_info = child_type.ptrInfo().data;
3440 const has_null = switch (ptr_info.size) {
3441 .Slice, .C => true,
3442 else => ptr_info.@"allowzero",
3443 };
3444 if (!has_null) {
3445 const ptr_size_bytes = @divExact(target.cpu.arch.ptrBitWidth(), 8);
3446 return AbiSizeAdvanced{ .scalar = ptr_size_bytes };
3447 }
3448 },
3449 .ErrorSet => return abiSizeAdvanced(Type.anyerror, target, strat),
3450 else => {},
3437 if (ty.optionalReprIsPayload()) {
3438 return abiSizeAdvanced(child_type, target, strat);
34513439 }
34523440
34533441 const payload_size = switch (try child_type.abiSizeAdvanced(target, strat)) {
......@@ -3712,28 +3700,10 @@ pub const Type = extern union {
37123700
37133701 .int_signed, .int_unsigned => return ty.cast(Payload.Bits).?.data,
37143702
3715 .optional => {
3716 var buf: Payload.ElemType = undefined;
3717 const child_type = ty.optionalChild(&buf);
3718 if (!child_type.hasRuntimeBits()) return 8;
3719
3720 if (child_type.zigTypeTag() == .Pointer and !child_type.isCPtr() and !child_type.isSlice())
3721 return target.cpu.arch.ptrBitWidth();
3722
3723 // Optional types are represented as a struct with the child type as the first
3724 // field and a boolean as the second. Since the child type's abi alignment is
3725 // guaranteed to be >= that of bool's (1 byte) the added size is exactly equal
3726 // to the child type's ABI alignment.
3727 const child_bit_size = try bitSizeAdvanced(child_type, target, sema_kit);
3728 return child_bit_size + 1;
3729 },
3730
3731 .error_union => {
3732 const payload = ty.castTag(.error_union).?.data;
3733 if (!payload.payload.hasRuntimeBits()) {
3734 return payload.error_set.bitSizeAdvanced(target, sema_kit);
3735 }
3736 @panic("TODO bitSize error union");
3703 .optional, .error_union => {
3704 // Optionals and error unions are not packed so their bitsize
3705 // includes padding bits.
3706 return (try abiSizeAdvanced(ty, target, if (sema_kit) |sk| .{ .sema_kit = sk } else .eager)).scalar * 8;
37373707 },
37383708
37393709 .atomic_order,
......@@ -4010,8 +3980,8 @@ pub const Type = extern union {
40103980 .Pointer => {
40113981 const info = child_ty.ptrInfo().data;
40123982 switch (info.size) {
4013 .Slice, .C => return false,
4014 .Many, .One => return !info.@"allowzero",
3983 .C => return false,
3984 .Slice, .Many, .One => return !info.@"allowzero",
40153985 }
40163986 },
40173987 .ErrorSet => return true,
test/behavior.zig+2
......@@ -108,7 +108,9 @@ test {
108108 _ = @import("behavior/bugs/13112.zig");
109109 _ = @import("behavior/bugs/13128.zig");
110110 _ = @import("behavior/bugs/13164.zig");
111 _ = @import("behavior/bugs/13159.zig");
111112 _ = @import("behavior/bugs/13171.zig");
113 _ = @import("behavior/bugs/13285.zig");
112114 _ = @import("behavior/byteswap.zig");
113115 _ = @import("behavior/byval_arg_var.zig");
114116 _ = @import("behavior/call.zig");
test/behavior/bugs/13159.zig created+14
......@@ -0,0 +1,14 @@
1const std = @import("std");
2const expect = std.testing.expect;
3
4const Bar = packed struct {
5 const Baz = enum {
6 fizz,
7 buzz,
8 };
9};
10
11test {
12 var foo = Bar.Baz.fizz;
13 try expect(foo == .fizz);
14}
test/behavior/bugs/13285.zig created+11
......@@ -0,0 +1,11 @@
1const Crasher = struct {
2 lets_crash: u64 = 0,
3};
4
5test {
6 var a: Crasher = undefined;
7 var crasher_ptr = &a;
8 var crasher_local = crasher_ptr.*;
9 const crasher_local_ptr = &crasher_local;
10 crasher_local_ptr.lets_crash = 1;
11}
test/behavior/cast.zig+11
......@@ -1170,6 +1170,7 @@ test "implicitly cast from [N]T to ?[]const T" {
11701170 if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest;
11711171 if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO
11721172 if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
1173 if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO
11731174
11741175 try expect(mem.eql(u8, castToOptionalSlice().?, "hi"));
11751176 comptime try expect(mem.eql(u8, castToOptionalSlice().?, "hi"));
......@@ -1256,6 +1257,7 @@ test "*const [N]null u8 to ?[]const u8" {
12561257 if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest;
12571258 if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO
12581259 if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
1260 if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO
12591261
12601262 const S = struct {
12611263 fn doTheTest() !void {
......@@ -1394,6 +1396,8 @@ test "cast i8 fn call peers to i32 result" {
13941396test "cast compatible optional types" {
13951397 if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
13961398 if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
1399 if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO
1400 if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO
13971401
13981402 var a: ?[:0]const u8 = null;
13991403 var b: ?[]const u8 = a;
......@@ -1440,3 +1444,10 @@ test "coerce between pointers of compatible differently-named floats" {
14401444 f2.* += 1;
14411445 try expect(f1 == @as(F, 12.34) + 1);
14421446}
1447
1448test "peer type resolution of const and non-const pointer to array" {
1449 const a = @intToPtr(*[1024]u8, 42);
1450 const b = @intToPtr(*const [1024]u8, 42);
1451 try std.testing.expect(@TypeOf(a, b) == *const [1024]u8);
1452 try std.testing.expect(a == b);
1453}
test/behavior/optional.zig+16
......@@ -3,6 +3,7 @@ const std = @import("std");
33const testing = std.testing;
44const expect = testing.expect;
55const expectEqual = testing.expectEqual;
6const expectEqualStrings = std.testing.expectEqualStrings;
67
78test "passing an optional integer as a parameter" {
89 if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest;
......@@ -428,3 +429,18 @@ test "alignment of wrapping an optional payload" {
428429 };
429430 try expect(S.foo().?.x == 1234);
430431}
432
433test "Optional slice size is optimized" {
434 if (builtin.zig_backend == .stage1) return error.SkipZigTest;
435 if (builtin.zig_backend == .stage2_c) return error.SkipZigTest;
436 if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest;
437 if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest;
438 if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;
439 if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest;
440
441 try expect(@sizeOf(?[]u8) == @sizeOf([]u8));
442 var a: ?[]const u8 = null;
443 try expect(a == null);
444 a = "hello";
445 try expectEqualStrings(a.?, "hello");
446}
test/behavior/translate_c_macros.h+1
......@@ -40,6 +40,7 @@ union U {
4040#define CAST_OR_CALL_WITH_PARENS(type_or_fn, val) ((type_or_fn)(val))
4141
4242#define NESTED_COMMA_OPERATOR (1, (2, 3))
43#define NESTED_COMMA_OPERATOR_LHS (1, 2), 3
4344
4445#include <stdint.h>
4546#if !defined(__UINTPTR_MAX__)
test/behavior/translate_c_macros.zig+1
......@@ -100,6 +100,7 @@ test "nested comma operator" {
100100 if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
101101
102102 try expectEqual(@as(c_int, 3), h.NESTED_COMMA_OPERATOR);
103 try expectEqual(@as(c_int, 3), h.NESTED_COMMA_OPERATOR_LHS);
103104}
104105
105106test "cast functions" {
test/cases/compile_errors/too_big_packed_struct.zig created+13
......@@ -0,0 +1,13 @@
1pub export fn entry() void {
2 const T = packed struct {
3 a: u65535,
4 b: u65535,
5 };
6 @compileLog(@sizeOf(T));
7}
8
9// error
10// backend=stage2
11// target=native
12//
13// :2:22: error: size of packed struct '131070' exceeds maximum bit width of 65535
test/cases/compile_errors/zero-bit_generic_args_are_coerced_to_param_type.zig created+10
......@@ -0,0 +1,10 @@
1fn bar(a: anytype, _: @TypeOf(a)) void {}
2pub export fn entry() void {
3 bar(@as(u0, 0), "fooo");
4}
5
6// error
7// backend=stage2
8// target=native
9//
10// :3:21: error: expected type 'u0', found '*const [4:0]u8'
test/translate_c.zig+4-4
......@@ -499,20 +499,20 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
499499 \\int baz(int x, int y) { return 0; }
500500 \\#define bar(x) (&x, +3, 4 == 4, 5 * 6, baz(1, 2), 2 % 2, baz(1,2))
501501 , &[_][]const u8{
502 \\pub const foo = blk: {
502 \\pub const foo = blk_1: {
503503 \\ _ = @TypeOf(foo);
504 \\ break :blk bar;
504 \\ break :blk_1 bar;
505505 \\};
506506 ,
507507 \\pub inline fn bar(x: anytype) @TypeOf(baz(@as(c_int, 1), @as(c_int, 2))) {
508 \\ return blk: {
508 \\ return blk_1: {
509509 \\ _ = &x;
510510 \\ _ = @as(c_int, 3);
511511 \\ _ = @as(c_int, 4) == @as(c_int, 4);
512512 \\ _ = @as(c_int, 5) * @as(c_int, 6);
513513 \\ _ = baz(@as(c_int, 1), @as(c_int, 2));
514514 \\ _ = @as(c_int, 2) % @as(c_int, 2);
515 \\ break :blk baz(@as(c_int, 1), @as(c_int, 2));
515 \\ break :blk_1 baz(@as(c_int, 1), @as(c_int, 2));
516516 \\ };
517517 \\}
518518 });