From 0d7abc6368a826490f8985634882300b50d81cba Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sat, 4 Feb 2017 10:38:28 -0500 Subject: [PATCH] add compile error when setting non power of 2 alignment --- src/ir.cpp | 9 ++++++++- test/run_tests.cpp | 7 +++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/ir.cpp b/src/ir.cpp index f56ceaf4dd..a504d6c073 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -9451,6 +9451,10 @@ static TypeTableEntry *ir_analyze_instruction_set_fn_visible(IrAnalyze *ira, return ira->codegen->builtin_types.entry_void; } +static bool is_power_of_2(uint64_t x) { + return x != 0 && ((x & (~x + 1)) == x); +} + static TypeTableEntry *ir_analyze_instruction_set_global_align(IrAnalyze *ira, IrInstructionSetGlobalAlign *instruction) { @@ -9461,7 +9465,10 @@ static TypeTableEntry *ir_analyze_instruction_set_global_align(IrAnalyze *ira, if (!ir_resolve_usize(ira, align_value, &scalar_align)) return ira->codegen->builtin_types.entry_invalid; - // TODO error if not power of 2 + if (!is_power_of_2(scalar_align)) { + ir_add_error(ira, instruction->value, buf_sprintf("alignment value must be power of 2")); + return ira->codegen->builtin_types.entry_invalid; + } AstNode *source_node = instruction->base.source_node; if (tld_var->set_global_align_node) { diff --git a/test/run_tests.cpp b/test/run_tests.cpp index 987e72aaf9..e48c080a54 100644 --- a/test/run_tests.cpp +++ b/test/run_tests.cpp @@ -1662,6 +1662,13 @@ fn foo() { } )SOURCE", 1, ".tmp_source.zig:3:24: error: integer value 753664 cannot be implicitly casted to type 'u16'"); + add_compile_fail_case("set global variable alignment to non power of 2", R"SOURCE( +const some_data: [100]u8 = { + @setGlobalAlign(some_data, 3); + undefined +}; + )SOURCE", 1, ".tmp_source.zig:3:32: error: alignment value must be power of 2"); + } //////////////////////////////////////////////////////////////////////////////