authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2017-01-31 13:38:04-05:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2017-01-31 13:38:04-05:00
logb258fdb532a36f8ee9f091ac588a6189bad81acd
tree58d2c7e77ef90d3b60876a85ed234fff7b76efb2
parenteb00aa21f54dcfdf4e1a438c839bc4acf2033c8d

add integer literal to pointer explicit cast

closes #227

2 files changed, 35 insertions(+), 0 deletions(-)

src/ir.cpp+28
......@@ -6424,6 +6424,27 @@ static IrInstruction *ir_analyze_int_to_ptr(IrAnalyze *ira, IrInstruction *sourc
64246424 return result;
64256425}
64266426
6427static IrInstruction *ir_analyze_int_lit_to_ptr(IrAnalyze *ira, IrInstruction *source_instr,
6428 IrInstruction *target, TypeTableEntry *wanted_type)
6429{
6430 assert(wanted_type->id == TypeTableEntryIdPointer);
6431
6432 ConstExprValue *val = ir_resolve_const(ira, target, UndefBad);
6433 if (!val)
6434 return ira->codegen->invalid_instruction;
6435
6436 TypeTableEntry *usize_type = ira->codegen->builtin_types.entry_usize;
6437 if (!ir_num_lit_fits_in_other_type(ira, target, usize_type))
6438 return ira->codegen->invalid_instruction;
6439
6440 IrInstruction *result = ir_create_const(&ira->new_irb, source_instr->scope,
6441 source_instr->source_node, wanted_type, val->depends_on_compile_var);
6442 result->value.data.x_ptr.base_ptr = nullptr;
6443 result->value.data.x_ptr.index = bignum_to_twos_complement(&val->data.x_bignum);
6444 result->value.data.x_ptr.special = ConstPtrSpecialRuntime;
6445 return result;
6446}
6447
64276448static IrInstruction *ir_analyze_int_to_enum(IrAnalyze *ira, IrInstruction *source_instr,
64286449 IrInstruction *target, TypeTableEntry *wanted_type)
64296450{
......@@ -6491,6 +6512,13 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst
64916512 return ir_analyze_int_to_ptr(ira, source_instr, value, wanted_type);
64926513 }
64936514
6515 // explicit cast from number literal to pointer
6516 if (wanted_type_canon->id == TypeTableEntryIdPointer &&
6517 (actual_type_canon->id == TypeTableEntryIdNumLitInt))
6518 {
6519 return ir_analyze_int_lit_to_ptr(ira, source_instr, value, wanted_type);
6520 }
6521
64946522 // explicit widening or shortening cast
64956523 if ((wanted_type_canon->id == TypeTableEntryIdInt &&
64966524 actual_type_canon->id == TypeTableEntryIdInt) ||
test/cases/cast.zig+7
......@@ -8,3 +8,10 @@ fn intToPtrCast() {
88 const z = usize(y);
99 assert(z == 13);
1010}
11
12fn numLitIntToPtrCast() {
13 @setFnTest(this);
14
15 const vga_mem = (&u16)(0xB8000);
16 assert(usize(vga_mem) == 0xB8000);
17}