zig

fork of https://codeberg.org/ziglang/zig
Log | Files | Refs | README | LICENSE

blob cf71bd90 (322203B) - Raw


      1 /*
      2  * Copyright (c) 2015 Andrew Kelley
      3  *
      4  * This file is part of zig, which is MIT licensed.
      5  * See http://opensource.org/licenses/MIT
      6  */
      7 
      8 #include "analyze.hpp"
      9 #include "ast_render.hpp"
     10 #include "codegen.hpp"
     11 #include "config.h"
     12 #include "error.hpp"
     13 #include "ir.hpp"
     14 #include "ir_print.hpp"
     15 #include "os.hpp"
     16 #include "parser.hpp"
     17 #include "softfloat.hpp"
     18 #include "zig_llvm.h"
     19 
     20 
     21 static const size_t default_backward_branch_quota = 1000;
     22 
     23 static Error resolve_struct_type(CodeGen *g, ZigType *struct_type);
     24 
     25 static Error ATTRIBUTE_MUST_USE resolve_struct_zero_bits(CodeGen *g, ZigType *struct_type);
     26 static Error ATTRIBUTE_MUST_USE resolve_struct_alignment(CodeGen *g, ZigType *struct_type);
     27 static Error ATTRIBUTE_MUST_USE resolve_enum_zero_bits(CodeGen *g, ZigType *enum_type);
     28 static Error ATTRIBUTE_MUST_USE resolve_union_zero_bits(CodeGen *g, ZigType *union_type);
     29 static Error ATTRIBUTE_MUST_USE resolve_union_alignment(CodeGen *g, ZigType *union_type);
     30 static void analyze_fn_body(CodeGen *g, ZigFn *fn_table_entry);
     31 static void resolve_llvm_types(CodeGen *g, ZigType *type, ResolveStatus wanted_resolve_status);
     32 static void preview_use_decl(CodeGen *g, TldUsingNamespace *using_namespace, ScopeDecls *dest_decls_scope);
     33 static void resolve_use_decl(CodeGen *g, TldUsingNamespace *tld_using_namespace, ScopeDecls *dest_decls_scope);
     34 
     35 // nullptr means not analyzed yet; this one means currently being analyzed
     36 static const AstNode *inferred_async_checking = reinterpret_cast<AstNode *>(0x1);
     37 // this one means analyzed and it's not async
     38 static const AstNode *inferred_async_none = reinterpret_cast<AstNode *>(0x2);
     39 
     40 static bool is_top_level_struct(ZigType *import) {
     41     return import->id == ZigTypeIdStruct && import->data.structure.root_struct != nullptr;
     42 }
     43 
     44 static ErrorMsg *add_error_note_token(CodeGen *g, ErrorMsg *parent_msg, ZigType *owner, Token *token, Buf *msg) {
     45     assert(is_top_level_struct(owner));
     46     RootStruct *root_struct = owner->data.structure.root_struct;
     47 
     48     ErrorMsg *err = err_msg_create_with_line(root_struct->path, token->start_line, token->start_column,
     49             root_struct->source_code, root_struct->line_offsets, msg);
     50 
     51     err_msg_add_note(parent_msg, err);
     52     return err;
     53 }
     54 
     55 ErrorMsg *add_token_error(CodeGen *g, ZigType *owner, Token *token, Buf *msg) {
     56     assert(is_top_level_struct(owner));
     57     RootStruct *root_struct = owner->data.structure.root_struct;
     58     ErrorMsg *err = err_msg_create_with_line(root_struct->path, token->start_line, token->start_column,
     59             root_struct->source_code, root_struct->line_offsets, msg);
     60 
     61     g->errors.append(err);
     62     return err;
     63 }
     64 
     65 ErrorMsg *add_node_error(CodeGen *g, const AstNode *node, Buf *msg) {
     66     Token fake_token;
     67     fake_token.start_line = node->line;
     68     fake_token.start_column = node->column;
     69     return add_token_error(g, node->owner, &fake_token, msg);
     70 }
     71 
     72 ErrorMsg *add_error_note(CodeGen *g, ErrorMsg *parent_msg, const AstNode *node, Buf *msg) {
     73     Token fake_token;
     74     fake_token.start_line = node->line;
     75     fake_token.start_column = node->column;
     76     return add_error_note_token(g, parent_msg, node->owner, &fake_token, msg);
     77 }
     78 
     79 ZigType *new_type_table_entry(ZigTypeId id) {
     80     ZigType *entry = allocate<ZigType>(1);
     81     entry->id = id;
     82     return entry;
     83 }
     84 
     85 static ScopeDecls **get_container_scope_ptr(ZigType *type_entry) {
     86     if (type_entry->id == ZigTypeIdStruct) {
     87         return &type_entry->data.structure.decls_scope;
     88     } else if (type_entry->id == ZigTypeIdEnum) {
     89         return &type_entry->data.enumeration.decls_scope;
     90     } else if (type_entry->id == ZigTypeIdUnion) {
     91         return &type_entry->data.unionation.decls_scope;
     92     }
     93     zig_unreachable();
     94 }
     95 
     96 ScopeDecls *get_container_scope(ZigType *type_entry) {
     97     return *get_container_scope_ptr(type_entry);
     98 }
     99 
    100 void init_scope(CodeGen *g, Scope *dest, ScopeId id, AstNode *source_node, Scope *parent) {
    101     dest->codegen = g;
    102     dest->id = id;
    103     dest->source_node = source_node;
    104     dest->parent = parent;
    105 }
    106 
    107 static ScopeDecls *create_decls_scope(CodeGen *g, AstNode *node, Scope *parent, ZigType *container_type,
    108         ZigType *import, Buf *bare_name)
    109 {
    110     assert(node == nullptr || node->type == NodeTypeContainerDecl || node->type == NodeTypeFnCallExpr);
    111     ScopeDecls *scope = allocate<ScopeDecls>(1);
    112     init_scope(g, &scope->base, ScopeIdDecls, node, parent);
    113     scope->decl_table.init(4);
    114     scope->container_type = container_type;
    115     scope->import = import;
    116     scope->bare_name = bare_name;
    117     return scope;
    118 }
    119 
    120 ScopeBlock *create_block_scope(CodeGen *g, AstNode *node, Scope *parent) {
    121     assert(node->type == NodeTypeBlock);
    122     ScopeBlock *scope = allocate<ScopeBlock>(1);
    123     init_scope(g, &scope->base, ScopeIdBlock, node, parent);
    124     scope->name = node->data.block.name;
    125     return scope;
    126 }
    127 
    128 ScopeDefer *create_defer_scope(CodeGen *g, AstNode *node, Scope *parent) {
    129     assert(node->type == NodeTypeDefer);
    130     ScopeDefer *scope = allocate<ScopeDefer>(1);
    131     init_scope(g, &scope->base, ScopeIdDefer, node, parent);
    132     return scope;
    133 }
    134 
    135 ScopeDeferExpr *create_defer_expr_scope(CodeGen *g, AstNode *node, Scope *parent) {
    136     assert(node->type == NodeTypeDefer);
    137     ScopeDeferExpr *scope = allocate<ScopeDeferExpr>(1);
    138     init_scope(g, &scope->base, ScopeIdDeferExpr, node, parent);
    139     return scope;
    140 }
    141 
    142 Scope *create_var_scope(CodeGen *g, AstNode *node, Scope *parent, ZigVar *var) {
    143     ScopeVarDecl *scope = allocate<ScopeVarDecl>(1);
    144     init_scope(g, &scope->base, ScopeIdVarDecl, node, parent);
    145     scope->var = var;
    146     return &scope->base;
    147 }
    148 
    149 ScopeCImport *create_cimport_scope(CodeGen *g, AstNode *node, Scope *parent) {
    150     assert(node->type == NodeTypeFnCallExpr);
    151     ScopeCImport *scope = allocate<ScopeCImport>(1);
    152     init_scope(g, &scope->base, ScopeIdCImport, node, parent);
    153     buf_resize(&scope->buf, 0);
    154     return scope;
    155 }
    156 
    157 ScopeLoop *create_loop_scope(CodeGen *g, AstNode *node, Scope *parent) {
    158     ScopeLoop *scope = allocate<ScopeLoop>(1);
    159     init_scope(g, &scope->base, ScopeIdLoop, node, parent);
    160     if (node->type == NodeTypeWhileExpr) {
    161         scope->name = node->data.while_expr.name;
    162     } else if (node->type == NodeTypeForExpr) {
    163         scope->name = node->data.for_expr.name;
    164     } else {
    165         zig_unreachable();
    166     }
    167     return scope;
    168 }
    169 
    170 Scope *create_runtime_scope(CodeGen *g, AstNode *node, Scope *parent, IrInstruction *is_comptime) {
    171     ScopeRuntime *scope = allocate<ScopeRuntime>(1);
    172     scope->is_comptime = is_comptime;
    173     init_scope(g, &scope->base, ScopeIdRuntime, node, parent);
    174     return &scope->base;
    175 }
    176 
    177 ScopeSuspend *create_suspend_scope(CodeGen *g, AstNode *node, Scope *parent) {
    178     assert(node->type == NodeTypeSuspend);
    179     ScopeSuspend *scope = allocate<ScopeSuspend>(1);
    180     init_scope(g, &scope->base, ScopeIdSuspend, node, parent);
    181     return scope;
    182 }
    183 
    184 ScopeFnDef *create_fndef_scope(CodeGen *g, AstNode *node, Scope *parent, ZigFn *fn_entry) {
    185     ScopeFnDef *scope = allocate<ScopeFnDef>(1);
    186     init_scope(g, &scope->base, ScopeIdFnDef, node, parent);
    187     scope->fn_entry = fn_entry;
    188     return scope;
    189 }
    190 
    191 Scope *create_comptime_scope(CodeGen *g, AstNode *node, Scope *parent) {
    192     ScopeCompTime *scope = allocate<ScopeCompTime>(1);
    193     init_scope(g, &scope->base, ScopeIdCompTime, node, parent);
    194     return &scope->base;
    195 }
    196 
    197 ZigType *get_scope_import(Scope *scope) {
    198     while (scope) {
    199         if (scope->id == ScopeIdDecls) {
    200             ScopeDecls *decls_scope = (ScopeDecls *)scope;
    201             assert(is_top_level_struct(decls_scope->import));
    202             return decls_scope->import;
    203         }
    204         scope = scope->parent;
    205     }
    206     zig_unreachable();
    207 }
    208 
    209 static ZigType *new_container_type_entry(CodeGen *g, ZigTypeId id, AstNode *source_node, Scope *parent_scope,
    210         Buf *bare_name)
    211 {
    212     ZigType *entry = new_type_table_entry(id);
    213     *get_container_scope_ptr(entry) = create_decls_scope(g, source_node, parent_scope, entry,
    214             get_scope_import(parent_scope), bare_name);
    215     return entry;
    216 }
    217 
    218 static uint8_t bits_needed_for_unsigned(uint64_t x) {
    219     if (x == 0) {
    220         return 0;
    221     }
    222     uint8_t base = log2_u64(x);
    223     uint64_t upper = (((uint64_t)1) << base) - 1;
    224     return (upper >= x) ? base : (base + 1);
    225 }
    226 
    227 AstNode *type_decl_node(ZigType *type_entry) {
    228     switch (type_entry->id) {
    229         case ZigTypeIdInvalid:
    230             zig_unreachable();
    231         case ZigTypeIdStruct:
    232             return type_entry->data.structure.decl_node;
    233         case ZigTypeIdEnum:
    234             return type_entry->data.enumeration.decl_node;
    235         case ZigTypeIdUnion:
    236             return type_entry->data.unionation.decl_node;
    237         case ZigTypeIdCoroFrame:
    238             return type_entry->data.frame.fn->proto_node;
    239         case ZigTypeIdOpaque:
    240         case ZigTypeIdMetaType:
    241         case ZigTypeIdVoid:
    242         case ZigTypeIdBool:
    243         case ZigTypeIdUnreachable:
    244         case ZigTypeIdInt:
    245         case ZigTypeIdFloat:
    246         case ZigTypeIdPointer:
    247         case ZigTypeIdArray:
    248         case ZigTypeIdComptimeFloat:
    249         case ZigTypeIdComptimeInt:
    250         case ZigTypeIdEnumLiteral:
    251         case ZigTypeIdUndefined:
    252         case ZigTypeIdNull:
    253         case ZigTypeIdOptional:
    254         case ZigTypeIdErrorUnion:
    255         case ZigTypeIdErrorSet:
    256         case ZigTypeIdFn:
    257         case ZigTypeIdBoundFn:
    258         case ZigTypeIdArgTuple:
    259         case ZigTypeIdVector:
    260         case ZigTypeIdAnyFrame:
    261             return nullptr;
    262     }
    263     zig_unreachable();
    264 }
    265 
    266 bool type_is_resolved(ZigType *type_entry, ResolveStatus status) {
    267     switch (type_entry->id) {
    268         case ZigTypeIdInvalid:
    269             zig_unreachable();
    270         case ZigTypeIdStruct:
    271             return type_entry->data.structure.resolve_status >= status;
    272         case ZigTypeIdUnion:
    273             return type_entry->data.unionation.resolve_status >= status;
    274         case ZigTypeIdCoroFrame:
    275             switch (status) {
    276                 case ResolveStatusInvalid:
    277                     zig_unreachable();
    278                 case ResolveStatusUnstarted:
    279                 case ResolveStatusZeroBitsKnown:
    280                     return true;
    281                 case ResolveStatusAlignmentKnown:
    282                 case ResolveStatusSizeKnown:
    283                     return type_entry->data.frame.locals_struct != nullptr;
    284                 case ResolveStatusLLVMFwdDecl:
    285                 case ResolveStatusLLVMFull:
    286                     return type_entry->llvm_type != nullptr;
    287             }
    288         case ZigTypeIdEnum:
    289             switch (status) {
    290                 case ResolveStatusUnstarted:
    291                     return true;
    292                 case ResolveStatusInvalid:
    293                     zig_unreachable();
    294                 case ResolveStatusZeroBitsKnown:
    295                     return type_entry->data.enumeration.zero_bits_known;
    296                 case ResolveStatusAlignmentKnown:
    297                     return type_entry->data.enumeration.zero_bits_known;
    298                 case ResolveStatusSizeKnown:
    299                     return type_entry->data.enumeration.complete;
    300                 case ResolveStatusLLVMFwdDecl:
    301                 case ResolveStatusLLVMFull:
    302                     return type_entry->llvm_di_type != nullptr;
    303             }
    304             zig_unreachable();
    305         case ZigTypeIdOpaque:
    306             return status < ResolveStatusSizeKnown;
    307         case ZigTypeIdMetaType:
    308         case ZigTypeIdVoid:
    309         case ZigTypeIdBool:
    310         case ZigTypeIdUnreachable:
    311         case ZigTypeIdInt:
    312         case ZigTypeIdFloat:
    313         case ZigTypeIdPointer:
    314         case ZigTypeIdArray:
    315         case ZigTypeIdComptimeFloat:
    316         case ZigTypeIdComptimeInt:
    317         case ZigTypeIdEnumLiteral:
    318         case ZigTypeIdUndefined:
    319         case ZigTypeIdNull:
    320         case ZigTypeIdOptional:
    321         case ZigTypeIdErrorUnion:
    322         case ZigTypeIdErrorSet:
    323         case ZigTypeIdFn:
    324         case ZigTypeIdBoundFn:
    325         case ZigTypeIdArgTuple:
    326         case ZigTypeIdVector:
    327         case ZigTypeIdAnyFrame:
    328             return true;
    329     }
    330     zig_unreachable();
    331 }
    332 
    333 bool type_is_complete(ZigType *type_entry) {
    334     return type_is_resolved(type_entry, ResolveStatusSizeKnown);
    335 }
    336 
    337 uint64_t type_size(CodeGen *g, ZigType *type_entry) {
    338     assert(type_is_resolved(type_entry, ResolveStatusSizeKnown));
    339     return type_entry->abi_size;
    340 }
    341 
    342 uint64_t type_size_bits(CodeGen *g, ZigType *type_entry) {
    343     assert(type_is_resolved(type_entry, ResolveStatusSizeKnown));
    344     return type_entry->size_in_bits;
    345 }
    346 
    347 uint32_t get_abi_alignment(CodeGen *g, ZigType *type_entry) {
    348     assert(type_is_resolved(type_entry, ResolveStatusAlignmentKnown));
    349     return type_entry->abi_align;
    350 }
    351 
    352 static bool is_slice(ZigType *type) {
    353     return type->id == ZigTypeIdStruct && type->data.structure.is_slice;
    354 }
    355 
    356 ZigType *get_smallest_unsigned_int_type(CodeGen *g, uint64_t x) {
    357     return get_int_type(g, false, bits_needed_for_unsigned(x));
    358 }
    359 
    360 ZigType *get_any_frame_type(CodeGen *g, ZigType *result_type) {
    361     if (result_type != nullptr && result_type->any_frame_parent != nullptr) {
    362         return result_type->any_frame_parent;
    363     } else if (result_type == nullptr && g->builtin_types.entry_any_frame != nullptr) {
    364         return g->builtin_types.entry_any_frame;
    365     }
    366 
    367     ZigType *entry = new_type_table_entry(ZigTypeIdAnyFrame);
    368     entry->abi_size = g->builtin_types.entry_usize->abi_size;
    369     entry->size_in_bits = g->builtin_types.entry_usize->size_in_bits;
    370     entry->abi_align = g->builtin_types.entry_usize->abi_align;
    371     entry->data.any_frame.result_type = result_type;
    372     buf_init_from_str(&entry->name, "anyframe");
    373     if (result_type != nullptr) {
    374         buf_appendf(&entry->name, "->%s", buf_ptr(&result_type->name));
    375     }
    376 
    377     if (result_type != nullptr) {
    378         result_type->any_frame_parent = entry;
    379     } else if (result_type == nullptr) {
    380         g->builtin_types.entry_any_frame = entry;
    381     }
    382     return entry;
    383 }
    384 
    385 static const char *ptr_len_to_star_str(PtrLen ptr_len) {
    386     switch (ptr_len) {
    387         case PtrLenSingle:
    388             return "*";
    389         case PtrLenUnknown:
    390             return "[*]";
    391         case PtrLenC:
    392             return "[*c]";
    393     }
    394     zig_unreachable();
    395 }
    396 
    397 ZigType *get_coro_frame_type(CodeGen *g, ZigFn *fn) {
    398     if (fn->frame_type != nullptr) {
    399         return fn->frame_type;
    400     }
    401 
    402     ZigType *entry = new_type_table_entry(ZigTypeIdCoroFrame);
    403     buf_resize(&entry->name, 0);
    404     buf_appendf(&entry->name, "@Frame(%s)", buf_ptr(&fn->symbol_name));
    405 
    406     entry->data.frame.fn = fn;
    407 
    408     // Coroutine frames are always non-zero bits because they always have a resume index.
    409     entry->abi_size = SIZE_MAX;
    410     entry->size_in_bits = SIZE_MAX;
    411 
    412     fn->frame_type = entry;
    413     return entry;
    414 }
    415 
    416 ZigType *get_pointer_to_type_extra(CodeGen *g, ZigType *child_type, bool is_const,
    417         bool is_volatile, PtrLen ptr_len, uint32_t byte_alignment,
    418         uint32_t bit_offset_in_host, uint32_t host_int_bytes, bool allow_zero)
    419 {
    420     assert(ptr_len != PtrLenC || allow_zero);
    421     assert(!type_is_invalid(child_type));
    422     assert(ptr_len == PtrLenSingle || child_type->id != ZigTypeIdOpaque);
    423 
    424     if (byte_alignment != 0) {
    425         uint32_t abi_alignment = get_abi_alignment(g, child_type);
    426         if (byte_alignment == abi_alignment)
    427             byte_alignment = 0;
    428     }
    429 
    430     if (host_int_bytes != 0) {
    431         uint32_t child_type_bits = type_size_bits(g, child_type);
    432         if (host_int_bytes * 8 == child_type_bits) {
    433             assert(bit_offset_in_host == 0);
    434             host_int_bytes = 0;
    435         }
    436     }
    437 
    438     TypeId type_id = {};
    439     ZigType **parent_pointer = nullptr;
    440     if (host_int_bytes != 0 || is_volatile || byte_alignment != 0 || ptr_len != PtrLenSingle || allow_zero) {
    441         type_id.id = ZigTypeIdPointer;
    442         type_id.data.pointer.child_type = child_type;
    443         type_id.data.pointer.is_const = is_const;
    444         type_id.data.pointer.is_volatile = is_volatile;
    445         type_id.data.pointer.alignment = byte_alignment;
    446         type_id.data.pointer.bit_offset_in_host = bit_offset_in_host;
    447         type_id.data.pointer.host_int_bytes = host_int_bytes;
    448         type_id.data.pointer.ptr_len = ptr_len;
    449         type_id.data.pointer.allow_zero = allow_zero;
    450 
    451         auto existing_entry = g->type_table.maybe_get(type_id);
    452         if (existing_entry)
    453             return existing_entry->value;
    454     } else {
    455         assert(bit_offset_in_host == 0);
    456         parent_pointer = &child_type->pointer_parent[(is_const ? 1 : 0)];
    457         if (*parent_pointer) {
    458             assert((*parent_pointer)->data.pointer.explicit_alignment == 0);
    459             return *parent_pointer;
    460         }
    461     }
    462 
    463     assert(type_is_resolved(child_type, ResolveStatusZeroBitsKnown));
    464 
    465     ZigType *entry = new_type_table_entry(ZigTypeIdPointer);
    466 
    467     const char *star_str = ptr_len_to_star_str(ptr_len);
    468     const char *const_str = is_const ? "const " : "";
    469     const char *volatile_str = is_volatile ? "volatile " : "";
    470     const char *allow_zero_str;
    471     if (ptr_len == PtrLenC) {
    472         assert(allow_zero);
    473         allow_zero_str = "";
    474     } else {
    475         allow_zero_str = allow_zero ? "allowzero " : "";
    476     }
    477     buf_resize(&entry->name, 0);
    478     if (host_int_bytes == 0 && byte_alignment == 0) {
    479         buf_appendf(&entry->name, "%s%s%s%s%s",
    480                 star_str, const_str, volatile_str, allow_zero_str, buf_ptr(&child_type->name));
    481     } else if (host_int_bytes == 0) {
    482         buf_appendf(&entry->name, "%salign(%" PRIu32 ") %s%s%s%s", star_str, byte_alignment,
    483                 const_str, volatile_str, allow_zero_str, buf_ptr(&child_type->name));
    484     } else if (byte_alignment == 0) {
    485         buf_appendf(&entry->name, "%salign(:%" PRIu32 ":%" PRIu32 ") %s%s%s%s", star_str,
    486                 bit_offset_in_host, host_int_bytes, const_str, volatile_str, allow_zero_str,
    487                 buf_ptr(&child_type->name));
    488     } else {
    489         buf_appendf(&entry->name, "%salign(%" PRIu32 ":%" PRIu32 ":%" PRIu32 ") %s%s%s%s", star_str, byte_alignment,
    490                 bit_offset_in_host, host_int_bytes, const_str, volatile_str, allow_zero_str,
    491                 buf_ptr(&child_type->name));
    492     }
    493 
    494     assert(child_type->id != ZigTypeIdInvalid);
    495 
    496     if (type_has_bits(child_type)) {
    497         entry->abi_size = g->builtin_types.entry_usize->abi_size;
    498         entry->size_in_bits = g->builtin_types.entry_usize->size_in_bits;
    499         entry->abi_align = g->builtin_types.entry_usize->abi_align;
    500     } else {
    501         assert(byte_alignment == 0);
    502         entry->abi_size = 0;
    503         entry->size_in_bits = 0;
    504         entry->abi_align = 0;
    505     }
    506 
    507     entry->data.pointer.ptr_len = ptr_len;
    508     entry->data.pointer.child_type = child_type;
    509     entry->data.pointer.is_const = is_const;
    510     entry->data.pointer.is_volatile = is_volatile;
    511     entry->data.pointer.explicit_alignment = byte_alignment;
    512     entry->data.pointer.bit_offset_in_host = bit_offset_in_host;
    513     entry->data.pointer.host_int_bytes = host_int_bytes;
    514     entry->data.pointer.allow_zero = allow_zero;
    515 
    516     if (parent_pointer) {
    517         *parent_pointer = entry;
    518     } else {
    519         g->type_table.put(type_id, entry);
    520     }
    521     return entry;
    522 }
    523 
    524 ZigType *get_pointer_to_type(CodeGen *g, ZigType *child_type, bool is_const) {
    525     return get_pointer_to_type_extra(g, child_type, is_const, false, PtrLenSingle, 0, 0, 0, false);
    526 }
    527 
    528 ZigType *get_optional_type(CodeGen *g, ZigType *child_type) {
    529     if (child_type->optional_parent != nullptr) {
    530         return child_type->optional_parent;
    531     }
    532 
    533     assert(type_is_resolved(child_type, ResolveStatusSizeKnown));
    534 
    535     ZigType *entry = new_type_table_entry(ZigTypeIdOptional);
    536 
    537     buf_resize(&entry->name, 0);
    538     buf_appendf(&entry->name, "?%s", buf_ptr(&child_type->name));
    539 
    540     if (!type_has_bits(child_type)) {
    541         entry->size_in_bits = g->builtin_types.entry_bool->size_in_bits;
    542         entry->abi_size = g->builtin_types.entry_bool->abi_size;
    543         entry->abi_align = g->builtin_types.entry_bool->abi_align;
    544     } else if (type_is_nonnull_ptr(child_type) || child_type->id == ZigTypeIdErrorSet) {
    545         // This is an optimization but also is necessary for calling C
    546         // functions where all pointers are optional pointers.
    547         // Function types are technically pointers.
    548         entry->size_in_bits = child_type->size_in_bits;
    549         entry->abi_size = child_type->abi_size;
    550         entry->abi_align = child_type->abi_align;
    551     } else {
    552         // This value only matters if the type is legal in a packed struct, which is not
    553         // true for optional types which did not fit the above 2 categories (zero bit child type,
    554         // or nonnull ptr child type, or error set child type).
    555         entry->size_in_bits = child_type->size_in_bits + 1;
    556 
    557         // We're going to make a struct with the child type as the first field,
    558         // and a bool as the second. Since the child type's abi alignment is guaranteed
    559         // to be >= the bool's abi size (1 byte), the added size is exactly equal to the
    560         // child type's ABI alignment.
    561         assert(child_type->abi_align >= g->builtin_types.entry_bool->abi_size);
    562         entry->abi_align = child_type->abi_align;
    563         entry->abi_size = child_type->abi_size + child_type->abi_align;
    564     }
    565 
    566     entry->data.maybe.child_type = child_type;
    567 
    568     child_type->optional_parent = entry;
    569     return entry;
    570 }
    571 
    572 static size_t align_forward(size_t addr, size_t alignment) {
    573     return (addr + alignment - 1) & ~(alignment - 1);
    574 }
    575 
    576 static size_t next_field_offset(size_t offset, size_t align_from_zero, size_t field_size, size_t next_field_align) {
    577     // Convert offset to a pretend address which has the specified alignment.
    578     size_t addr = offset + align_from_zero;
    579     // March the address forward to respect the field alignment.
    580     size_t aligned_addr = align_forward(addr + field_size, next_field_align);
    581     // Convert back from pretend address to offset.
    582     return aligned_addr - align_from_zero;
    583 }
    584 
    585 ZigType *get_error_union_type(CodeGen *g, ZigType *err_set_type, ZigType *payload_type) {
    586     assert(err_set_type->id == ZigTypeIdErrorSet);
    587     assert(!type_is_invalid(payload_type));
    588 
    589     TypeId type_id = {};
    590     type_id.id = ZigTypeIdErrorUnion;
    591     type_id.data.error_union.err_set_type = err_set_type;
    592     type_id.data.error_union.payload_type = payload_type;
    593 
    594     auto existing_entry = g->type_table.maybe_get(type_id);
    595     if (existing_entry) {
    596         return existing_entry->value;
    597     }
    598 
    599     ZigType *entry = new_type_table_entry(ZigTypeIdErrorUnion);
    600     assert(type_is_resolved(payload_type, ResolveStatusSizeKnown));
    601 
    602     buf_resize(&entry->name, 0);
    603     buf_appendf(&entry->name, "%s!%s", buf_ptr(&err_set_type->name), buf_ptr(&payload_type->name));
    604 
    605     entry->data.error_union.err_set_type = err_set_type;
    606     entry->data.error_union.payload_type = payload_type;
    607 
    608     if (!type_has_bits(payload_type)) {
    609         if (type_has_bits(err_set_type)) {
    610             entry->size_in_bits = err_set_type->size_in_bits;
    611             entry->abi_size = err_set_type->abi_size;
    612             entry->abi_align = err_set_type->abi_align;
    613         } else {
    614             entry->size_in_bits = 0;
    615             entry->abi_size = 0;
    616             entry->abi_align = 0;
    617         }
    618     } else if (!type_has_bits(err_set_type)) {
    619         entry->size_in_bits = payload_type->size_in_bits;
    620         entry->abi_size = payload_type->abi_size;
    621         entry->abi_align = payload_type->abi_align;
    622     } else {
    623         entry->abi_align = max(err_set_type->abi_align, payload_type->abi_align);
    624         size_t field_sizes[2];
    625         size_t field_aligns[2];
    626         field_sizes[err_union_err_index] = err_set_type->abi_size;
    627         field_aligns[err_union_err_index] = err_set_type->abi_align;
    628         field_sizes[err_union_payload_index] = payload_type->abi_size;
    629         field_aligns[err_union_payload_index] = payload_type->abi_align;
    630         size_t field2_offset = next_field_offset(0, entry->abi_align, field_sizes[0], field_aligns[1]);
    631         entry->abi_size = next_field_offset(field2_offset, entry->abi_align, field_sizes[1], entry->abi_align);
    632         entry->size_in_bits = entry->abi_size * 8;
    633     }
    634 
    635     g->type_table.put(type_id, entry);
    636     return entry;
    637 }
    638 
    639 ZigType *get_array_type(CodeGen *g, ZigType *child_type, uint64_t array_size) {
    640     TypeId type_id = {};
    641     type_id.id = ZigTypeIdArray;
    642     type_id.data.array.child_type = child_type;
    643     type_id.data.array.size = array_size;
    644     auto existing_entry = g->type_table.maybe_get(type_id);
    645     if (existing_entry) {
    646         return existing_entry->value;
    647     }
    648 
    649     assert(type_is_resolved(child_type, ResolveStatusSizeKnown));
    650 
    651     ZigType *entry = new_type_table_entry(ZigTypeIdArray);
    652 
    653     buf_resize(&entry->name, 0);
    654     buf_appendf(&entry->name, "[%" ZIG_PRI_u64 "]%s", array_size, buf_ptr(&child_type->name));
    655 
    656     entry->size_in_bits = child_type->size_in_bits * array_size;
    657     entry->abi_align = child_type->abi_align;
    658     entry->abi_size = child_type->abi_size * array_size;
    659 
    660     entry->data.array.child_type = child_type;
    661     entry->data.array.len = array_size;
    662 
    663     g->type_table.put(type_id, entry);
    664     return entry;
    665 }
    666 
    667 ZigType *get_slice_type(CodeGen *g, ZigType *ptr_type) {
    668     assert(ptr_type->id == ZigTypeIdPointer);
    669     assert(ptr_type->data.pointer.ptr_len == PtrLenUnknown);
    670 
    671     ZigType **parent_pointer = &ptr_type->data.pointer.slice_parent;
    672     if (*parent_pointer) {
    673         return *parent_pointer;
    674     }
    675 
    676     ZigType *entry = new_type_table_entry(ZigTypeIdStruct);
    677 
    678     // replace the & with [] to go from a ptr type name to a slice type name
    679     buf_resize(&entry->name, 0);
    680     size_t name_offset = (ptr_type->data.pointer.ptr_len == PtrLenSingle) ? 1 : 3;
    681     buf_appendf(&entry->name, "[]%s", buf_ptr(&ptr_type->name) + name_offset);
    682 
    683     unsigned element_count = 2;
    684     Buf *ptr_field_name = buf_create_from_str("ptr");
    685     Buf *len_field_name = buf_create_from_str("len");
    686 
    687     entry->data.structure.resolve_status = ResolveStatusSizeKnown;
    688     entry->data.structure.layout = ContainerLayoutAuto;
    689     entry->data.structure.is_slice = true;
    690     entry->data.structure.src_field_count = element_count;
    691     entry->data.structure.gen_field_count = element_count;
    692     entry->data.structure.fields = allocate<TypeStructField>(element_count);
    693     entry->data.structure.fields_by_name.init(element_count);
    694     entry->data.structure.fields[slice_ptr_index].name = ptr_field_name;
    695     entry->data.structure.fields[slice_ptr_index].type_entry = ptr_type;
    696     entry->data.structure.fields[slice_ptr_index].src_index = slice_ptr_index;
    697     entry->data.structure.fields[slice_ptr_index].gen_index = 0;
    698     entry->data.structure.fields[slice_len_index].name = len_field_name;
    699     entry->data.structure.fields[slice_len_index].type_entry = g->builtin_types.entry_usize;
    700     entry->data.structure.fields[slice_len_index].src_index = slice_len_index;
    701     entry->data.structure.fields[slice_len_index].gen_index = 1;
    702 
    703     entry->data.structure.fields_by_name.put(ptr_field_name, &entry->data.structure.fields[slice_ptr_index]);
    704     entry->data.structure.fields_by_name.put(len_field_name, &entry->data.structure.fields[slice_len_index]);
    705 
    706     switch (type_requires_comptime(g, ptr_type)) {
    707         case ReqCompTimeInvalid:
    708             zig_unreachable();
    709         case ReqCompTimeNo:
    710             break;
    711         case ReqCompTimeYes:
    712             entry->data.structure.requires_comptime = true;
    713     }
    714 
    715     if (!type_has_bits(ptr_type)) {
    716         entry->data.structure.gen_field_count = 1;
    717         entry->data.structure.fields[slice_ptr_index].gen_index = SIZE_MAX;
    718         entry->data.structure.fields[slice_len_index].gen_index = 0;
    719     }
    720 
    721     ZigType *child_type = ptr_type->data.pointer.child_type;
    722     if (ptr_type->data.pointer.is_const || ptr_type->data.pointer.is_volatile ||
    723         ptr_type->data.pointer.explicit_alignment != 0 || ptr_type->data.pointer.allow_zero)
    724     {
    725         ZigType *peer_ptr_type = get_pointer_to_type_extra(g, child_type, false, false,
    726                 PtrLenUnknown, 0, 0, 0, false);
    727         ZigType *peer_slice_type = get_slice_type(g, peer_ptr_type);
    728 
    729         entry->size_in_bits = peer_slice_type->size_in_bits;
    730         entry->abi_size = peer_slice_type->abi_size;
    731         entry->abi_align = peer_slice_type->abi_align;
    732 
    733         *parent_pointer = entry;
    734         return entry;
    735     }
    736 
    737     if (type_has_bits(ptr_type)) {
    738         entry->size_in_bits = ptr_type->size_in_bits + g->builtin_types.entry_usize->size_in_bits;
    739         entry->abi_size = ptr_type->abi_size + g->builtin_types.entry_usize->abi_size;
    740         entry->abi_align = ptr_type->abi_align;
    741     } else {
    742         entry->size_in_bits = g->builtin_types.entry_usize->size_in_bits;
    743         entry->abi_size = g->builtin_types.entry_usize->abi_size;
    744         entry->abi_align = g->builtin_types.entry_usize->abi_align;
    745     }
    746 
    747     *parent_pointer = entry;
    748     return entry;
    749 }
    750 
    751 ZigType *get_opaque_type(CodeGen *g, Scope *scope, AstNode *source_node, const char *full_name, Buf *bare_name) {
    752     ZigType *entry = new_type_table_entry(ZigTypeIdOpaque);
    753 
    754     buf_init_from_str(&entry->name, full_name);
    755 
    756     ZigType *import = scope ? get_scope_import(scope) : nullptr;
    757     unsigned line = source_node ? (unsigned)(source_node->line + 1) : 0;
    758 
    759     entry->llvm_type = LLVMInt8Type();
    760     entry->llvm_di_type = ZigLLVMCreateDebugForwardDeclType(g->dbuilder,
    761         ZigLLVMTag_DW_structure_type(), full_name,
    762         import ? ZigLLVMFileToScope(import->data.structure.root_struct->di_file) : nullptr,
    763         import ? import->data.structure.root_struct->di_file : nullptr,
    764         line);
    765     entry->data.opaque.bare_name = bare_name;
    766 
    767     // The actual size is unknown, but the value must not be 0 because that
    768     // is how type_has_bits is determined.
    769     entry->abi_size = SIZE_MAX;
    770     entry->size_in_bits = SIZE_MAX;
    771     entry->abi_align = 1;
    772 
    773     return entry;
    774 }
    775 
    776 ZigType *get_bound_fn_type(CodeGen *g, ZigFn *fn_entry) {
    777     ZigType *fn_type = fn_entry->type_entry;
    778     assert(fn_type->id == ZigTypeIdFn);
    779     if (fn_type->data.fn.bound_fn_parent)
    780         return fn_type->data.fn.bound_fn_parent;
    781 
    782     ZigType *bound_fn_type = new_type_table_entry(ZigTypeIdBoundFn);
    783     bound_fn_type->data.bound_fn.fn_type = fn_type;
    784 
    785     buf_resize(&bound_fn_type->name, 0);
    786     buf_appendf(&bound_fn_type->name, "(bound %s)", buf_ptr(&fn_type->name));
    787 
    788     fn_type->data.fn.bound_fn_parent = bound_fn_type;
    789     return bound_fn_type;
    790 }
    791 
    792 const char *calling_convention_name(CallingConvention cc) {
    793     switch (cc) {
    794         case CallingConventionUnspecified: return "undefined";
    795         case CallingConventionC: return "ccc";
    796         case CallingConventionCold: return "coldcc";
    797         case CallingConventionNaked: return "nakedcc";
    798         case CallingConventionStdcall: return "stdcallcc";
    799         case CallingConventionAsync: return "async";
    800     }
    801     zig_unreachable();
    802 }
    803 
    804 static const char *calling_convention_fn_type_str(CallingConvention cc) {
    805     switch (cc) {
    806         case CallingConventionUnspecified: return "";
    807         case CallingConventionC: return "extern ";
    808         case CallingConventionCold: return "coldcc ";
    809         case CallingConventionNaked: return "nakedcc ";
    810         case CallingConventionStdcall: return "stdcallcc ";
    811         case CallingConventionAsync: return "async ";
    812     }
    813     zig_unreachable();
    814 }
    815 
    816 bool calling_convention_allows_zig_types(CallingConvention cc) {
    817     switch (cc) {
    818         case CallingConventionUnspecified:
    819         case CallingConventionAsync:
    820             return true;
    821         case CallingConventionC:
    822         case CallingConventionCold:
    823         case CallingConventionNaked:
    824         case CallingConventionStdcall:
    825             return false;
    826     }
    827     zig_unreachable();
    828 }
    829 
    830 ZigType *get_ptr_to_stack_trace_type(CodeGen *g) {
    831     if (g->stack_trace_type == nullptr) {
    832         ConstExprValue *stack_trace_type_val = get_builtin_value(g, "StackTrace");
    833         assert(stack_trace_type_val->type->id == ZigTypeIdMetaType);
    834 
    835         g->stack_trace_type = stack_trace_type_val->data.x_type;
    836         assertNoError(type_resolve(g, g->stack_trace_type, ResolveStatusZeroBitsKnown));
    837 
    838         g->ptr_to_stack_trace_type = get_pointer_to_type(g, g->stack_trace_type, false);
    839     }
    840     return g->ptr_to_stack_trace_type;
    841 }
    842 
    843 bool want_first_arg_sret(CodeGen *g, FnTypeId *fn_type_id) {
    844     if (fn_type_id->cc == CallingConventionUnspecified) {
    845         return handle_is_ptr(fn_type_id->return_type);
    846     }
    847     if (fn_type_id->cc != CallingConventionC) {
    848         return false;
    849     }
    850     if (type_is_c_abi_int(g, fn_type_id->return_type)) {
    851         return false;
    852     }
    853     if (g->zig_target->arch == ZigLLVM_x86_64) {
    854         X64CABIClass abi_class = type_c_abi_x86_64_class(g, fn_type_id->return_type);
    855         return abi_class == X64CABIClass_MEMORY;
    856     } else if (target_is_arm(g->zig_target)) {
    857         return type_size(g, fn_type_id->return_type) > 16;
    858     }
    859     zig_panic("TODO implement C ABI for this architecture. See https://github.com/ziglang/zig/issues/1481");
    860 }
    861 
    862 ZigType *get_fn_type(CodeGen *g, FnTypeId *fn_type_id) {
    863     Error err;
    864     auto table_entry = g->fn_type_table.maybe_get(fn_type_id);
    865     if (table_entry) {
    866         return table_entry->value;
    867     }
    868     if (fn_type_id->return_type != nullptr) {
    869         if ((err = ensure_complete_type(g, fn_type_id->return_type)))
    870             return g->builtin_types.entry_invalid;
    871         assert(fn_type_id->return_type->id != ZigTypeIdOpaque);
    872     } else {
    873         zig_panic("TODO implement inferred return types https://github.com/ziglang/zig/issues/447");
    874     }
    875 
    876     ZigType *fn_type = new_type_table_entry(ZigTypeIdFn);
    877     fn_type->data.fn.fn_type_id = *fn_type_id;
    878 
    879     // populate the name of the type
    880     buf_resize(&fn_type->name, 0);
    881     const char *cc_str = calling_convention_fn_type_str(fn_type->data.fn.fn_type_id.cc);
    882     buf_appendf(&fn_type->name, "%s", cc_str);
    883     buf_appendf(&fn_type->name, "fn(");
    884     for (size_t i = 0; i < fn_type_id->param_count; i += 1) {
    885         FnTypeParamInfo *param_info = &fn_type_id->param_info[i];
    886 
    887         ZigType *param_type = param_info->type;
    888         const char *comma = (i == 0) ? "" : ", ";
    889         const char *noalias_str = param_info->is_noalias ? "noalias " : "";
    890         buf_appendf(&fn_type->name, "%s%s%s", comma, noalias_str, buf_ptr(&param_type->name));
    891     }
    892 
    893     if (fn_type_id->is_var_args) {
    894         const char *comma = (fn_type_id->param_count == 0) ? "" : ", ";
    895         buf_appendf(&fn_type->name, "%s...", comma);
    896     }
    897     buf_appendf(&fn_type->name, ")");
    898     if (fn_type_id->alignment != 0) {
    899         buf_appendf(&fn_type->name, " align(%" PRIu32 ")", fn_type_id->alignment);
    900     }
    901     buf_appendf(&fn_type->name, " %s", buf_ptr(&fn_type_id->return_type->name));
    902 
    903     // The fn_type is a pointer; not to be confused with the raw function type.
    904     fn_type->size_in_bits = g->builtin_types.entry_usize->size_in_bits;
    905     fn_type->abi_size = g->builtin_types.entry_usize->abi_size;
    906     fn_type->abi_align = g->builtin_types.entry_usize->abi_align;
    907 
    908     g->fn_type_table.put(&fn_type->data.fn.fn_type_id, fn_type);
    909 
    910     return fn_type;
    911 }
    912 
    913 static ZigTypeId container_to_type(ContainerKind kind) {
    914     switch (kind) {
    915         case ContainerKindStruct:
    916             return ZigTypeIdStruct;
    917         case ContainerKindEnum:
    918             return ZigTypeIdEnum;
    919         case ContainerKindUnion:
    920             return ZigTypeIdUnion;
    921     }
    922     zig_unreachable();
    923 }
    924 
    925 // This is like get_partial_container_type except it's for the implicit root struct of files.
    926 static ZigType *get_root_container_type(CodeGen *g, const char *full_name, Buf *bare_name,
    927         RootStruct *root_struct)
    928 {
    929     ZigType *entry = new_type_table_entry(ZigTypeIdStruct);
    930     entry->data.structure.decls_scope = create_decls_scope(g, nullptr, nullptr, entry, entry, bare_name);
    931     entry->data.structure.root_struct = root_struct;
    932     entry->data.structure.layout = ContainerLayoutAuto;
    933 
    934     buf_init_from_str(&entry->name, full_name);
    935     return entry;
    936 }
    937 
    938 ZigType *get_partial_container_type(CodeGen *g, Scope *scope, ContainerKind kind,
    939         AstNode *decl_node, const char *full_name, Buf *bare_name, ContainerLayout layout)
    940 {
    941     ZigTypeId type_id = container_to_type(kind);
    942     ZigType *entry = new_container_type_entry(g, type_id, decl_node, scope, bare_name);
    943 
    944     switch (kind) {
    945         case ContainerKindStruct:
    946             entry->data.structure.decl_node = decl_node;
    947             entry->data.structure.layout = layout;
    948             break;
    949         case ContainerKindEnum:
    950             entry->data.enumeration.decl_node = decl_node;
    951             entry->data.enumeration.layout = layout;
    952             break;
    953         case ContainerKindUnion:
    954             entry->data.unionation.decl_node = decl_node;
    955             entry->data.unionation.layout = layout;
    956             break;
    957     }
    958 
    959     buf_init_from_str(&entry->name, full_name);
    960 
    961     return entry;
    962 }
    963 
    964 ConstExprValue *analyze_const_value(CodeGen *g, Scope *scope, AstNode *node, ZigType *type_entry, Buf *type_name) {
    965     size_t backward_branch_count = 0;
    966     size_t backward_branch_quota = default_backward_branch_quota;
    967     return ir_eval_const_value(g, scope, node, type_entry,
    968             &backward_branch_count, &backward_branch_quota,
    969             nullptr, nullptr, node, type_name, nullptr, nullptr);
    970 }
    971 
    972 ZigType *analyze_type_expr(CodeGen *g, Scope *scope, AstNode *node) {
    973     ConstExprValue *result = analyze_const_value(g, scope, node, g->builtin_types.entry_type, nullptr);
    974     if (type_is_invalid(result->type))
    975         return g->builtin_types.entry_invalid;
    976 
    977     assert(result->special != ConstValSpecialRuntime);
    978     // Reject undefined as valid `type` type even though the specification
    979     // allows it to be casted to anything.
    980     // See also ir_resolve_type()
    981     if (result->special == ConstValSpecialUndef) {
    982         add_node_error(g, node,
    983             buf_sprintf("expected type 'type', found '%s'",
    984                 buf_ptr(&g->builtin_types.entry_undef->name)));
    985         return g->builtin_types.entry_invalid;
    986     }
    987 
    988     assert(result->data.x_type != nullptr);
    989     return result->data.x_type;
    990 }
    991 
    992 ZigType *get_generic_fn_type(CodeGen *g, FnTypeId *fn_type_id) {
    993     ZigType *fn_type = new_type_table_entry(ZigTypeIdFn);
    994     buf_resize(&fn_type->name, 0);
    995     const char *cc_str = calling_convention_fn_type_str(fn_type->data.fn.fn_type_id.cc);
    996     buf_appendf(&fn_type->name, "%s", cc_str);
    997     buf_appendf(&fn_type->name, "fn(");
    998     size_t i = 0;
    999     for (; i < fn_type_id->next_param_index; i += 1) {
   1000         const char *comma_str = (i == 0) ? "" : ",";
   1001         buf_appendf(&fn_type->name, "%s%s", comma_str,
   1002             buf_ptr(&fn_type_id->param_info[i].type->name));
   1003     }
   1004     for (; i < fn_type_id->param_count; i += 1) {
   1005         const char *comma_str = (i == 0) ? "" : ",";
   1006         buf_appendf(&fn_type->name, "%svar", comma_str);
   1007     }
   1008     buf_appendf(&fn_type->name, ")var");
   1009 
   1010     fn_type->data.fn.fn_type_id = *fn_type_id;
   1011     fn_type->data.fn.is_generic = true;
   1012     fn_type->abi_size = 0;
   1013     fn_type->size_in_bits = 0;
   1014     fn_type->abi_align = 0;
   1015     return fn_type;
   1016 }
   1017 
   1018 void init_fn_type_id(FnTypeId *fn_type_id, AstNode *proto_node, size_t param_count_alloc) {
   1019     assert(proto_node->type == NodeTypeFnProto);
   1020     AstNodeFnProto *fn_proto = &proto_node->data.fn_proto;
   1021 
   1022     if (fn_proto->cc == CallingConventionUnspecified) {
   1023         bool extern_abi = fn_proto->is_extern || fn_proto->is_export;
   1024         fn_type_id->cc = extern_abi ? CallingConventionC : CallingConventionUnspecified;
   1025     } else {
   1026         fn_type_id->cc = fn_proto->cc;
   1027     }
   1028 
   1029     fn_type_id->param_count = fn_proto->params.length;
   1030     fn_type_id->param_info = allocate<FnTypeParamInfo>(param_count_alloc);
   1031     fn_type_id->next_param_index = 0;
   1032     fn_type_id->is_var_args = fn_proto->is_var_args;
   1033 }
   1034 
   1035 static bool analyze_const_align(CodeGen *g, Scope *scope, AstNode *node, uint32_t *result) {
   1036     ConstExprValue *align_result = analyze_const_value(g, scope, node, get_align_amt_type(g), nullptr);
   1037     if (type_is_invalid(align_result->type))
   1038         return false;
   1039 
   1040     uint32_t align_bytes = bigint_as_unsigned(&align_result->data.x_bigint);
   1041     if (align_bytes == 0) {
   1042         add_node_error(g, node, buf_sprintf("alignment must be >= 1"));
   1043         return false;
   1044     }
   1045     if (!is_power_of_2(align_bytes)) {
   1046         add_node_error(g, node, buf_sprintf("alignment value %" PRIu32 " is not a power of 2", align_bytes));
   1047         return false;
   1048     }
   1049 
   1050     *result = align_bytes;
   1051     return true;
   1052 }
   1053 
   1054 static bool analyze_const_string(CodeGen *g, Scope *scope, AstNode *node, Buf **out_buffer) {
   1055     ZigType *ptr_type = get_pointer_to_type_extra(g, g->builtin_types.entry_u8, true, false,
   1056             PtrLenUnknown, 0, 0, 0, false);
   1057     ZigType *str_type = get_slice_type(g, ptr_type);
   1058     ConstExprValue *result_val = analyze_const_value(g, scope, node, str_type, nullptr);
   1059     if (type_is_invalid(result_val->type))
   1060         return false;
   1061 
   1062     ConstExprValue *ptr_field = &result_val->data.x_struct.fields[slice_ptr_index];
   1063     ConstExprValue *len_field = &result_val->data.x_struct.fields[slice_len_index];
   1064 
   1065     assert(ptr_field->data.x_ptr.special == ConstPtrSpecialBaseArray);
   1066     ConstExprValue *array_val = ptr_field->data.x_ptr.data.base_array.array_val;
   1067     if (array_val->data.x_array.special == ConstArraySpecialBuf) {
   1068         *out_buffer = array_val->data.x_array.data.s_buf;
   1069         return true;
   1070     }
   1071     expand_undef_array(g, array_val);
   1072     size_t len = bigint_as_unsigned(&len_field->data.x_bigint);
   1073     Buf *result = buf_alloc();
   1074     buf_resize(result, len);
   1075     for (size_t i = 0; i < len; i += 1) {
   1076         size_t new_index = ptr_field->data.x_ptr.data.base_array.elem_index + i;
   1077         ConstExprValue *char_val = &array_val->data.x_array.data.s_none.elements[new_index];
   1078         if (char_val->special == ConstValSpecialUndef) {
   1079             add_node_error(g, node, buf_sprintf("use of undefined value"));
   1080             return false;
   1081         }
   1082         uint64_t big_c = bigint_as_unsigned(&char_val->data.x_bigint);
   1083         assert(big_c <= UINT8_MAX);
   1084         uint8_t c = (uint8_t)big_c;
   1085         buf_ptr(result)[i] = c;
   1086     }
   1087     *out_buffer = result;
   1088     return true;
   1089 }
   1090 
   1091 static Error emit_error_unless_type_allowed_in_packed_struct(CodeGen *g, ZigType *type_entry,
   1092         AstNode *source_node)
   1093 {
   1094     Error err;
   1095     switch (type_entry->id) {
   1096         case ZigTypeIdInvalid:
   1097             zig_unreachable();
   1098         case ZigTypeIdMetaType:
   1099         case ZigTypeIdUnreachable:
   1100         case ZigTypeIdComptimeFloat:
   1101         case ZigTypeIdComptimeInt:
   1102         case ZigTypeIdEnumLiteral:
   1103         case ZigTypeIdUndefined:
   1104         case ZigTypeIdNull:
   1105         case ZigTypeIdErrorUnion:
   1106         case ZigTypeIdErrorSet:
   1107         case ZigTypeIdBoundFn:
   1108         case ZigTypeIdArgTuple:
   1109         case ZigTypeIdOpaque:
   1110         case ZigTypeIdCoroFrame:
   1111         case ZigTypeIdAnyFrame:
   1112             add_node_error(g, source_node,
   1113                     buf_sprintf("type '%s' not allowed in packed struct; no guaranteed in-memory representation",
   1114                         buf_ptr(&type_entry->name)));
   1115             return ErrorSemanticAnalyzeFail;
   1116         case ZigTypeIdVoid:
   1117         case ZigTypeIdBool:
   1118         case ZigTypeIdInt:
   1119         case ZigTypeIdFloat:
   1120         case ZigTypeIdPointer:
   1121         case ZigTypeIdFn:
   1122         case ZigTypeIdVector:
   1123             return ErrorNone;
   1124         case ZigTypeIdArray: {
   1125             ZigType *elem_type = type_entry->data.array.child_type;
   1126             if ((err = emit_error_unless_type_allowed_in_packed_struct(g, elem_type, source_node)))
   1127                 return err;
   1128             // TODO revisit this when doing https://github.com/ziglang/zig/issues/1512
   1129             if (type_size(g, type_entry) * 8 == type_size_bits(g, type_entry))
   1130                 return ErrorNone;
   1131             add_node_error(g, source_node,
   1132                 buf_sprintf("array of '%s' not allowed in packed struct due to padding bits",
   1133                     buf_ptr(&elem_type->name)));
   1134             return ErrorSemanticAnalyzeFail;
   1135         }
   1136         case ZigTypeIdStruct:
   1137             switch (type_entry->data.structure.layout) {
   1138                 case ContainerLayoutPacked:
   1139                 case ContainerLayoutExtern:
   1140                     return ErrorNone;
   1141                 case ContainerLayoutAuto:
   1142                     add_node_error(g, source_node,
   1143                         buf_sprintf("non-packed, non-extern struct '%s' not allowed in packed struct; no guaranteed in-memory representation",
   1144                             buf_ptr(&type_entry->name)));
   1145                     return ErrorSemanticAnalyzeFail;
   1146             }
   1147             zig_unreachable();
   1148         case ZigTypeIdUnion:
   1149             switch (type_entry->data.unionation.layout) {
   1150                 case ContainerLayoutPacked:
   1151                 case ContainerLayoutExtern:
   1152                     return ErrorNone;
   1153                 case ContainerLayoutAuto:
   1154                     add_node_error(g, source_node,
   1155                         buf_sprintf("non-packed, non-extern union '%s' not allowed in packed struct; no guaranteed in-memory representation",
   1156                             buf_ptr(&type_entry->name)));
   1157                     return ErrorSemanticAnalyzeFail;
   1158             }
   1159             zig_unreachable();
   1160         case ZigTypeIdOptional:
   1161             if (get_codegen_ptr_type(type_entry) != nullptr) {
   1162                 return ErrorNone;
   1163             } else {
   1164                 add_node_error(g, source_node,
   1165                     buf_sprintf("type '%s' not allowed in packed struct; no guaranteed in-memory representation",
   1166                         buf_ptr(&type_entry->name)));
   1167                 return ErrorSemanticAnalyzeFail;
   1168             }
   1169         case ZigTypeIdEnum: {
   1170             AstNode *decl_node = type_entry->data.enumeration.decl_node;
   1171             if (decl_node->data.container_decl.init_arg_expr != nullptr) {
   1172                 return ErrorNone;
   1173             }
   1174             ErrorMsg *msg = add_node_error(g, source_node,
   1175                 buf_sprintf("type '%s' not allowed in packed struct; no guaranteed in-memory representation",
   1176                     buf_ptr(&type_entry->name)));
   1177             add_error_note(g, msg, decl_node,
   1178                     buf_sprintf("enum declaration does not specify an integer tag type"));
   1179             return ErrorSemanticAnalyzeFail;
   1180         }
   1181     }
   1182     zig_unreachable();
   1183 }
   1184 
   1185 bool type_allowed_in_extern(CodeGen *g, ZigType *type_entry) {
   1186     switch (type_entry->id) {
   1187         case ZigTypeIdInvalid:
   1188             zig_unreachable();
   1189         case ZigTypeIdMetaType:
   1190         case ZigTypeIdComptimeFloat:
   1191         case ZigTypeIdComptimeInt:
   1192         case ZigTypeIdEnumLiteral:
   1193         case ZigTypeIdUndefined:
   1194         case ZigTypeIdNull:
   1195         case ZigTypeIdErrorUnion:
   1196         case ZigTypeIdErrorSet:
   1197         case ZigTypeIdBoundFn:
   1198         case ZigTypeIdArgTuple:
   1199         case ZigTypeIdVoid:
   1200         case ZigTypeIdCoroFrame:
   1201         case ZigTypeIdAnyFrame:
   1202             return false;
   1203         case ZigTypeIdOpaque:
   1204         case ZigTypeIdUnreachable:
   1205         case ZigTypeIdBool:
   1206             return true;
   1207         case ZigTypeIdInt:
   1208             switch (type_entry->data.integral.bit_count) {
   1209                 case 8:
   1210                 case 16:
   1211                 case 32:
   1212                 case 64:
   1213                 case 128:
   1214                     return true;
   1215                 default:
   1216                     return false;
   1217             }
   1218         case ZigTypeIdVector:
   1219             return type_allowed_in_extern(g, type_entry->data.vector.elem_type);
   1220         case ZigTypeIdFloat:
   1221             return true;
   1222         case ZigTypeIdArray:
   1223             return type_allowed_in_extern(g, type_entry->data.array.child_type);
   1224         case ZigTypeIdFn:
   1225             return type_entry->data.fn.fn_type_id.cc == CallingConventionC ||
   1226                  type_entry->data.fn.fn_type_id.cc == CallingConventionStdcall;
   1227         case ZigTypeIdPointer:
   1228             if (type_size(g, type_entry) == 0)
   1229                 return false;
   1230             return true;
   1231         case ZigTypeIdStruct:
   1232             return type_entry->data.structure.layout == ContainerLayoutExtern || type_entry->data.structure.layout == ContainerLayoutPacked;
   1233         case ZigTypeIdOptional:
   1234             {
   1235                 ZigType *child_type = type_entry->data.maybe.child_type;
   1236                 if (child_type->id != ZigTypeIdPointer && child_type->id != ZigTypeIdFn) {
   1237                     return false;
   1238                 }
   1239                 return type_allowed_in_extern(g, child_type);
   1240             }
   1241         case ZigTypeIdEnum:
   1242             return type_entry->data.enumeration.layout == ContainerLayoutExtern || type_entry->data.enumeration.layout == ContainerLayoutPacked;
   1243         case ZigTypeIdUnion:
   1244             return type_entry->data.unionation.layout == ContainerLayoutExtern || type_entry->data.unionation.layout == ContainerLayoutPacked;
   1245     }
   1246     zig_unreachable();
   1247 }
   1248 
   1249 ZigType *get_auto_err_set_type(CodeGen *g, ZigFn *fn_entry) {
   1250     ZigType *err_set_type = new_type_table_entry(ZigTypeIdErrorSet);
   1251     buf_resize(&err_set_type->name, 0);
   1252     buf_appendf(&err_set_type->name, "@typeOf(%s).ReturnType.ErrorSet", buf_ptr(&fn_entry->symbol_name));
   1253     err_set_type->data.error_set.err_count = 0;
   1254     err_set_type->data.error_set.errors = nullptr;
   1255     err_set_type->data.error_set.infer_fn = fn_entry;
   1256     err_set_type->size_in_bits = g->builtin_types.entry_global_error_set->size_in_bits;
   1257     err_set_type->abi_align = g->builtin_types.entry_global_error_set->abi_align;
   1258     err_set_type->abi_size = g->builtin_types.entry_global_error_set->abi_size;
   1259 
   1260     return err_set_type;
   1261 }
   1262 
   1263 static ZigType *analyze_fn_type(CodeGen *g, AstNode *proto_node, Scope *child_scope, ZigFn *fn_entry) {
   1264     assert(proto_node->type == NodeTypeFnProto);
   1265     AstNodeFnProto *fn_proto = &proto_node->data.fn_proto;
   1266     Error err;
   1267 
   1268     FnTypeId fn_type_id = {0};
   1269     init_fn_type_id(&fn_type_id, proto_node, proto_node->data.fn_proto.params.length);
   1270 
   1271     for (; fn_type_id.next_param_index < fn_type_id.param_count; fn_type_id.next_param_index += 1) {
   1272         AstNode *param_node = fn_proto->params.at(fn_type_id.next_param_index);
   1273         assert(param_node->type == NodeTypeParamDecl);
   1274 
   1275         bool param_is_comptime = param_node->data.param_decl.is_inline;
   1276         bool param_is_var_args = param_node->data.param_decl.is_var_args;
   1277 
   1278         if (param_is_comptime) {
   1279             if (!calling_convention_allows_zig_types(fn_type_id.cc)) {
   1280                 add_node_error(g, param_node,
   1281                         buf_sprintf("comptime parameter not allowed in function with calling convention '%s'",
   1282                             calling_convention_name(fn_type_id.cc)));
   1283                 return g->builtin_types.entry_invalid;
   1284             }
   1285             if (param_node->data.param_decl.type != nullptr) {
   1286                 ZigType *type_entry = analyze_type_expr(g, child_scope, param_node->data.param_decl.type);
   1287                 if (type_is_invalid(type_entry)) {
   1288                     return g->builtin_types.entry_invalid;
   1289                 }
   1290                 FnTypeParamInfo *param_info = &fn_type_id.param_info[fn_type_id.next_param_index];
   1291                 param_info->type = type_entry;
   1292                 param_info->is_noalias = param_node->data.param_decl.is_noalias;
   1293                 fn_type_id.next_param_index += 1;
   1294             }
   1295 
   1296             return get_generic_fn_type(g, &fn_type_id);
   1297         } else if (param_is_var_args) {
   1298             if (fn_type_id.cc == CallingConventionC) {
   1299                 fn_type_id.param_count = fn_type_id.next_param_index;
   1300                 continue;
   1301             } else if (calling_convention_allows_zig_types(fn_type_id.cc)) {
   1302                 return get_generic_fn_type(g, &fn_type_id);
   1303             } else {
   1304                 add_node_error(g, param_node,
   1305                         buf_sprintf("var args not allowed in function with calling convention '%s'",
   1306                             calling_convention_name(fn_type_id.cc)));
   1307                 return g->builtin_types.entry_invalid;
   1308             }
   1309         } else if (param_node->data.param_decl.var_token != nullptr) {
   1310             if (!calling_convention_allows_zig_types(fn_type_id.cc)) {
   1311                 add_node_error(g, param_node,
   1312                         buf_sprintf("parameter of type 'var' not allowed in function with calling convention '%s'",
   1313                             calling_convention_name(fn_type_id.cc)));
   1314                 return g->builtin_types.entry_invalid;
   1315             }
   1316             return get_generic_fn_type(g, &fn_type_id);
   1317         }
   1318 
   1319         ZigType *type_entry = analyze_type_expr(g, child_scope, param_node->data.param_decl.type);
   1320         if (type_is_invalid(type_entry)) {
   1321             return g->builtin_types.entry_invalid;
   1322         }
   1323         if (!calling_convention_allows_zig_types(fn_type_id.cc)) {
   1324             if ((err = type_resolve(g, type_entry, ResolveStatusZeroBitsKnown)))
   1325                 return g->builtin_types.entry_invalid;
   1326             if (!type_has_bits(type_entry)) {
   1327                 add_node_error(g, param_node->data.param_decl.type,
   1328                     buf_sprintf("parameter of type '%s' has 0 bits; not allowed in function with calling convention '%s'",
   1329                         buf_ptr(&type_entry->name), calling_convention_name(fn_type_id.cc)));
   1330                 return g->builtin_types.entry_invalid;
   1331             }
   1332         }
   1333 
   1334         if (!calling_convention_allows_zig_types(fn_type_id.cc) && !type_allowed_in_extern(g, type_entry)) {
   1335             add_node_error(g, param_node->data.param_decl.type,
   1336                     buf_sprintf("parameter of type '%s' not allowed in function with calling convention '%s'",
   1337                         buf_ptr(&type_entry->name),
   1338                         calling_convention_name(fn_type_id.cc)));
   1339             return g->builtin_types.entry_invalid;
   1340         }
   1341 
   1342         switch (type_entry->id) {
   1343             case ZigTypeIdInvalid:
   1344                 zig_unreachable();
   1345             case ZigTypeIdUnreachable:
   1346             case ZigTypeIdUndefined:
   1347             case ZigTypeIdNull:
   1348             case ZigTypeIdArgTuple:
   1349             case ZigTypeIdOpaque:
   1350                 add_node_error(g, param_node->data.param_decl.type,
   1351                     buf_sprintf("parameter of type '%s' not allowed", buf_ptr(&type_entry->name)));
   1352                 return g->builtin_types.entry_invalid;
   1353             case ZigTypeIdComptimeFloat:
   1354             case ZigTypeIdComptimeInt:
   1355             case ZigTypeIdEnumLiteral:
   1356             case ZigTypeIdBoundFn:
   1357             case ZigTypeIdMetaType:
   1358             case ZigTypeIdVoid:
   1359             case ZigTypeIdBool:
   1360             case ZigTypeIdInt:
   1361             case ZigTypeIdFloat:
   1362             case ZigTypeIdPointer:
   1363             case ZigTypeIdArray:
   1364             case ZigTypeIdStruct:
   1365             case ZigTypeIdOptional:
   1366             case ZigTypeIdErrorUnion:
   1367             case ZigTypeIdErrorSet:
   1368             case ZigTypeIdEnum:
   1369             case ZigTypeIdUnion:
   1370             case ZigTypeIdFn:
   1371             case ZigTypeIdVector:
   1372             case ZigTypeIdCoroFrame:
   1373             case ZigTypeIdAnyFrame:
   1374                 switch (type_requires_comptime(g, type_entry)) {
   1375                     case ReqCompTimeNo:
   1376                         break;
   1377                     case ReqCompTimeYes:
   1378                         add_node_error(g, param_node->data.param_decl.type,
   1379                             buf_sprintf("parameter of type '%s' must be declared comptime",
   1380                             buf_ptr(&type_entry->name)));
   1381                         return g->builtin_types.entry_invalid;
   1382                     case ReqCompTimeInvalid:
   1383                         return g->builtin_types.entry_invalid;
   1384                 }
   1385                 break;
   1386         }
   1387         FnTypeParamInfo *param_info = &fn_type_id.param_info[fn_type_id.next_param_index];
   1388         param_info->type = type_entry;
   1389         param_info->is_noalias = param_node->data.param_decl.is_noalias;
   1390     }
   1391 
   1392     if (fn_proto->align_expr != nullptr) {
   1393         if (!analyze_const_align(g, child_scope, fn_proto->align_expr, &fn_type_id.alignment)) {
   1394             return g->builtin_types.entry_invalid;
   1395         }
   1396     }
   1397 
   1398     if (fn_proto->return_var_token != nullptr) {
   1399         if (!calling_convention_allows_zig_types(fn_type_id.cc)) {
   1400             add_node_error(g, fn_proto->return_type,
   1401                 buf_sprintf("return type 'var' not allowed in function with calling convention '%s'",
   1402                 calling_convention_name(fn_type_id.cc)));
   1403             return g->builtin_types.entry_invalid;
   1404         }
   1405         add_node_error(g, proto_node,
   1406             buf_sprintf("TODO implement inferred return types https://github.com/ziglang/zig/issues/447"));
   1407         return g->builtin_types.entry_invalid;
   1408         //return get_generic_fn_type(g, &fn_type_id);
   1409     }
   1410 
   1411     ZigType *specified_return_type = analyze_type_expr(g, child_scope, fn_proto->return_type);
   1412     if (type_is_invalid(specified_return_type)) {
   1413         fn_type_id.return_type = g->builtin_types.entry_invalid;
   1414         return g->builtin_types.entry_invalid;
   1415     }
   1416 
   1417     if (fn_proto->auto_err_set) {
   1418         ZigType *inferred_err_set_type = get_auto_err_set_type(g, fn_entry);
   1419         if ((err = type_resolve(g, specified_return_type, ResolveStatusSizeKnown)))
   1420             return g->builtin_types.entry_invalid;
   1421         fn_type_id.return_type = get_error_union_type(g, inferred_err_set_type, specified_return_type);
   1422     } else {
   1423         fn_type_id.return_type = specified_return_type;
   1424     }
   1425 
   1426     if (!calling_convention_allows_zig_types(fn_type_id.cc) &&
   1427         fn_type_id.return_type->id != ZigTypeIdVoid &&
   1428         !type_allowed_in_extern(g, fn_type_id.return_type))
   1429     {
   1430         add_node_error(g, fn_proto->return_type,
   1431                 buf_sprintf("return type '%s' not allowed in function with calling convention '%s'",
   1432                     buf_ptr(&fn_type_id.return_type->name),
   1433                     calling_convention_name(fn_type_id.cc)));
   1434         return g->builtin_types.entry_invalid;
   1435     }
   1436 
   1437     switch (fn_type_id.return_type->id) {
   1438         case ZigTypeIdInvalid:
   1439             zig_unreachable();
   1440 
   1441         case ZigTypeIdUndefined:
   1442         case ZigTypeIdNull:
   1443         case ZigTypeIdArgTuple:
   1444         case ZigTypeIdOpaque:
   1445             add_node_error(g, fn_proto->return_type,
   1446                 buf_sprintf("return type '%s' not allowed", buf_ptr(&fn_type_id.return_type->name)));
   1447             return g->builtin_types.entry_invalid;
   1448 
   1449         case ZigTypeIdComptimeFloat:
   1450         case ZigTypeIdComptimeInt:
   1451         case ZigTypeIdEnumLiteral:
   1452         case ZigTypeIdBoundFn:
   1453         case ZigTypeIdMetaType:
   1454         case ZigTypeIdUnreachable:
   1455         case ZigTypeIdVoid:
   1456         case ZigTypeIdBool:
   1457         case ZigTypeIdInt:
   1458         case ZigTypeIdFloat:
   1459         case ZigTypeIdPointer:
   1460         case ZigTypeIdArray:
   1461         case ZigTypeIdStruct:
   1462         case ZigTypeIdOptional:
   1463         case ZigTypeIdErrorUnion:
   1464         case ZigTypeIdErrorSet:
   1465         case ZigTypeIdEnum:
   1466         case ZigTypeIdUnion:
   1467         case ZigTypeIdFn:
   1468         case ZigTypeIdVector:
   1469         case ZigTypeIdCoroFrame:
   1470         case ZigTypeIdAnyFrame:
   1471             switch (type_requires_comptime(g, fn_type_id.return_type)) {
   1472                 case ReqCompTimeInvalid:
   1473                     return g->builtin_types.entry_invalid;
   1474                 case ReqCompTimeYes:
   1475                     return get_generic_fn_type(g, &fn_type_id);
   1476                 case ReqCompTimeNo:
   1477                     break;
   1478             }
   1479             break;
   1480     }
   1481 
   1482     return get_fn_type(g, &fn_type_id);
   1483 }
   1484 
   1485 bool type_is_invalid(ZigType *type_entry) {
   1486     switch (type_entry->id) {
   1487         case ZigTypeIdInvalid:
   1488             return true;
   1489         case ZigTypeIdStruct:
   1490             return type_entry->data.structure.resolve_status == ResolveStatusInvalid;
   1491         case ZigTypeIdUnion:
   1492             return type_entry->data.unionation.resolve_status == ResolveStatusInvalid;
   1493         case ZigTypeIdEnum:
   1494             return type_entry->data.enumeration.is_invalid;
   1495         default:
   1496             return false;
   1497     }
   1498     zig_unreachable();
   1499 }
   1500 
   1501 
   1502 ZigType *get_struct_type(CodeGen *g, const char *type_name, const char *field_names[],
   1503         ZigType *field_types[], size_t field_count)
   1504 {
   1505     ZigType *struct_type = new_type_table_entry(ZigTypeIdStruct);
   1506 
   1507     buf_init_from_str(&struct_type->name, type_name);
   1508 
   1509     struct_type->data.structure.src_field_count = field_count;
   1510     struct_type->data.structure.gen_field_count = 0;
   1511     struct_type->data.structure.resolve_status = ResolveStatusSizeKnown;
   1512     struct_type->data.structure.fields = allocate<TypeStructField>(field_count);
   1513     struct_type->data.structure.fields_by_name.init(field_count);
   1514 
   1515     size_t abi_align = 0;
   1516     for (size_t i = 0; i < field_count; i += 1) {
   1517         TypeStructField *field = &struct_type->data.structure.fields[i];
   1518         field->name = buf_create_from_str(field_names[i]);
   1519         field->type_entry = field_types[i];
   1520         field->src_index = i;
   1521 
   1522         if (type_has_bits(field->type_entry)) {
   1523             assert(type_is_resolved(field->type_entry, ResolveStatusSizeKnown));
   1524             if (field->type_entry->abi_align > abi_align) {
   1525                 abi_align = field->type_entry->abi_align;
   1526             }
   1527             field->gen_index = struct_type->data.structure.gen_field_count;
   1528             struct_type->data.structure.gen_field_count += 1;
   1529         } else {
   1530             field->gen_index = SIZE_MAX;
   1531         }
   1532 
   1533         auto prev_entry = struct_type->data.structure.fields_by_name.put_unique(field->name, field);
   1534         assert(prev_entry == nullptr);
   1535     }
   1536 
   1537     size_t next_offset = 0;
   1538     for (size_t i = 0; i < field_count; i += 1) {
   1539         TypeStructField *field = &struct_type->data.structure.fields[i];
   1540         if (field->gen_index == SIZE_MAX)
   1541             continue;
   1542         field->offset = next_offset;
   1543         size_t next_src_field_index = i + 1;
   1544         for (; next_src_field_index < field_count; next_src_field_index += 1) {
   1545             if (struct_type->data.structure.fields[next_src_field_index].gen_index != SIZE_MAX) {
   1546                 break;
   1547             }
   1548         }
   1549         size_t next_abi_align = (next_src_field_index == field_count) ?
   1550             abi_align : struct_type->data.structure.fields[next_src_field_index].type_entry->abi_align;
   1551         next_offset = next_field_offset(next_offset, abi_align, field->type_entry->abi_size, next_abi_align);
   1552     }
   1553 
   1554     struct_type->abi_align = abi_align;
   1555     struct_type->abi_size = next_offset;
   1556     struct_type->size_in_bits = next_offset * 8;
   1557 
   1558     return struct_type;
   1559 }
   1560 
   1561 static size_t get_store_size_bytes(size_t size_in_bits) {
   1562     return (size_in_bits + 7) / 8;
   1563 }
   1564 
   1565 static size_t get_abi_align_bytes(size_t size_in_bits, size_t pointer_size_bytes) {
   1566     size_t store_size_bytes = get_store_size_bytes(size_in_bits);
   1567     if (store_size_bytes >= pointer_size_bytes)
   1568         return pointer_size_bytes;
   1569     return round_to_next_power_of_2(store_size_bytes);
   1570 }
   1571 
   1572 static size_t get_abi_size_bytes(size_t size_in_bits, size_t pointer_size_bytes) {
   1573     size_t store_size_bytes = get_store_size_bytes(size_in_bits);
   1574     size_t abi_align = get_abi_align_bytes(size_in_bits, pointer_size_bytes);
   1575     return align_forward(store_size_bytes, abi_align);
   1576 }
   1577 
   1578 static Error resolve_struct_type(CodeGen *g, ZigType *struct_type) {
   1579     assert(struct_type->id == ZigTypeIdStruct);
   1580 
   1581     Error err;
   1582 
   1583     if (struct_type->data.structure.resolve_status == ResolveStatusInvalid)
   1584         return ErrorSemanticAnalyzeFail;
   1585     if (struct_type->data.structure.resolve_status >= ResolveStatusSizeKnown)
   1586         return ErrorNone;
   1587 
   1588     if ((err = resolve_struct_alignment(g, struct_type)))
   1589         return err;
   1590 
   1591     AstNode *decl_node = struct_type->data.structure.decl_node;
   1592 
   1593     if (struct_type->data.structure.resolve_loop_flag) {
   1594         if (struct_type->data.structure.resolve_status != ResolveStatusInvalid) {
   1595             struct_type->data.structure.resolve_status = ResolveStatusInvalid;
   1596             ErrorMsg *msg = add_node_error(g, decl_node,
   1597                 buf_sprintf("struct '%s' contains itself", buf_ptr(&struct_type->name)));
   1598             emit_error_notes_for_ref_stack(g, msg);
   1599         }
   1600         return ErrorSemanticAnalyzeFail;
   1601     }
   1602 
   1603     assert(struct_type->data.structure.fields || struct_type->data.structure.src_field_count == 0);
   1604     assert(decl_node->type == NodeTypeContainerDecl);
   1605 
   1606     size_t field_count = struct_type->data.structure.src_field_count;
   1607 
   1608     bool packed = (struct_type->data.structure.layout == ContainerLayoutPacked);
   1609     struct_type->data.structure.resolve_loop_flag = true;
   1610 
   1611     uint32_t *host_int_bytes = packed ? allocate<uint32_t>(struct_type->data.structure.gen_field_count) : nullptr;
   1612 
   1613     // Resolve sizes of all the field types. Done before the offset loop because the offset
   1614     // loop has to look ahead.
   1615     for (size_t i = 0; i < field_count; i += 1) {
   1616         TypeStructField *field = &struct_type->data.structure.fields[i];
   1617         if ((err = type_resolve(g, field->type_entry, ResolveStatusSizeKnown))) {
   1618             struct_type->data.structure.resolve_status = ResolveStatusInvalid;
   1619             return ErrorSemanticAnalyzeFail;
   1620         }
   1621     }
   1622 
   1623     size_t packed_bits_offset = 0;
   1624     size_t next_offset = 0;
   1625     size_t first_packed_bits_offset_misalign = SIZE_MAX;
   1626     size_t gen_field_index = 0;
   1627     size_t size_in_bits = 0;
   1628     size_t abi_align = struct_type->abi_align;
   1629 
   1630     // Calculate offsets
   1631     for (size_t i = 0; i < field_count; i += 1) {
   1632         TypeStructField *field = &struct_type->data.structure.fields[i];
   1633         if (field->gen_index == SIZE_MAX)
   1634             continue;
   1635         ZigType *field_type = field->type_entry;
   1636         assert(field_type != nullptr);
   1637 
   1638         field->gen_index = gen_field_index;
   1639         field->offset = next_offset;
   1640 
   1641         if (packed) {
   1642             size_t field_size_in_bits = type_size_bits(g, field_type);
   1643             size_t next_packed_bits_offset = packed_bits_offset + field_size_in_bits;
   1644 
   1645             size_in_bits += field_size_in_bits;
   1646 
   1647             if (first_packed_bits_offset_misalign != SIZE_MAX) {
   1648                 // this field is not byte-aligned; it is part of the previous field with a bit offset
   1649                 field->bit_offset_in_host = packed_bits_offset - first_packed_bits_offset_misalign;
   1650 
   1651                 size_t full_bit_count = next_packed_bits_offset - first_packed_bits_offset_misalign;
   1652                 size_t full_abi_size = get_abi_size_bytes(full_bit_count, g->pointer_size_bytes);
   1653                 if (full_abi_size * 8 == full_bit_count) {
   1654                     // next field recovers ABI alignment
   1655                     host_int_bytes[gen_field_index] = full_abi_size;
   1656                     gen_field_index += 1;
   1657                     // TODO: https://github.com/ziglang/zig/issues/1512
   1658                     next_offset = next_field_offset(next_offset, abi_align, full_abi_size, 1);
   1659                     size_in_bits = next_offset * 8;
   1660 
   1661                     first_packed_bits_offset_misalign = SIZE_MAX;
   1662                 }
   1663             } else if (get_abi_size_bytes(field_type->size_in_bits, g->pointer_size_bytes) * 8 != field_size_in_bits) {
   1664                 first_packed_bits_offset_misalign = packed_bits_offset;
   1665                 field->bit_offset_in_host = 0;
   1666             } else {
   1667                 // This is a byte-aligned field (both start and end) in a packed struct.
   1668                 host_int_bytes[gen_field_index] = field_type->size_in_bits / 8;
   1669                 field->bit_offset_in_host = 0;
   1670                 gen_field_index += 1;
   1671                 // TODO: https://github.com/ziglang/zig/issues/1512
   1672                 next_offset = next_field_offset(next_offset, abi_align, field_type->size_in_bits / 8, 1);
   1673                 size_in_bits = next_offset * 8;
   1674             }
   1675             packed_bits_offset = next_packed_bits_offset;
   1676         } else {
   1677             gen_field_index += 1;
   1678             size_t next_src_field_index = i + 1;
   1679             for (; next_src_field_index < field_count; next_src_field_index += 1) {
   1680                 if (struct_type->data.structure.fields[next_src_field_index].gen_index != SIZE_MAX) {
   1681                     break;
   1682                 }
   1683             }
   1684             size_t next_abi_align = (next_src_field_index == field_count) ?
   1685                 abi_align : struct_type->data.structure.fields[next_src_field_index].type_entry->abi_align;
   1686             next_offset = next_field_offset(next_offset, abi_align, field_type->abi_size, next_abi_align);
   1687             size_in_bits = next_offset * 8;
   1688         }
   1689     }
   1690     if (first_packed_bits_offset_misalign != SIZE_MAX) {
   1691         size_t full_bit_count = packed_bits_offset - first_packed_bits_offset_misalign;
   1692         size_t full_abi_size = get_abi_size_bytes(full_bit_count, g->pointer_size_bytes);
   1693         next_offset = next_field_offset(next_offset, abi_align, full_abi_size, abi_align);
   1694         host_int_bytes[gen_field_index] = full_abi_size;
   1695         gen_field_index += 1;
   1696     }
   1697 
   1698     struct_type->abi_size = next_offset;
   1699     struct_type->size_in_bits = size_in_bits;
   1700     struct_type->data.structure.resolve_status = ResolveStatusSizeKnown;
   1701     struct_type->data.structure.gen_field_count = (uint32_t)gen_field_index;
   1702     struct_type->data.structure.resolve_loop_flag = false;
   1703     struct_type->data.structure.host_int_bytes = host_int_bytes;
   1704 
   1705     return ErrorNone;
   1706 }
   1707 
   1708 static Error resolve_union_alignment(CodeGen *g, ZigType *union_type) {
   1709     assert(union_type->id == ZigTypeIdUnion);
   1710 
   1711     Error err;
   1712 
   1713     if (union_type->data.unionation.resolve_status == ResolveStatusInvalid)
   1714         return ErrorSemanticAnalyzeFail;
   1715     if (union_type->data.unionation.resolve_status >= ResolveStatusAlignmentKnown)
   1716         return ErrorNone;
   1717     if ((err = resolve_union_zero_bits(g, union_type)))
   1718         return err;
   1719     if (union_type->data.unionation.resolve_status >= ResolveStatusAlignmentKnown)
   1720         return ErrorNone;
   1721 
   1722     if (union_type->data.unionation.resolve_loop_flag) {
   1723         if (!union_type->data.unionation.reported_infinite_err) {
   1724             AstNode *decl_node = union_type->data.unionation.decl_node;
   1725             union_type->data.unionation.reported_infinite_err = true;
   1726             union_type->data.unionation.resolve_status = ResolveStatusInvalid;
   1727             ErrorMsg *msg = add_node_error(g, decl_node,
   1728                     buf_sprintf("union '%s' contains itself", buf_ptr(&union_type->name)));
   1729             emit_error_notes_for_ref_stack(g, msg);
   1730         }
   1731         return ErrorSemanticAnalyzeFail;
   1732     }
   1733 
   1734     // set temporary flag
   1735     union_type->data.unionation.resolve_loop_flag = true;
   1736 
   1737     ZigType *most_aligned_union_member = nullptr;
   1738     uint32_t field_count = union_type->data.unionation.src_field_count;
   1739     bool packed = union_type->data.unionation.layout == ContainerLayoutPacked;
   1740 
   1741     for (uint32_t i = 0; i < field_count; i += 1) {
   1742         TypeUnionField *field = &union_type->data.unionation.fields[i];
   1743         if (field->gen_index == UINT32_MAX)
   1744             continue;
   1745 
   1746         size_t this_field_align;
   1747         if (packed) {
   1748             // TODO: https://github.com/ziglang/zig/issues/1512
   1749             this_field_align = 1;
   1750         // This is the same hack as resolve_struct_alignment. See the comment there.
   1751         } else if (field->type_entry == nullptr) {
   1752             this_field_align = g->builtin_types.entry_usize->abi_align;
   1753         } else {
   1754             if ((err = type_resolve(g, field->type_entry, ResolveStatusAlignmentKnown))) {
   1755                 union_type->data.unionation.resolve_status = ResolveStatusInvalid;
   1756                 return ErrorSemanticAnalyzeFail;
   1757             }
   1758 
   1759             if (union_type->data.unionation.resolve_status == ResolveStatusInvalid)
   1760                 return ErrorSemanticAnalyzeFail;
   1761 
   1762             this_field_align = field->type_entry->abi_align;
   1763         }
   1764 
   1765         if (most_aligned_union_member == nullptr ||
   1766             this_field_align > most_aligned_union_member->abi_align)
   1767         {
   1768             most_aligned_union_member = field->type_entry;
   1769         }
   1770     }
   1771 
   1772     // unset temporary flag
   1773     union_type->data.unionation.resolve_loop_flag = false;
   1774     union_type->data.unionation.resolve_status = ResolveStatusAlignmentKnown;
   1775     union_type->data.unionation.most_aligned_union_member = most_aligned_union_member;
   1776 
   1777     ZigType *tag_type = union_type->data.unionation.tag_type;
   1778     if (tag_type != nullptr && type_has_bits(tag_type)) {
   1779         if ((err = type_resolve(g, tag_type, ResolveStatusAlignmentKnown))) {
   1780             union_type->data.unionation.resolve_status = ResolveStatusInvalid;
   1781             return ErrorSemanticAnalyzeFail;
   1782         }
   1783         if (most_aligned_union_member == nullptr) {
   1784             union_type->abi_align = tag_type->abi_align;
   1785             union_type->data.unionation.gen_tag_index = SIZE_MAX;
   1786             union_type->data.unionation.gen_union_index = SIZE_MAX;
   1787         } else if (tag_type->abi_align > most_aligned_union_member->abi_align) {
   1788             union_type->abi_align = tag_type->abi_align;
   1789             union_type->data.unionation.gen_tag_index = 0;
   1790             union_type->data.unionation.gen_union_index = 1;
   1791         } else {
   1792             union_type->abi_align = most_aligned_union_member->abi_align;
   1793             union_type->data.unionation.gen_union_index = 0;
   1794             union_type->data.unionation.gen_tag_index = 1;
   1795         }
   1796     } else {
   1797         assert(most_aligned_union_member != nullptr);
   1798         union_type->abi_align = most_aligned_union_member->abi_align;
   1799         union_type->data.unionation.gen_union_index = SIZE_MAX;
   1800         union_type->data.unionation.gen_tag_index = SIZE_MAX;
   1801     }
   1802 
   1803     return ErrorNone;
   1804 }
   1805 
   1806 static Error resolve_union_type(CodeGen *g, ZigType *union_type) {
   1807     assert(union_type->id == ZigTypeIdUnion);
   1808 
   1809     Error err;
   1810 
   1811     if (union_type->data.unionation.resolve_status == ResolveStatusInvalid)
   1812         return ErrorSemanticAnalyzeFail;
   1813     if (union_type->data.unionation.resolve_status >= ResolveStatusSizeKnown)
   1814         return ErrorNone;
   1815 
   1816     if ((err = resolve_union_alignment(g, union_type)))
   1817         return err;
   1818 
   1819     AstNode *decl_node = union_type->data.unionation.decl_node;
   1820 
   1821 
   1822     assert(decl_node->type == NodeTypeContainerDecl);
   1823 
   1824     uint32_t field_count = union_type->data.unionation.src_field_count;
   1825     ZigType *most_aligned_union_member = union_type->data.unionation.most_aligned_union_member;
   1826 
   1827     assert(union_type->data.unionation.fields);
   1828 
   1829     size_t union_abi_size = 0;
   1830     size_t union_size_in_bits = 0;
   1831 
   1832     if (union_type->data.unionation.resolve_loop_flag) {
   1833         if (!union_type->data.unionation.reported_infinite_err) {
   1834             union_type->data.unionation.reported_infinite_err = true;
   1835             union_type->data.unionation.resolve_status = ResolveStatusInvalid;
   1836             ErrorMsg *msg = add_node_error(g, decl_node,
   1837                     buf_sprintf("union '%s' depends on its own size", buf_ptr(&union_type->name)));
   1838             emit_error_notes_for_ref_stack(g, msg);
   1839         }
   1840         return ErrorSemanticAnalyzeFail;
   1841     }
   1842 
   1843     // set temporary flag
   1844     union_type->data.unionation.resolve_loop_flag = true;
   1845 
   1846     for (uint32_t i = 0; i < field_count; i += 1) {
   1847         TypeUnionField *union_field = &union_type->data.unionation.fields[i];
   1848         ZigType *field_type = union_field->type_entry;
   1849 
   1850         if ((err = type_resolve(g, field_type, ResolveStatusSizeKnown))) {
   1851             union_type->data.unionation.resolve_status = ResolveStatusInvalid;
   1852             return ErrorSemanticAnalyzeFail;
   1853         }
   1854 
   1855         if (type_is_invalid(union_type))
   1856             return ErrorSemanticAnalyzeFail;
   1857 
   1858         if (!type_has_bits(field_type))
   1859             continue;
   1860 
   1861         union_abi_size = max(union_abi_size, field_type->abi_size);
   1862         union_size_in_bits = max(union_size_in_bits, field_type->size_in_bits);
   1863     }
   1864 
   1865     // The union itself for now has to be treated as being independently aligned.
   1866     // See https://github.com/ziglang/zig/issues/2166.
   1867     if (most_aligned_union_member != nullptr) {
   1868         union_abi_size = align_forward(union_abi_size, most_aligned_union_member->abi_align);
   1869     }
   1870 
   1871     // unset temporary flag
   1872     union_type->data.unionation.resolve_loop_flag = false;
   1873     union_type->data.unionation.resolve_status = ResolveStatusSizeKnown;
   1874     union_type->data.unionation.union_abi_size = union_abi_size;
   1875 
   1876     ZigType *tag_type = union_type->data.unionation.tag_type;
   1877     if (tag_type != nullptr && type_has_bits(tag_type)) {
   1878         if ((err = type_resolve(g, tag_type, ResolveStatusSizeKnown))) {
   1879             union_type->data.unionation.resolve_status = ResolveStatusInvalid;
   1880             return ErrorSemanticAnalyzeFail;
   1881         }
   1882         if (most_aligned_union_member == nullptr) {
   1883             union_type->abi_size = tag_type->abi_size;
   1884             union_type->size_in_bits = tag_type->size_in_bits;
   1885         } else {
   1886             size_t field_sizes[2];
   1887             size_t field_aligns[2];
   1888             field_sizes[union_type->data.unionation.gen_tag_index] = tag_type->abi_size;
   1889             field_aligns[union_type->data.unionation.gen_tag_index] = tag_type->abi_align;
   1890             field_sizes[union_type->data.unionation.gen_union_index] = union_abi_size;
   1891             field_aligns[union_type->data.unionation.gen_union_index] = most_aligned_union_member->abi_align;
   1892             size_t field2_offset = next_field_offset(0, union_type->abi_align, field_sizes[0], field_aligns[1]);
   1893             union_type->abi_size = next_field_offset(field2_offset, union_type->abi_align, field_sizes[1], union_type->abi_align);
   1894             union_type->size_in_bits = union_type->abi_size * 8;
   1895         }
   1896     } else {
   1897         union_type->abi_size = union_abi_size;
   1898         union_type->size_in_bits = union_size_in_bits;
   1899     }
   1900 
   1901     return ErrorNone;
   1902 }
   1903 
   1904 static bool type_is_valid_extern_enum_tag(CodeGen *g, ZigType *ty) {
   1905     // Only integer types are allowed by the C ABI
   1906     if(ty->id != ZigTypeIdInt)
   1907         return false;
   1908 
   1909     // According to the ANSI C standard the enumeration type should be either a
   1910     // signed char, a signed integer or an unsigned one. But GCC/Clang allow
   1911     // other integral types as a compiler extension so let's accomodate them
   1912     // aswell.
   1913     return type_allowed_in_extern(g, ty);
   1914 }
   1915 
   1916 static Error resolve_enum_zero_bits(CodeGen *g, ZigType *enum_type) {
   1917     assert(enum_type->id == ZigTypeIdEnum);
   1918 
   1919     if (enum_type->data.enumeration.is_invalid)
   1920         return ErrorSemanticAnalyzeFail;
   1921 
   1922     if (enum_type->data.enumeration.zero_bits_known)
   1923         return ErrorNone;
   1924 
   1925     if (enum_type->data.enumeration.zero_bits_loop_flag) {
   1926         ErrorMsg *msg = add_node_error(g, enum_type->data.enumeration.decl_node,
   1927             buf_sprintf("'%s' depends on itself", buf_ptr(&enum_type->name)));
   1928         emit_error_notes_for_ref_stack(g, msg);
   1929         enum_type->data.enumeration.is_invalid = true;
   1930         return ErrorSemanticAnalyzeFail;
   1931     }
   1932 
   1933     enum_type->data.enumeration.zero_bits_loop_flag = true;
   1934 
   1935     AstNode *decl_node = enum_type->data.enumeration.decl_node;
   1936     assert(decl_node->type == NodeTypeContainerDecl);
   1937 
   1938     assert(!enum_type->data.enumeration.fields);
   1939     uint32_t field_count = (uint32_t)decl_node->data.container_decl.fields.length;
   1940     if (field_count == 0) {
   1941         add_node_error(g, decl_node, buf_sprintf("enums must have 1 or more fields"));
   1942 
   1943         enum_type->data.enumeration.src_field_count = field_count;
   1944         enum_type->data.enumeration.fields = nullptr;
   1945         enum_type->data.enumeration.is_invalid = true;
   1946         enum_type->data.enumeration.zero_bits_loop_flag = false;
   1947         enum_type->data.enumeration.zero_bits_known = true;
   1948         return ErrorSemanticAnalyzeFail;
   1949     }
   1950 
   1951     enum_type->data.enumeration.src_field_count = field_count;
   1952     enum_type->data.enumeration.fields = allocate<TypeEnumField>(field_count);
   1953     enum_type->data.enumeration.fields_by_name.init(field_count);
   1954 
   1955     Scope *scope = &enum_type->data.enumeration.decls_scope->base;
   1956 
   1957     HashMap<BigInt, AstNode *, bigint_hash, bigint_eql> occupied_tag_values = {};
   1958     occupied_tag_values.init(field_count);
   1959 
   1960     ZigType *tag_int_type;
   1961     if (enum_type->data.enumeration.layout == ContainerLayoutExtern) {
   1962         tag_int_type = get_c_int_type(g, CIntTypeInt);
   1963     } else if (enum_type->data.enumeration.layout == ContainerLayoutAuto && field_count == 1) {
   1964         tag_int_type = g->builtin_types.entry_num_lit_int;
   1965     } else {
   1966         tag_int_type = get_smallest_unsigned_int_type(g, field_count - 1);
   1967     }
   1968 
   1969     enum_type->size_in_bits = tag_int_type->size_in_bits;
   1970     enum_type->abi_size = tag_int_type->abi_size;
   1971     enum_type->abi_align = tag_int_type->abi_align;
   1972 
   1973     if (decl_node->data.container_decl.init_arg_expr != nullptr) {
   1974         ZigType *wanted_tag_int_type = analyze_type_expr(g, scope, decl_node->data.container_decl.init_arg_expr);
   1975         if (type_is_invalid(wanted_tag_int_type)) {
   1976             enum_type->data.enumeration.is_invalid = true;
   1977         } else if (wanted_tag_int_type->id != ZigTypeIdInt) {
   1978             enum_type->data.enumeration.is_invalid = true;
   1979             add_node_error(g, decl_node->data.container_decl.init_arg_expr,
   1980                 buf_sprintf("expected integer, found '%s'", buf_ptr(&wanted_tag_int_type->name)));
   1981         } else if (enum_type->data.enumeration.layout == ContainerLayoutExtern &&
   1982                    !type_is_valid_extern_enum_tag(g, wanted_tag_int_type)) {
   1983             enum_type->data.enumeration.is_invalid = true;
   1984             ErrorMsg *msg = add_node_error(g, decl_node->data.container_decl.init_arg_expr,
   1985                 buf_sprintf("'%s' is not a valid tag type for an extern enum",
   1986                             buf_ptr(&wanted_tag_int_type->name)));
   1987             add_error_note(g, msg, decl_node->data.container_decl.init_arg_expr,
   1988                 buf_sprintf("any integral type of size 8, 16, 32, 64 or 128 bit is valid"));
   1989         } else {
   1990             tag_int_type = wanted_tag_int_type;
   1991         }
   1992     }
   1993 
   1994     enum_type->data.enumeration.tag_int_type = tag_int_type;
   1995     enum_type->size_in_bits = tag_int_type->size_in_bits;
   1996     enum_type->abi_size = tag_int_type->abi_size;
   1997     enum_type->abi_align = tag_int_type->abi_align;
   1998 
   1999     BigInt bi_one;
   2000     bigint_init_unsigned(&bi_one, 1);
   2001 
   2002     TypeEnumField *last_enum_field = nullptr;
   2003 
   2004     for (uint32_t field_i = 0; field_i < field_count; field_i += 1) {
   2005         AstNode *field_node = decl_node->data.container_decl.fields.at(field_i);
   2006         TypeEnumField *type_enum_field = &enum_type->data.enumeration.fields[field_i];
   2007         type_enum_field->name = field_node->data.struct_field.name;
   2008         type_enum_field->decl_index = field_i;
   2009         type_enum_field->decl_node = field_node;
   2010 
   2011         if (field_node->data.struct_field.type != nullptr) {
   2012             ErrorMsg *msg = add_node_error(g, field_node->data.struct_field.type,
   2013                 buf_sprintf("structs and unions, not enums, support field types"));
   2014             add_error_note(g, msg, decl_node,
   2015                     buf_sprintf("consider 'union(enum)' here"));
   2016         }
   2017 
   2018         auto field_entry = enum_type->data.enumeration.fields_by_name.put_unique(type_enum_field->name, type_enum_field);
   2019         if (field_entry != nullptr) {
   2020             ErrorMsg *msg = add_node_error(g, field_node,
   2021                 buf_sprintf("duplicate enum field: '%s'", buf_ptr(type_enum_field->name)));
   2022             add_error_note(g, msg, field_entry->value->decl_node, buf_sprintf("other field here"));
   2023             enum_type->data.enumeration.is_invalid = true;
   2024             continue;
   2025         }
   2026 
   2027         AstNode *tag_value = field_node->data.struct_field.value;
   2028 
   2029         if (tag_value != nullptr) {
   2030             // A user-specified value is available
   2031             ConstExprValue *result = analyze_const_value(g, scope, tag_value, tag_int_type, nullptr);
   2032             if (type_is_invalid(result->type)) {
   2033                 enum_type->data.enumeration.is_invalid = true;
   2034                 continue;
   2035             }
   2036 
   2037             assert(result->special != ConstValSpecialRuntime);
   2038             assert(result->type->id == ZigTypeIdInt || result->type->id == ZigTypeIdComptimeInt);
   2039 
   2040             bigint_init_bigint(&type_enum_field->value, &result->data.x_bigint);
   2041         } else {
   2042             // No value was explicitly specified: allocate the last value + 1
   2043             // or, if this is the first element, zero
   2044             if (last_enum_field != nullptr) {
   2045                 bigint_add(&type_enum_field->value, &last_enum_field->value, &bi_one);
   2046             } else {
   2047                 bigint_init_unsigned(&type_enum_field->value, 0);
   2048             }
   2049 
   2050             // Make sure we can represent this number with tag_int_type
   2051             if (!bigint_fits_in_bits(&type_enum_field->value,
   2052                                      tag_int_type->size_in_bits,
   2053                                      tag_int_type->data.integral.is_signed)) {
   2054                 enum_type->data.enumeration.is_invalid = true;
   2055 
   2056                 Buf *val_buf = buf_alloc();
   2057                 bigint_append_buf(val_buf, &type_enum_field->value, 10);
   2058                 add_node_error(g, field_node,
   2059                     buf_sprintf("enumeration value %s too large for type '%s'",
   2060                         buf_ptr(val_buf), buf_ptr(&tag_int_type->name)));
   2061 
   2062                 break;
   2063             }
   2064         }
   2065 
   2066         // Make sure the value is unique
   2067         auto entry = occupied_tag_values.put_unique(type_enum_field->value, field_node);
   2068         if (entry != nullptr) {
   2069             enum_type->data.enumeration.is_invalid = true;
   2070 
   2071             Buf *val_buf = buf_alloc();
   2072             bigint_append_buf(val_buf, &type_enum_field->value, 10);
   2073 
   2074             ErrorMsg *msg = add_node_error(g, field_node,
   2075                     buf_sprintf("enum tag value %s already taken", buf_ptr(val_buf)));
   2076             add_error_note(g, msg, entry->value,
   2077                     buf_sprintf("other occurrence here"));
   2078         }
   2079 
   2080         last_enum_field = type_enum_field;
   2081     }
   2082 
   2083     enum_type->data.enumeration.zero_bits_loop_flag = false;
   2084     enum_type->data.enumeration.zero_bits_known = true;
   2085     enum_type->data.enumeration.complete = true;
   2086 
   2087     if (enum_type->data.enumeration.is_invalid)
   2088         return ErrorSemanticAnalyzeFail;
   2089 
   2090     return ErrorNone;
   2091 }
   2092 
   2093 static Error resolve_struct_zero_bits(CodeGen *g, ZigType *struct_type) {
   2094     assert(struct_type->id == ZigTypeIdStruct);
   2095 
   2096     Error err;
   2097 
   2098     if (struct_type->data.structure.resolve_status == ResolveStatusInvalid)
   2099         return ErrorSemanticAnalyzeFail;
   2100     if (struct_type->data.structure.resolve_status >= ResolveStatusZeroBitsKnown)
   2101         return ErrorNone;
   2102 
   2103     AstNode *decl_node = struct_type->data.structure.decl_node;
   2104     assert(decl_node->type == NodeTypeContainerDecl);
   2105 
   2106     if (struct_type->data.structure.resolve_loop_flag) {
   2107         // TODO This is a problem. I believe it can be solved with lazy values.
   2108         struct_type->size_in_bits = SIZE_MAX;
   2109         struct_type->abi_size = SIZE_MAX;
   2110         struct_type->data.structure.resolve_status = ResolveStatusZeroBitsKnown;
   2111         struct_type->data.structure.resolve_loop_flag = false;
   2112         return ErrorNone;
   2113     }
   2114 
   2115     struct_type->data.structure.resolve_loop_flag = true;
   2116 
   2117     assert(!struct_type->data.structure.fields);
   2118     size_t field_count = decl_node->data.container_decl.fields.length;
   2119     struct_type->data.structure.src_field_count = (uint32_t)field_count;
   2120     struct_type->data.structure.fields = allocate<TypeStructField>(field_count);
   2121     struct_type->data.structure.fields_by_name.init(field_count);
   2122 
   2123     Scope *scope = &struct_type->data.structure.decls_scope->base;
   2124 
   2125     size_t gen_field_index = 0;
   2126     for (size_t i = 0; i < field_count; i += 1) {
   2127         AstNode *field_node = decl_node->data.container_decl.fields.at(i);
   2128         TypeStructField *type_struct_field = &struct_type->data.structure.fields[i];
   2129         type_struct_field->name = field_node->data.struct_field.name;
   2130         type_struct_field->decl_node = field_node;
   2131 
   2132         if (field_node->data.struct_field.type == nullptr) {
   2133             add_node_error(g, field_node, buf_sprintf("struct field missing type"));
   2134             struct_type->data.structure.resolve_status = ResolveStatusInvalid;
   2135             return ErrorSemanticAnalyzeFail;
   2136         }
   2137 
   2138         auto field_entry = struct_type->data.structure.fields_by_name.put_unique(type_struct_field->name, type_struct_field);
   2139         if (field_entry != nullptr) {
   2140             ErrorMsg *msg = add_node_error(g, field_node,
   2141                 buf_sprintf("duplicate struct field: '%s'", buf_ptr(type_struct_field->name)));
   2142             add_error_note(g, msg, field_entry->value->decl_node, buf_sprintf("other field here"));
   2143             struct_type->data.structure.resolve_status = ResolveStatusInvalid;
   2144             return ErrorSemanticAnalyzeFail;
   2145         }
   2146 
   2147         ZigType *field_type = analyze_type_expr(g, scope, field_node->data.struct_field.type);
   2148         type_struct_field->type_entry = field_type;
   2149         if (type_is_invalid(field_type)) {
   2150             struct_type->data.structure.resolve_status = ResolveStatusInvalid;
   2151             return ErrorSemanticAnalyzeFail;
   2152         }
   2153         if (struct_type->data.structure.resolve_status == ResolveStatusInvalid)
   2154             return ErrorSemanticAnalyzeFail;
   2155 
   2156         if (struct_type->data.structure.layout == ContainerLayoutExtern &&
   2157             !type_allowed_in_extern(g, field_type))
   2158         {
   2159             add_node_error(g, field_node,
   2160                     buf_sprintf("extern structs cannot contain fields of type '%s'",
   2161                         buf_ptr(&field_type->name)));
   2162             struct_type->data.structure.resolve_status = ResolveStatusInvalid;
   2163             return ErrorSemanticAnalyzeFail;
   2164         } else if (struct_type->data.structure.layout == ContainerLayoutPacked) {
   2165             if ((err = emit_error_unless_type_allowed_in_packed_struct(g, field_type, field_node))) {
   2166                 struct_type->data.structure.resolve_status = ResolveStatusInvalid;
   2167                 return ErrorSemanticAnalyzeFail;
   2168             }
   2169         }
   2170 
   2171         type_struct_field->src_index = i;
   2172         type_struct_field->gen_index = SIZE_MAX;
   2173 
   2174         if (field_type->id == ZigTypeIdOpaque) {
   2175             add_node_error(g, field_node->data.struct_field.type,
   2176                 buf_sprintf("opaque types have unknown size and therefore cannot be directly embedded in structs"));
   2177             struct_type->data.structure.resolve_status = ResolveStatusInvalid;
   2178             return ErrorSemanticAnalyzeFail;
   2179         }
   2180         switch (type_requires_comptime(g, field_type)) {
   2181             case ReqCompTimeYes:
   2182                 struct_type->data.structure.requires_comptime = true;
   2183                 break;
   2184             case ReqCompTimeInvalid:
   2185                 struct_type->data.structure.resolve_status = ResolveStatusInvalid;
   2186                 return ErrorSemanticAnalyzeFail;
   2187             case ReqCompTimeNo:
   2188                 break;
   2189         }
   2190 
   2191         if (!type_has_bits(field_type))
   2192             continue;
   2193 
   2194         type_struct_field->gen_index = gen_field_index;
   2195         gen_field_index += 1;
   2196     }
   2197 
   2198     struct_type->data.structure.resolve_loop_flag = false;
   2199     struct_type->data.structure.gen_field_count = (uint32_t)gen_field_index;
   2200     if (gen_field_index != 0) {
   2201         struct_type->abi_size = SIZE_MAX;
   2202         struct_type->size_in_bits = SIZE_MAX;
   2203     }
   2204 
   2205     if (struct_type->data.structure.resolve_status == ResolveStatusInvalid)
   2206         return ErrorSemanticAnalyzeFail;
   2207 
   2208     struct_type->data.structure.resolve_status = ResolveStatusZeroBitsKnown;
   2209     return ErrorNone;
   2210 }
   2211 
   2212 static Error resolve_struct_alignment(CodeGen *g, ZigType *struct_type) {
   2213     assert(struct_type->id == ZigTypeIdStruct);
   2214 
   2215     Error err;
   2216 
   2217     if (struct_type->data.structure.resolve_status == ResolveStatusInvalid)
   2218         return ErrorSemanticAnalyzeFail;
   2219     if (struct_type->data.structure.resolve_status >= ResolveStatusAlignmentKnown)
   2220         return ErrorNone;
   2221     if ((err = resolve_struct_zero_bits(g, struct_type)))
   2222         return err;
   2223     if (struct_type->data.structure.resolve_status >= ResolveStatusAlignmentKnown)
   2224         return ErrorNone;
   2225 
   2226     AstNode *decl_node = struct_type->data.structure.decl_node;
   2227 
   2228     if (struct_type->data.structure.resolve_loop_flag) {
   2229         if (struct_type->data.structure.resolve_status != ResolveStatusInvalid) {
   2230             struct_type->data.structure.resolve_status = ResolveStatusInvalid;
   2231             ErrorMsg *msg = add_node_error(g, decl_node,
   2232                 buf_sprintf("struct '%s' contains itself", buf_ptr(&struct_type->name)));
   2233             emit_error_notes_for_ref_stack(g, msg);
   2234         }
   2235         return ErrorSemanticAnalyzeFail;
   2236     }
   2237 
   2238     struct_type->data.structure.resolve_loop_flag = true;
   2239     assert(decl_node->type == NodeTypeContainerDecl);
   2240 
   2241     size_t field_count = struct_type->data.structure.src_field_count;
   2242     bool packed = struct_type->data.structure.layout == ContainerLayoutPacked;
   2243 
   2244     for (size_t i = 0; i < field_count; i += 1) {
   2245         TypeStructField *field = &struct_type->data.structure.fields[i];
   2246         if (field->gen_index == SIZE_MAX)
   2247             continue;
   2248 
   2249         size_t this_field_align;
   2250         if (packed) {
   2251             // TODO: https://github.com/ziglang/zig/issues/1512
   2252             this_field_align = 1;
   2253         // TODO If we have no type_entry for the field, we've already failed to
   2254         // compile the program correctly. This stage1 compiler needs a deeper
   2255         // reworking to make this correct, or we can ignore the problem
   2256         // and make sure it is fixed in stage2. This workaround is for when
   2257         // there is a false positive of a dependency loop, of alignment depending
   2258         // on itself. When this false positive happens we assume a pointer-aligned
   2259         // field, which is usually fine but could be incorrectly over-aligned or
   2260         // even under-aligned. See https://github.com/ziglang/zig/issues/1512
   2261         } else if (field->type_entry == nullptr) {
   2262             this_field_align = g->builtin_types.entry_usize->abi_align;
   2263         } else {
   2264             if ((err = type_resolve(g, field->type_entry, ResolveStatusAlignmentKnown))) {
   2265                 struct_type->data.structure.resolve_status = ResolveStatusInvalid;
   2266                 return ErrorSemanticAnalyzeFail;
   2267             }
   2268             this_field_align = field->type_entry->abi_align;
   2269         }
   2270 
   2271         // TODO: https://github.com/ziglang/zig/issues/1512
   2272         if (this_field_align > struct_type->abi_align) {
   2273             struct_type->abi_align = this_field_align;
   2274         }
   2275     }
   2276 
   2277     struct_type->data.structure.resolve_loop_flag = false;
   2278 
   2279     if (struct_type->data.structure.resolve_status == ResolveStatusInvalid) {
   2280         return ErrorSemanticAnalyzeFail;
   2281     }
   2282 
   2283     struct_type->data.structure.resolve_status = ResolveStatusAlignmentKnown;
   2284     return ErrorNone;
   2285 }
   2286 
   2287 static Error resolve_union_zero_bits(CodeGen *g, ZigType *union_type) {
   2288     assert(union_type->id == ZigTypeIdUnion);
   2289 
   2290     Error err;
   2291 
   2292     if (union_type->data.unionation.resolve_status == ResolveStatusInvalid)
   2293         return ErrorSemanticAnalyzeFail;
   2294 
   2295     if (union_type->data.unionation.resolve_status >= ResolveStatusZeroBitsKnown)
   2296         return ErrorNone;
   2297 
   2298     if (union_type->data.unionation.resolve_loop_flag) {
   2299         // If we get here it's due to recursion. From this we conclude that the struct is
   2300         // not zero bits.
   2301         // TODO actually it could still be zero bits. Here we should continue analyzing
   2302         // the union from the next field index.
   2303         union_type->data.unionation.resolve_status = ResolveStatusZeroBitsKnown;
   2304         union_type->data.unionation.resolve_loop_flag = false;
   2305         union_type->abi_size = SIZE_MAX;
   2306         union_type->size_in_bits = SIZE_MAX;
   2307         return ErrorNone;
   2308     }
   2309 
   2310     union_type->data.unionation.resolve_loop_flag = true;
   2311 
   2312     AstNode *decl_node = union_type->data.unionation.decl_node;
   2313     assert(decl_node->type == NodeTypeContainerDecl);
   2314 
   2315     assert(union_type->data.unionation.fields == nullptr);
   2316     uint32_t field_count = (uint32_t)decl_node->data.container_decl.fields.length;
   2317     if (field_count == 0) {
   2318         add_node_error(g, decl_node, buf_sprintf("unions must have 1 or more fields"));
   2319         union_type->data.unionation.src_field_count = field_count;
   2320         union_type->data.unionation.resolve_status = ResolveStatusInvalid;
   2321         return ErrorSemanticAnalyzeFail;
   2322     }
   2323     union_type->data.unionation.src_field_count = field_count;
   2324     union_type->data.unionation.fields = allocate<TypeUnionField>(field_count);
   2325     union_type->data.unionation.fields_by_name.init(field_count);
   2326 
   2327     Scope *scope = &union_type->data.unionation.decls_scope->base;
   2328 
   2329     HashMap<BigInt, AstNode *, bigint_hash, bigint_eql> occupied_tag_values = {};
   2330 
   2331     AstNode *enum_type_node = decl_node->data.container_decl.init_arg_expr;
   2332     union_type->data.unionation.have_explicit_tag_type = decl_node->data.container_decl.auto_enum ||
   2333         enum_type_node != nullptr;
   2334     bool auto_layout = (union_type->data.unionation.layout == ContainerLayoutAuto);
   2335     bool want_safety = (field_count >= 2) && (auto_layout || enum_type_node != nullptr) && !(g->build_mode == BuildModeFastRelease || g->build_mode == BuildModeSmallRelease);
   2336     ZigType *tag_type;
   2337     bool create_enum_type = decl_node->data.container_decl.auto_enum || (enum_type_node == nullptr && want_safety);
   2338     bool *covered_enum_fields;
   2339     ZigLLVMDIEnumerator **di_enumerators;
   2340     if (create_enum_type) {
   2341         occupied_tag_values.init(field_count);
   2342 
   2343         di_enumerators = allocate<ZigLLVMDIEnumerator*>(field_count);
   2344 
   2345         ZigType *tag_int_type;
   2346         if (enum_type_node != nullptr) {
   2347             tag_int_type = analyze_type_expr(g, scope, enum_type_node);
   2348             if (type_is_invalid(tag_int_type)) {
   2349                 union_type->data.unionation.resolve_status = ResolveStatusInvalid;
   2350                 return ErrorSemanticAnalyzeFail;
   2351             }
   2352             if (tag_int_type->id != ZigTypeIdInt) {
   2353                 add_node_error(g, enum_type_node,
   2354                     buf_sprintf("expected integer tag type, found '%s'", buf_ptr(&tag_int_type->name)));
   2355                 union_type->data.unionation.resolve_status = ResolveStatusInvalid;
   2356                 return ErrorSemanticAnalyzeFail;
   2357             }
   2358         } else if (auto_layout && field_count == 1) {
   2359             tag_int_type = g->builtin_types.entry_num_lit_int;
   2360         } else {
   2361             tag_int_type = get_smallest_unsigned_int_type(g, field_count - 1);
   2362         }
   2363 
   2364         tag_type = new_type_table_entry(ZigTypeIdEnum);
   2365         buf_resize(&tag_type->name, 0);
   2366         buf_appendf(&tag_type->name, "@TagType(%s)", buf_ptr(&union_type->name));
   2367         tag_type->llvm_type = tag_int_type->llvm_type;
   2368         tag_type->llvm_di_type = tag_int_type->llvm_di_type;
   2369         tag_type->abi_size = tag_int_type->abi_size;
   2370         tag_type->abi_align = tag_int_type->abi_align;
   2371         tag_type->size_in_bits = tag_int_type->size_in_bits;
   2372 
   2373         tag_type->data.enumeration.tag_int_type = tag_int_type;
   2374         tag_type->data.enumeration.zero_bits_known = true;
   2375         tag_type->data.enumeration.decl_node = decl_node;
   2376         tag_type->data.enumeration.layout = ContainerLayoutAuto;
   2377         tag_type->data.enumeration.src_field_count = field_count;
   2378         tag_type->data.enumeration.fields = allocate<TypeEnumField>(field_count);
   2379         tag_type->data.enumeration.fields_by_name.init(field_count);
   2380         tag_type->data.enumeration.decls_scope = union_type->data.unionation.decls_scope;
   2381         tag_type->data.enumeration.complete = true;
   2382     } else if (enum_type_node != nullptr) {
   2383         ZigType *enum_type = analyze_type_expr(g, scope, enum_type_node);
   2384         if (type_is_invalid(enum_type)) {
   2385             union_type->data.unionation.resolve_status = ResolveStatusInvalid;
   2386             return ErrorSemanticAnalyzeFail;
   2387         }
   2388         if (enum_type->id != ZigTypeIdEnum) {
   2389             union_type->data.unionation.resolve_status = ResolveStatusInvalid;
   2390             add_node_error(g, enum_type_node,
   2391                 buf_sprintf("expected enum tag type, found '%s'", buf_ptr(&enum_type->name)));
   2392             return ErrorSemanticAnalyzeFail;
   2393         }
   2394         if ((err = type_resolve(g, enum_type, ResolveStatusAlignmentKnown))) {
   2395             assert(g->errors.length != 0);
   2396             return err;
   2397         }
   2398         tag_type = enum_type;
   2399         covered_enum_fields = allocate<bool>(enum_type->data.enumeration.src_field_count);
   2400     } else {
   2401         tag_type = nullptr;
   2402     }
   2403     union_type->data.unionation.tag_type = tag_type;
   2404 
   2405     uint32_t gen_field_index = 0;
   2406     for (uint32_t i = 0; i < field_count; i += 1) {
   2407         AstNode *field_node = decl_node->data.container_decl.fields.at(i);
   2408         Buf *field_name = field_node->data.struct_field.name;
   2409         TypeUnionField *union_field = &union_type->data.unionation.fields[i];
   2410         union_field->name = field_node->data.struct_field.name;
   2411         union_field->decl_node = field_node;
   2412         union_field->gen_index = UINT32_MAX;
   2413 
   2414         auto field_entry = union_type->data.unionation.fields_by_name.put_unique(union_field->name, union_field);
   2415         if (field_entry != nullptr) {
   2416             ErrorMsg *msg = add_node_error(g, field_node,
   2417                 buf_sprintf("duplicate union field: '%s'", buf_ptr(union_field->name)));
   2418             add_error_note(g, msg, field_entry->value->decl_node, buf_sprintf("other field here"));
   2419             union_type->data.unionation.resolve_status = ResolveStatusInvalid;
   2420             return ErrorSemanticAnalyzeFail;
   2421         }
   2422 
   2423         ZigType *field_type;
   2424         if (field_node->data.struct_field.type == nullptr) {
   2425             if (decl_node->data.container_decl.auto_enum || decl_node->data.container_decl.init_arg_expr != nullptr) {
   2426                 field_type = g->builtin_types.entry_void;
   2427             } else {
   2428                 add_node_error(g, field_node, buf_sprintf("union field missing type"));
   2429                 union_type->data.unionation.resolve_status = ResolveStatusInvalid;
   2430                 return ErrorSemanticAnalyzeFail;
   2431             }
   2432         } else {
   2433             field_type = analyze_type_expr(g, scope, field_node->data.struct_field.type);
   2434             if ((err = type_resolve(g, field_type, ResolveStatusAlignmentKnown))) {
   2435                 union_type->data.unionation.resolve_status = ResolveStatusInvalid;
   2436                 return ErrorSemanticAnalyzeFail;
   2437             }
   2438             if (union_type->data.unionation.resolve_status == ResolveStatusInvalid)
   2439                 return ErrorSemanticAnalyzeFail;
   2440         }
   2441         union_field->type_entry = field_type;
   2442 
   2443         if (field_type->id == ZigTypeIdOpaque) {
   2444             add_node_error(g, field_node->data.struct_field.type,
   2445                 buf_sprintf("opaque types have unknown size and therefore cannot be directly embedded in unions"));
   2446             union_type->data.unionation.resolve_status = ResolveStatusInvalid;
   2447             return ErrorSemanticAnalyzeFail;
   2448         }
   2449 
   2450         switch (type_requires_comptime(g, field_type)) {
   2451             case ReqCompTimeInvalid:
   2452                 union_type->data.unionation.resolve_status = ResolveStatusInvalid;
   2453                 return ErrorSemanticAnalyzeFail;
   2454             case ReqCompTimeYes:
   2455                 union_type->data.unionation.requires_comptime = true;
   2456                 break;
   2457             case ReqCompTimeNo:
   2458                 break;
   2459         }
   2460 
   2461         if (field_node->data.struct_field.value != nullptr && !decl_node->data.container_decl.auto_enum) {
   2462             ErrorMsg *msg = add_node_error(g, field_node->data.struct_field.value,
   2463                     buf_sprintf("non-enum union field assignment"));
   2464             add_error_note(g, msg, decl_node,
   2465                     buf_sprintf("consider 'union(enum)' here"));
   2466         }
   2467 
   2468         if (create_enum_type) {
   2469             di_enumerators[i] = ZigLLVMCreateDebugEnumerator(g->dbuilder, buf_ptr(field_name), i);
   2470             union_field->enum_field = &tag_type->data.enumeration.fields[i];
   2471             union_field->enum_field->name = field_name;
   2472             union_field->enum_field->decl_index = i;
   2473             union_field->enum_field->decl_node = field_node;
   2474 
   2475             auto prev_entry = tag_type->data.enumeration.fields_by_name.put_unique(union_field->enum_field->name, union_field->enum_field);
   2476             assert(prev_entry == nullptr); // caught by union de-duplicator above
   2477 
   2478             AstNode *tag_value = field_node->data.struct_field.value;
   2479             // In this first pass we resolve explicit tag values.
   2480             // In a second pass we will fill in the unspecified ones.
   2481             if (tag_value != nullptr) {
   2482                 ZigType *tag_int_type = tag_type->data.enumeration.tag_int_type;
   2483                 ConstExprValue *result = analyze_const_value(g, scope, tag_value, tag_int_type, nullptr);
   2484                 if (type_is_invalid(result->type)) {
   2485                     union_type->data.unionation.resolve_status = ResolveStatusInvalid;
   2486                     return ErrorSemanticAnalyzeFail;
   2487                 }
   2488                 assert(result->special != ConstValSpecialRuntime);
   2489                 assert(result->type->id == ZigTypeIdInt);
   2490                 auto entry = occupied_tag_values.put_unique(result->data.x_bigint, tag_value);
   2491                 if (entry == nullptr) {
   2492                     bigint_init_bigint(&union_field->enum_field->value, &result->data.x_bigint);
   2493                 } else {
   2494                     Buf *val_buf = buf_alloc();
   2495                     bigint_append_buf(val_buf, &result->data.x_bigint, 10);
   2496 
   2497                     ErrorMsg *msg = add_node_error(g, tag_value,
   2498                             buf_sprintf("enum tag value %s already taken", buf_ptr(val_buf)));
   2499                     add_error_note(g, msg, entry->value,
   2500                             buf_sprintf("other occurrence here"));
   2501                     union_type->data.unionation.resolve_status = ResolveStatusInvalid;
   2502                     return ErrorSemanticAnalyzeFail;
   2503                 }
   2504             }
   2505         } else if (enum_type_node != nullptr) {
   2506             union_field->enum_field = find_enum_type_field(tag_type, field_name);
   2507             if (union_field->enum_field == nullptr) {
   2508                 ErrorMsg *msg = add_node_error(g, field_node,
   2509                     buf_sprintf("enum field not found: '%s'", buf_ptr(field_name)));
   2510                 add_error_note(g, msg, tag_type->data.enumeration.decl_node,
   2511                         buf_sprintf("enum declared here"));
   2512                 union_type->data.unionation.resolve_status = ResolveStatusInvalid;
   2513                 return ErrorSemanticAnalyzeFail;
   2514             }
   2515             covered_enum_fields[union_field->enum_field->decl_index] = true;
   2516         } else {
   2517             union_field->enum_field = allocate<TypeEnumField>(1);
   2518             union_field->enum_field->name = field_name;
   2519             union_field->enum_field->decl_index = i;
   2520             bigint_init_unsigned(&union_field->enum_field->value, i);
   2521         }
   2522         assert(union_field->enum_field != nullptr);
   2523 
   2524         if (!type_has_bits(field_type))
   2525             continue;
   2526 
   2527         union_field->gen_index = gen_field_index;
   2528         gen_field_index += 1;
   2529     }
   2530 
   2531     bool src_have_tag = decl_node->data.container_decl.auto_enum ||
   2532         decl_node->data.container_decl.init_arg_expr != nullptr;
   2533 
   2534     if (src_have_tag && union_type->data.unionation.layout != ContainerLayoutAuto) {
   2535         const char *qual_str;
   2536         switch (union_type->data.unionation.layout) {
   2537             case ContainerLayoutAuto:
   2538                 zig_unreachable();
   2539             case ContainerLayoutPacked:
   2540                 qual_str = "packed";
   2541                 break;
   2542             case ContainerLayoutExtern:
   2543                 qual_str = "extern";
   2544                 break;
   2545         }
   2546         AstNode *source_node = (decl_node->data.container_decl.init_arg_expr != nullptr) ?
   2547             decl_node->data.container_decl.init_arg_expr : decl_node;
   2548         add_node_error(g, source_node,
   2549             buf_sprintf("%s union does not support enum tag type", qual_str));
   2550         union_type->data.unionation.resolve_status = ResolveStatusInvalid;
   2551         return ErrorSemanticAnalyzeFail;
   2552     }
   2553 
   2554     if (create_enum_type) {
   2555         // Now iterate again and populate the unspecified tag values
   2556         uint32_t next_maybe_unoccupied_index = 0;
   2557 
   2558         for (uint32_t field_i = 0; field_i < field_count; field_i += 1) {
   2559             AstNode *field_node = decl_node->data.container_decl.fields.at(field_i);
   2560             TypeUnionField *union_field = &union_type->data.unionation.fields[field_i];
   2561             AstNode *tag_value = field_node->data.struct_field.value;
   2562 
   2563             if (tag_value == nullptr) {
   2564                 if (occupied_tag_values.size() == 0) {
   2565                     bigint_init_unsigned(&union_field->enum_field->value, next_maybe_unoccupied_index);
   2566                     next_maybe_unoccupied_index += 1;
   2567                 } else {
   2568                     BigInt proposed_value;
   2569                     for (;;) {
   2570                         bigint_init_unsigned(&proposed_value, next_maybe_unoccupied_index);
   2571                         next_maybe_unoccupied_index += 1;
   2572                         auto entry = occupied_tag_values.put_unique(proposed_value, field_node);
   2573                         if (entry != nullptr) {
   2574                             continue;
   2575                         }
   2576                         break;
   2577                     }
   2578                     bigint_init_bigint(&union_field->enum_field->value, &proposed_value);
   2579                 }
   2580             }
   2581         }
   2582     } else if (enum_type_node != nullptr) {
   2583         for (uint32_t i = 0; i < tag_type->data.enumeration.src_field_count; i += 1) {
   2584             TypeEnumField *enum_field = &tag_type->data.enumeration.fields[i];
   2585             if (!covered_enum_fields[i]) {
   2586                 AstNode *enum_decl_node = tag_type->data.enumeration.decl_node;
   2587                 AstNode *field_node = enum_decl_node->data.container_decl.fields.at(i);
   2588                 ErrorMsg *msg = add_node_error(g, decl_node,
   2589                     buf_sprintf("enum field missing: '%s'", buf_ptr(enum_field->name)));
   2590                 add_error_note(g, msg, field_node,
   2591                         buf_sprintf("declared here"));
   2592                 union_type->data.unionation.resolve_status = ResolveStatusInvalid;
   2593             }
   2594         }
   2595     }
   2596 
   2597     if (union_type->data.unionation.resolve_status == ResolveStatusInvalid) {
   2598         return ErrorSemanticAnalyzeFail;
   2599     }
   2600 
   2601     union_type->data.unionation.resolve_loop_flag = false;
   2602 
   2603     union_type->data.unionation.gen_field_count = gen_field_index;
   2604     bool zero_bits = gen_field_index == 0 && (field_count < 2 || !src_have_tag);
   2605     if (!zero_bits) {
   2606         union_type->abi_size = SIZE_MAX;
   2607         union_type->size_in_bits = SIZE_MAX;
   2608     }
   2609     union_type->data.unionation.resolve_status = zero_bits ? ResolveStatusSizeKnown : ResolveStatusZeroBitsKnown;
   2610 
   2611     return ErrorNone;
   2612 }
   2613 
   2614 static void get_fully_qualified_decl_name(Buf *buf, Tld *tld, bool is_test) {
   2615     buf_resize(buf, 0);
   2616 
   2617     Scope *scope = tld->parent_scope;
   2618     while (scope->id != ScopeIdDecls) {
   2619         scope = scope->parent;
   2620     }
   2621     ScopeDecls *decls_scope = reinterpret_cast<ScopeDecls *>(scope);
   2622     buf_append_buf(buf, &decls_scope->container_type->name);
   2623     if (buf_len(buf) != 0) buf_append_char(buf, NAMESPACE_SEP_CHAR);
   2624     if (is_test) {
   2625         buf_append_str(buf, "test \"");
   2626         buf_append_buf(buf, tld->name);
   2627         buf_append_char(buf, '"');
   2628     } else {
   2629         buf_append_buf(buf, tld->name);
   2630     }
   2631 }
   2632 
   2633 ZigFn *create_fn_raw(CodeGen *g, FnInline inline_value) {
   2634     ZigFn *fn_entry = allocate<ZigFn>(1);
   2635 
   2636     fn_entry->prealloc_backward_branch_quota = default_backward_branch_quota;
   2637 
   2638     fn_entry->analyzed_executable.backward_branch_count = &fn_entry->prealloc_bbc;
   2639     fn_entry->analyzed_executable.backward_branch_quota = &fn_entry->prealloc_backward_branch_quota;
   2640     fn_entry->analyzed_executable.fn_entry = fn_entry;
   2641     fn_entry->ir_executable.fn_entry = fn_entry;
   2642     fn_entry->fn_inline = inline_value;
   2643 
   2644     return fn_entry;
   2645 }
   2646 
   2647 ZigFn *create_fn(CodeGen *g, AstNode *proto_node) {
   2648     assert(proto_node->type == NodeTypeFnProto);
   2649     AstNodeFnProto *fn_proto = &proto_node->data.fn_proto;
   2650 
   2651     FnInline inline_value = fn_proto->is_inline ? FnInlineAlways : FnInlineAuto;
   2652     ZigFn *fn_entry = create_fn_raw(g, inline_value);
   2653 
   2654     fn_entry->proto_node = proto_node;
   2655     fn_entry->body_node = (proto_node->data.fn_proto.fn_def_node == nullptr) ? nullptr :
   2656         proto_node->data.fn_proto.fn_def_node->data.fn_def.body;
   2657 
   2658     return fn_entry;
   2659 }
   2660 
   2661 static bool scope_is_root_decls(Scope *scope) {
   2662     while (scope) {
   2663         if (scope->id == ScopeIdDecls) {
   2664             ScopeDecls *scope_decls = (ScopeDecls *)scope;
   2665             return is_top_level_struct(scope_decls->container_type);
   2666         }
   2667         scope = scope->parent;
   2668     }
   2669     zig_unreachable();
   2670 }
   2671 
   2672 void typecheck_panic_fn(CodeGen *g, TldFn *tld_fn, ZigFn *panic_fn) {
   2673     ConstExprValue *panic_fn_type_val = get_builtin_value(g, "PanicFn");
   2674     assert(panic_fn_type_val != nullptr);
   2675     assert(panic_fn_type_val->type->id == ZigTypeIdMetaType);
   2676     ZigType *panic_fn_type = panic_fn_type_val->data.x_type;
   2677 
   2678     AstNode *fake_decl = allocate<AstNode>(1);
   2679     *fake_decl = *panic_fn->proto_node;
   2680     fake_decl->type = NodeTypeSymbol;
   2681     fake_decl->data.symbol_expr.symbol = tld_fn->base.name;
   2682 
   2683     // call this for the side effects of casting to panic_fn_type
   2684     analyze_const_value(g, tld_fn->base.parent_scope, fake_decl, panic_fn_type, nullptr);
   2685 }
   2686 
   2687 ZigType *get_test_fn_type(CodeGen *g) {
   2688     if (g->test_fn_type)
   2689         return g->test_fn_type;
   2690 
   2691     FnTypeId fn_type_id = {0};
   2692     fn_type_id.return_type = get_error_union_type(g, g->builtin_types.entry_global_error_set,
   2693             g->builtin_types.entry_void);
   2694     g->test_fn_type = get_fn_type(g, &fn_type_id);
   2695     return g->test_fn_type;
   2696 }
   2697 
   2698 void add_var_export(CodeGen *g, ZigVar *var, Buf *symbol_name, GlobalLinkageId linkage) {
   2699     GlobalExport *global_export = var->export_list.add_one();
   2700     memset(global_export, 0, sizeof(GlobalExport));
   2701     buf_init_from_buf(&global_export->name, symbol_name);
   2702     global_export->linkage = linkage;
   2703 }
   2704 
   2705 void add_fn_export(CodeGen *g, ZigFn *fn_table_entry, Buf *symbol_name, GlobalLinkageId linkage, bool ccc) {
   2706     if (ccc) {
   2707         if (buf_eql_str(symbol_name, "main") && g->libc_link_lib != nullptr) {
   2708             g->have_c_main = true;
   2709         } else if (buf_eql_str(symbol_name, "WinMain") &&
   2710             g->zig_target->os == OsWindows)
   2711         {
   2712             g->have_winmain = true;
   2713         } else if (buf_eql_str(symbol_name, "WinMainCRTStartup") &&
   2714             g->zig_target->os == OsWindows)
   2715         {
   2716             g->have_winmain_crt_startup = true;
   2717         } else if (buf_eql_str(symbol_name, "DllMainCRTStartup") &&
   2718             g->zig_target->os == OsWindows)
   2719         {
   2720             g->have_dllmain_crt_startup = true;
   2721         }
   2722     }
   2723 
   2724     GlobalExport *fn_export = fn_table_entry->export_list.add_one();
   2725     memset(fn_export, 0, sizeof(GlobalExport));
   2726     buf_init_from_buf(&fn_export->name, symbol_name);
   2727     fn_export->linkage = linkage;
   2728 }
   2729 
   2730 static void resolve_decl_fn(CodeGen *g, TldFn *tld_fn) {
   2731     ZigType *import = tld_fn->base.import;
   2732     AstNode *source_node = tld_fn->base.source_node;
   2733     if (source_node->type == NodeTypeFnProto) {
   2734         AstNodeFnProto *fn_proto = &source_node->data.fn_proto;
   2735 
   2736         AstNode *fn_def_node = fn_proto->fn_def_node;
   2737 
   2738         ZigFn *fn_table_entry = create_fn(g, source_node);
   2739         tld_fn->fn_entry = fn_table_entry;
   2740 
   2741         bool is_extern = (fn_table_entry->body_node == nullptr);
   2742         if (fn_proto->is_export || is_extern) {
   2743             buf_init_from_buf(&fn_table_entry->symbol_name, tld_fn->base.name);
   2744         } else {
   2745             get_fully_qualified_decl_name(&fn_table_entry->symbol_name, &tld_fn->base, false);
   2746         }
   2747 
   2748         if (fn_proto->is_export) {
   2749             bool ccc = (fn_proto->cc == CallingConventionUnspecified || fn_proto->cc == CallingConventionC);
   2750             add_fn_export(g, fn_table_entry, &fn_table_entry->symbol_name, GlobalLinkageIdStrong, ccc);
   2751         }
   2752 
   2753         if (!is_extern) {
   2754             fn_table_entry->fndef_scope = create_fndef_scope(g,
   2755                 fn_table_entry->body_node, tld_fn->base.parent_scope, fn_table_entry);
   2756 
   2757             for (size_t i = 0; i < fn_proto->params.length; i += 1) {
   2758                 AstNode *param_node = fn_proto->params.at(i);
   2759                 assert(param_node->type == NodeTypeParamDecl);
   2760                 if (param_node->data.param_decl.name == nullptr) {
   2761                     add_node_error(g, param_node, buf_sprintf("missing parameter name"));
   2762                 }
   2763             }
   2764         } else {
   2765             fn_table_entry->inferred_async_node = inferred_async_none;
   2766             g->external_prototypes.put_unique(tld_fn->base.name, &tld_fn->base);
   2767         }
   2768 
   2769         Scope *child_scope = fn_table_entry->fndef_scope ? &fn_table_entry->fndef_scope->base : tld_fn->base.parent_scope;
   2770 
   2771         fn_table_entry->type_entry = analyze_fn_type(g, source_node, child_scope, fn_table_entry);
   2772 
   2773         if (fn_proto->section_expr != nullptr) {
   2774             analyze_const_string(g, child_scope, fn_proto->section_expr, &fn_table_entry->section_name);
   2775         }
   2776 
   2777         if (fn_table_entry->type_entry->id == ZigTypeIdInvalid) {
   2778             tld_fn->base.resolution = TldResolutionInvalid;
   2779             return;
   2780         }
   2781 
   2782         if (!fn_table_entry->type_entry->data.fn.is_generic) {
   2783             if (fn_def_node)
   2784                 g->fn_defs.append(fn_table_entry);
   2785         }
   2786 
   2787         // if the calling convention implies that it cannot be async, we save that for later
   2788         // and leave the value to be nullptr to indicate that we have not emitted possible
   2789         // compile errors for improperly calling async functions.
   2790         if (fn_table_entry->type_entry->data.fn.fn_type_id.cc == CallingConventionAsync) {
   2791             fn_table_entry->inferred_async_node = fn_table_entry->proto_node;
   2792         }
   2793 
   2794         if (scope_is_root_decls(tld_fn->base.parent_scope) &&
   2795             (import == g->root_import || import->data.structure.root_struct->package == g->panic_package))
   2796         {
   2797             if (g->have_pub_main && buf_eql_str(tld_fn->base.name, "main")) {
   2798                 g->main_fn = fn_table_entry;
   2799             } else if ((import->data.structure.root_struct->package == g->panic_package || g->have_pub_panic) &&
   2800                     buf_eql_str(tld_fn->base.name, "panic"))
   2801             {
   2802                 g->panic_fn = fn_table_entry;
   2803                 g->panic_tld_fn = tld_fn;
   2804             }
   2805         }
   2806     } else if (source_node->type == NodeTypeTestDecl) {
   2807         ZigFn *fn_table_entry = create_fn_raw(g, FnInlineAuto);
   2808 
   2809         get_fully_qualified_decl_name(&fn_table_entry->symbol_name, &tld_fn->base, true);
   2810 
   2811         tld_fn->fn_entry = fn_table_entry;
   2812 
   2813         fn_table_entry->proto_node = source_node;
   2814         fn_table_entry->fndef_scope = create_fndef_scope(g, source_node, tld_fn->base.parent_scope, fn_table_entry);
   2815         fn_table_entry->type_entry = get_test_fn_type(g);
   2816         fn_table_entry->body_node = source_node->data.test_decl.body;
   2817         fn_table_entry->is_test = true;
   2818 
   2819         g->fn_defs.append(fn_table_entry);
   2820         g->test_fns.append(fn_table_entry);
   2821 
   2822     } else {
   2823         zig_unreachable();
   2824     }
   2825 }
   2826 
   2827 static void resolve_decl_comptime(CodeGen *g, TldCompTime *tld_comptime) {
   2828     assert(tld_comptime->base.source_node->type == NodeTypeCompTime);
   2829     AstNode *expr_node = tld_comptime->base.source_node->data.comptime_expr.expr;
   2830     analyze_const_value(g, tld_comptime->base.parent_scope, expr_node, g->builtin_types.entry_void, nullptr);
   2831 }
   2832 
   2833 static void add_top_level_decl(CodeGen *g, ScopeDecls *decls_scope, Tld *tld) {
   2834     bool is_export = false;
   2835     if (tld->id == TldIdVar) {
   2836         assert(tld->source_node->type == NodeTypeVariableDeclaration);
   2837         is_export = tld->source_node->data.variable_declaration.is_export;
   2838     } else if (tld->id == TldIdFn) {
   2839         assert(tld->source_node->type == NodeTypeFnProto);
   2840         is_export = tld->source_node->data.fn_proto.is_export;
   2841 
   2842         if (!is_export && !tld->source_node->data.fn_proto.is_extern &&
   2843             tld->source_node->data.fn_proto.fn_def_node == nullptr)
   2844         {
   2845             add_node_error(g, tld->source_node, buf_sprintf("non-extern function has no body"));
   2846             return;
   2847         }
   2848     } else if (tld->id == TldIdUsingNamespace) {
   2849         g->resolve_queue.append(tld);
   2850     }
   2851     if (is_export) {
   2852         g->resolve_queue.append(tld);
   2853 
   2854         auto entry = g->exported_symbol_names.put_unique(tld->name, tld);
   2855         if (entry) {
   2856             AstNode *other_source_node = entry->value->source_node;
   2857             ErrorMsg *msg = add_node_error(g, tld->source_node,
   2858                     buf_sprintf("exported symbol collision: '%s'", buf_ptr(tld->name)));
   2859             add_error_note(g, msg, other_source_node, buf_sprintf("other symbol here"));
   2860         }
   2861     }
   2862 
   2863     if (tld->name != nullptr) {
   2864         auto entry = decls_scope->decl_table.put_unique(tld->name, tld);
   2865         if (entry) {
   2866             Tld *other_tld = entry->value;
   2867             ErrorMsg *msg = add_node_error(g, tld->source_node, buf_sprintf("redefinition of '%s'", buf_ptr(tld->name)));
   2868             add_error_note(g, msg, other_tld->source_node, buf_sprintf("previous definition is here"));
   2869             return;
   2870         }
   2871 
   2872         ZigType *type;
   2873         if (get_primitive_type(g, tld->name, &type) != ErrorPrimitiveTypeNotFound) {
   2874             add_node_error(g, tld->source_node,
   2875                 buf_sprintf("declaration shadows primitive type '%s'", buf_ptr(tld->name)));
   2876         }
   2877     }
   2878 }
   2879 
   2880 static void preview_test_decl(CodeGen *g, AstNode *node, ScopeDecls *decls_scope) {
   2881     assert(node->type == NodeTypeTestDecl);
   2882 
   2883     if (!g->is_test_build)
   2884         return;
   2885 
   2886     ZigType *import = get_scope_import(&decls_scope->base);
   2887     if (import->data.structure.root_struct->package != g->root_package)
   2888         return;
   2889 
   2890     Buf *decl_name_buf = node->data.test_decl.name;
   2891 
   2892     Buf *test_name = g->test_name_prefix ?
   2893         buf_sprintf("%s%s", buf_ptr(g->test_name_prefix), buf_ptr(decl_name_buf)) : decl_name_buf;
   2894 
   2895     if (g->test_filter != nullptr && strstr(buf_ptr(test_name), buf_ptr(g->test_filter)) == nullptr) {
   2896         return;
   2897     }
   2898 
   2899     TldFn *tld_fn = allocate<TldFn>(1);
   2900     init_tld(&tld_fn->base, TldIdFn, test_name, VisibModPrivate, node, &decls_scope->base);
   2901     g->resolve_queue.append(&tld_fn->base);
   2902 }
   2903 
   2904 static void preview_comptime_decl(CodeGen *g, AstNode *node, ScopeDecls *decls_scope) {
   2905     assert(node->type == NodeTypeCompTime);
   2906 
   2907     TldCompTime *tld_comptime = allocate<TldCompTime>(1);
   2908     init_tld(&tld_comptime->base, TldIdCompTime, nullptr, VisibModPrivate, node, &decls_scope->base);
   2909     g->resolve_queue.append(&tld_comptime->base);
   2910 }
   2911 
   2912 void init_tld(Tld *tld, TldId id, Buf *name, VisibMod visib_mod, AstNode *source_node,
   2913     Scope *parent_scope)
   2914 {
   2915     tld->id = id;
   2916     tld->name = name;
   2917     tld->visib_mod = visib_mod;
   2918     tld->source_node = source_node;
   2919     tld->import = source_node ? source_node->owner : nullptr;
   2920     tld->parent_scope = parent_scope;
   2921 }
   2922 
   2923 void update_compile_var(CodeGen *g, Buf *name, ConstExprValue *value) {
   2924     Tld *tld = get_container_scope(g->compile_var_import)->decl_table.get(name);
   2925     resolve_top_level_decl(g, tld, tld->source_node);
   2926     assert(tld->id == TldIdVar);
   2927     TldVar *tld_var = (TldVar *)tld;
   2928     tld_var->var->const_value = value;
   2929     tld_var->var->var_type = value->type;
   2930     tld_var->var->align_bytes = get_abi_alignment(g, value->type);
   2931 }
   2932 
   2933 void scan_decls(CodeGen *g, ScopeDecls *decls_scope, AstNode *node) {
   2934     switch (node->type) {
   2935         case NodeTypeContainerDecl:
   2936             for (size_t i = 0; i < node->data.container_decl.decls.length; i += 1) {
   2937                 AstNode *child = node->data.container_decl.decls.at(i);
   2938                 scan_decls(g, decls_scope, child);
   2939             }
   2940             break;
   2941         case NodeTypeFnDef:
   2942             scan_decls(g, decls_scope, node->data.fn_def.fn_proto);
   2943             break;
   2944         case NodeTypeVariableDeclaration:
   2945             {
   2946                 Buf *name = node->data.variable_declaration.symbol;
   2947                 VisibMod visib_mod = node->data.variable_declaration.visib_mod;
   2948                 TldVar *tld_var = allocate<TldVar>(1);
   2949                 init_tld(&tld_var->base, TldIdVar, name, visib_mod, node, &decls_scope->base);
   2950                 tld_var->extern_lib_name = node->data.variable_declaration.lib_name;
   2951                 add_top_level_decl(g, decls_scope, &tld_var->base);
   2952                 break;
   2953             }
   2954         case NodeTypeFnProto:
   2955             {
   2956                 // if the name is missing, we immediately announce an error
   2957                 Buf *fn_name = node->data.fn_proto.name;
   2958                 if (fn_name == nullptr) {
   2959                     add_node_error(g, node, buf_sprintf("missing function name"));
   2960                     break;
   2961                 }
   2962 
   2963                 VisibMod visib_mod = node->data.fn_proto.visib_mod;
   2964                 TldFn *tld_fn = allocate<TldFn>(1);
   2965                 init_tld(&tld_fn->base, TldIdFn, fn_name, visib_mod, node, &decls_scope->base);
   2966                 tld_fn->extern_lib_name = node->data.fn_proto.lib_name;
   2967                 add_top_level_decl(g, decls_scope, &tld_fn->base);
   2968 
   2969                 break;
   2970             }
   2971         case NodeTypeUsingNamespace: {
   2972             VisibMod visib_mod = node->data.using_namespace.visib_mod;
   2973             TldUsingNamespace *tld_using_namespace = allocate<TldUsingNamespace>(1);
   2974             init_tld(&tld_using_namespace->base, TldIdUsingNamespace, nullptr, visib_mod, node, &decls_scope->base);
   2975             add_top_level_decl(g, decls_scope, &tld_using_namespace->base);
   2976             decls_scope->use_decls.append(tld_using_namespace);
   2977             break;
   2978         }
   2979         case NodeTypeTestDecl:
   2980             preview_test_decl(g, node, decls_scope);
   2981             break;
   2982         case NodeTypeCompTime:
   2983             preview_comptime_decl(g, node, decls_scope);
   2984             break;
   2985         case NodeTypeParamDecl:
   2986         case NodeTypeReturnExpr:
   2987         case NodeTypeDefer:
   2988         case NodeTypeBlock:
   2989         case NodeTypeGroupedExpr:
   2990         case NodeTypeBinOpExpr:
   2991         case NodeTypeCatchExpr:
   2992         case NodeTypeFnCallExpr:
   2993         case NodeTypeArrayAccessExpr:
   2994         case NodeTypeSliceExpr:
   2995         case NodeTypeFloatLiteral:
   2996         case NodeTypeIntLiteral:
   2997         case NodeTypeStringLiteral:
   2998         case NodeTypeCharLiteral:
   2999         case NodeTypeBoolLiteral:
   3000         case NodeTypeNullLiteral:
   3001         case NodeTypeUndefinedLiteral:
   3002         case NodeTypeSymbol:
   3003         case NodeTypePrefixOpExpr:
   3004         case NodeTypePointerType:
   3005         case NodeTypeIfBoolExpr:
   3006         case NodeTypeWhileExpr:
   3007         case NodeTypeForExpr:
   3008         case NodeTypeSwitchExpr:
   3009         case NodeTypeSwitchProng:
   3010         case NodeTypeSwitchRange:
   3011         case NodeTypeBreak:
   3012         case NodeTypeContinue:
   3013         case NodeTypeUnreachable:
   3014         case NodeTypeAsmExpr:
   3015         case NodeTypeFieldAccessExpr:
   3016         case NodeTypePtrDeref:
   3017         case NodeTypeUnwrapOptional:
   3018         case NodeTypeStructField:
   3019         case NodeTypeContainerInitExpr:
   3020         case NodeTypeStructValueField:
   3021         case NodeTypeArrayType:
   3022         case NodeTypeInferredArrayType:
   3023         case NodeTypeErrorType:
   3024         case NodeTypeIfErrorExpr:
   3025         case NodeTypeIfOptional:
   3026         case NodeTypeErrorSetDecl:
   3027         case NodeTypeCancel:
   3028         case NodeTypeResume:
   3029         case NodeTypeAwaitExpr:
   3030         case NodeTypeSuspend:
   3031         case NodeTypeEnumLiteral:
   3032         case NodeTypeAnyFrameType:
   3033             zig_unreachable();
   3034     }
   3035 }
   3036 
   3037 static Error resolve_decl_container(CodeGen *g, TldContainer *tld_container) {
   3038     ZigType *type_entry = tld_container->type_entry;
   3039     assert(type_entry);
   3040 
   3041     switch (type_entry->id) {
   3042         case ZigTypeIdStruct:
   3043             return resolve_struct_type(g, tld_container->type_entry);
   3044         case ZigTypeIdEnum:
   3045             return resolve_enum_zero_bits(g, tld_container->type_entry);
   3046         case ZigTypeIdUnion:
   3047             return resolve_union_type(g, tld_container->type_entry);
   3048         default:
   3049             zig_unreachable();
   3050     }
   3051 }
   3052 
   3053 ZigType *validate_var_type(CodeGen *g, AstNode *source_node, ZigType *type_entry) {
   3054     switch (type_entry->id) {
   3055         case ZigTypeIdInvalid:
   3056             return g->builtin_types.entry_invalid;
   3057         case ZigTypeIdUnreachable:
   3058         case ZigTypeIdUndefined:
   3059         case ZigTypeIdNull:
   3060         case ZigTypeIdArgTuple:
   3061         case ZigTypeIdOpaque:
   3062             add_node_error(g, source_node, buf_sprintf("variable of type '%s' not allowed",
   3063                 buf_ptr(&type_entry->name)));
   3064             return g->builtin_types.entry_invalid;
   3065         case ZigTypeIdComptimeFloat:
   3066         case ZigTypeIdComptimeInt:
   3067         case ZigTypeIdEnumLiteral:
   3068         case ZigTypeIdMetaType:
   3069         case ZigTypeIdVoid:
   3070         case ZigTypeIdBool:
   3071         case ZigTypeIdInt:
   3072         case ZigTypeIdFloat:
   3073         case ZigTypeIdPointer:
   3074         case ZigTypeIdArray:
   3075         case ZigTypeIdStruct:
   3076         case ZigTypeIdOptional:
   3077         case ZigTypeIdErrorUnion:
   3078         case ZigTypeIdErrorSet:
   3079         case ZigTypeIdEnum:
   3080         case ZigTypeIdUnion:
   3081         case ZigTypeIdFn:
   3082         case ZigTypeIdBoundFn:
   3083         case ZigTypeIdVector:
   3084         case ZigTypeIdCoroFrame:
   3085         case ZigTypeIdAnyFrame:
   3086             return type_entry;
   3087     }
   3088     zig_unreachable();
   3089 }
   3090 
   3091 // Set name to nullptr to make the variable anonymous (not visible to programmer).
   3092 // TODO merge with definition of add_local_var in ir.cpp
   3093 ZigVar *add_variable(CodeGen *g, AstNode *source_node, Scope *parent_scope, Buf *name,
   3094     bool is_const, ConstExprValue *const_value, Tld *src_tld, ZigType *var_type)
   3095 {
   3096     Error err;
   3097     assert(const_value != nullptr);
   3098     assert(var_type != nullptr);
   3099 
   3100     ZigVar *variable_entry = allocate<ZigVar>(1);
   3101     variable_entry->const_value = const_value;
   3102     variable_entry->var_type = var_type;
   3103     variable_entry->parent_scope = parent_scope;
   3104     variable_entry->shadowable = false;
   3105     variable_entry->mem_slot_index = SIZE_MAX;
   3106     variable_entry->src_arg_index = SIZE_MAX;
   3107 
   3108     assert(name);
   3109     buf_init_from_buf(&variable_entry->name, name);
   3110 
   3111     if ((err = type_resolve(g, var_type, ResolveStatusAlignmentKnown))) {
   3112         variable_entry->var_type = g->builtin_types.entry_invalid;
   3113     } else {
   3114         variable_entry->align_bytes = get_abi_alignment(g, var_type);
   3115 
   3116         ZigVar *existing_var = find_variable(g, parent_scope, name, nullptr);
   3117         if (existing_var && !existing_var->shadowable) {
   3118             if (existing_var->var_type == nullptr || !type_is_invalid(existing_var->var_type)) {
   3119                 ErrorMsg *msg = add_node_error(g, source_node,
   3120                         buf_sprintf("redeclaration of variable '%s'", buf_ptr(name)));
   3121                 add_error_note(g, msg, existing_var->decl_node, buf_sprintf("previous declaration is here"));
   3122             }
   3123             variable_entry->var_type = g->builtin_types.entry_invalid;
   3124         } else {
   3125             ZigType *type;
   3126             if (get_primitive_type(g, name, &type) != ErrorPrimitiveTypeNotFound) {
   3127                 add_node_error(g, source_node,
   3128                         buf_sprintf("variable shadows primitive type '%s'", buf_ptr(name)));
   3129                 variable_entry->var_type = g->builtin_types.entry_invalid;
   3130             } else {
   3131                 Scope *search_scope = nullptr;
   3132                 if (src_tld == nullptr) {
   3133                     search_scope = parent_scope;
   3134                 } else if (src_tld->parent_scope != nullptr && src_tld->parent_scope->parent != nullptr) {
   3135                     search_scope = src_tld->parent_scope->parent;
   3136                 }
   3137                 if (search_scope != nullptr) {
   3138                     Tld *tld = find_decl(g, search_scope, name);
   3139                     if (tld != nullptr) {
   3140                         ErrorMsg *msg = add_node_error(g, source_node,
   3141                                 buf_sprintf("redefinition of '%s'", buf_ptr(name)));
   3142                         add_error_note(g, msg, tld->source_node, buf_sprintf("previous definition is here"));
   3143                         variable_entry->var_type = g->builtin_types.entry_invalid;
   3144                     }
   3145                 }
   3146             }
   3147         }
   3148     }
   3149 
   3150     Scope *child_scope;
   3151     if (source_node && source_node->type == NodeTypeParamDecl) {
   3152         child_scope = create_var_scope(g, source_node, parent_scope, variable_entry);
   3153     } else {
   3154         // it's already in the decls table
   3155         child_scope = parent_scope;
   3156     }
   3157 
   3158 
   3159     variable_entry->src_is_const = is_const;
   3160     variable_entry->gen_is_const = is_const;
   3161     variable_entry->decl_node = source_node;
   3162     variable_entry->child_scope = child_scope;
   3163 
   3164 
   3165     return variable_entry;
   3166 }
   3167 
   3168 static void resolve_decl_var(CodeGen *g, TldVar *tld_var) {
   3169     AstNode *source_node = tld_var->base.source_node;
   3170     AstNodeVariableDeclaration *var_decl = &source_node->data.variable_declaration;
   3171 
   3172     bool is_const = var_decl->is_const;
   3173     bool is_extern = var_decl->is_extern;
   3174     bool is_export = var_decl->is_export;
   3175     bool is_thread_local = var_decl->threadlocal_tok != nullptr;
   3176 
   3177     ZigType *explicit_type = nullptr;
   3178     if (var_decl->type) {
   3179         if (tld_var->analyzing_type) {
   3180             ErrorMsg *msg = add_node_error(g, var_decl->type,
   3181                 buf_sprintf("type of '%s' depends on itself", buf_ptr(tld_var->base.name)));
   3182             emit_error_notes_for_ref_stack(g, msg);
   3183             explicit_type = g->builtin_types.entry_invalid;
   3184         } else {
   3185             tld_var->analyzing_type = true;
   3186             ZigType *proposed_type = analyze_type_expr(g, tld_var->base.parent_scope, var_decl->type);
   3187             explicit_type = validate_var_type(g, var_decl->type, proposed_type);
   3188         }
   3189     }
   3190 
   3191     assert(!is_export || !is_extern);
   3192 
   3193     ConstExprValue *init_value = nullptr;
   3194 
   3195     // TODO more validation for types that can't be used for export/extern variables
   3196     ZigType *implicit_type = nullptr;
   3197     if (explicit_type && explicit_type->id == ZigTypeIdInvalid) {
   3198         implicit_type = explicit_type;
   3199     } else if (var_decl->expr) {
   3200         init_value = analyze_const_value(g, tld_var->base.parent_scope, var_decl->expr, explicit_type, var_decl->symbol);
   3201         assert(init_value);
   3202         implicit_type = init_value->type;
   3203 
   3204         if (implicit_type->id == ZigTypeIdUnreachable) {
   3205             add_node_error(g, source_node, buf_sprintf("variable initialization is unreachable"));
   3206             implicit_type = g->builtin_types.entry_invalid;
   3207         } else if ((!is_const || is_extern) &&
   3208                 (implicit_type->id == ZigTypeIdComptimeFloat ||
   3209                 implicit_type->id == ZigTypeIdComptimeInt ||
   3210                 implicit_type->id == ZigTypeIdEnumLiteral))
   3211         {
   3212             add_node_error(g, source_node, buf_sprintf("unable to infer variable type"));
   3213             implicit_type = g->builtin_types.entry_invalid;
   3214         } else if (implicit_type->id == ZigTypeIdNull) {
   3215             add_node_error(g, source_node, buf_sprintf("unable to infer variable type"));
   3216             implicit_type = g->builtin_types.entry_invalid;
   3217         } else if (implicit_type->id == ZigTypeIdMetaType && !is_const) {
   3218             add_node_error(g, source_node, buf_sprintf("variable of type 'type' must be constant"));
   3219             implicit_type = g->builtin_types.entry_invalid;
   3220         }
   3221         assert(implicit_type->id == ZigTypeIdInvalid || init_value->special != ConstValSpecialRuntime);
   3222     } else if (!is_extern) {
   3223         add_node_error(g, source_node, buf_sprintf("variables must be initialized"));
   3224         implicit_type = g->builtin_types.entry_invalid;
   3225     }
   3226 
   3227     ZigType *type = explicit_type ? explicit_type : implicit_type;
   3228     assert(type != nullptr); // should have been caught by the parser
   3229 
   3230     ConstExprValue *init_val = (init_value != nullptr) ? init_value : create_const_runtime(type);
   3231 
   3232     tld_var->var = add_variable(g, source_node, tld_var->base.parent_scope, var_decl->symbol,
   3233             is_const, init_val, &tld_var->base, type);
   3234     tld_var->var->is_thread_local = is_thread_local;
   3235 
   3236     if (implicit_type != nullptr && type_is_invalid(implicit_type)) {
   3237         tld_var->var->var_type = g->builtin_types.entry_invalid;
   3238     }
   3239 
   3240     if (var_decl->align_expr != nullptr) {
   3241         if (!analyze_const_align(g, tld_var->base.parent_scope, var_decl->align_expr, &tld_var->var->align_bytes)) {
   3242             tld_var->var->var_type = g->builtin_types.entry_invalid;
   3243         }
   3244     }
   3245 
   3246     if (var_decl->section_expr != nullptr) {
   3247         if (!analyze_const_string(g, tld_var->base.parent_scope, var_decl->section_expr, &tld_var->section_name)) {
   3248             tld_var->section_name = nullptr;
   3249         }
   3250     }
   3251 
   3252     if (is_thread_local && is_const) {
   3253         add_node_error(g, source_node, buf_sprintf("threadlocal variable cannot be constant"));
   3254     }
   3255 
   3256     if (is_export) {
   3257         add_var_export(g, tld_var->var, &tld_var->var->name, GlobalLinkageIdStrong);
   3258     }
   3259 
   3260     g->global_vars.append(tld_var);
   3261 }
   3262 
   3263 static void add_symbols_from_container(CodeGen *g, TldUsingNamespace *src_using_namespace,
   3264         TldUsingNamespace *dst_using_namespace, ScopeDecls* dest_decls_scope)
   3265 {
   3266     if (src_using_namespace->base.resolution == TldResolutionUnresolved ||
   3267         src_using_namespace->base.resolution == TldResolutionResolving)
   3268     {
   3269         assert(src_using_namespace->base.parent_scope->id == ScopeIdDecls);
   3270         ScopeDecls *src_decls_scope = (ScopeDecls *)src_using_namespace->base.parent_scope;
   3271         preview_use_decl(g, src_using_namespace, src_decls_scope);
   3272         if (src_using_namespace != dst_using_namespace) {
   3273             resolve_use_decl(g, src_using_namespace, src_decls_scope);
   3274         }
   3275     }
   3276 
   3277     ConstExprValue *use_expr = src_using_namespace->using_namespace_value;
   3278     if (type_is_invalid(use_expr->type)) {
   3279         dest_decls_scope->any_imports_failed = true;
   3280         return;
   3281     }
   3282 
   3283     dst_using_namespace->base.resolution = TldResolutionOk;
   3284 
   3285     assert(use_expr->special != ConstValSpecialRuntime);
   3286 
   3287     // The source scope for the imported symbols
   3288     ScopeDecls *src_scope = get_container_scope(use_expr->data.x_type);
   3289     // The top-level container where the symbols are defined, it's used in the
   3290     // loop below in order to exclude the ones coming from an import statement
   3291     ZigType *src_import = get_scope_import(&src_scope->base);
   3292     assert(src_import != nullptr);
   3293 
   3294     if (src_scope->any_imports_failed) {
   3295         dest_decls_scope->any_imports_failed = true;
   3296     }
   3297 
   3298     auto it = src_scope->decl_table.entry_iterator();
   3299     for (;;) {
   3300         auto *entry = it.next();
   3301         if (!entry)
   3302             break;
   3303 
   3304         Buf *target_tld_name = entry->key;
   3305         Tld *target_tld = entry->value;
   3306 
   3307         if (target_tld->visib_mod == VisibModPrivate) {
   3308             continue;
   3309         }
   3310 
   3311         if (target_tld->import != src_import) {
   3312             continue;
   3313         }
   3314 
   3315         auto existing_entry = dest_decls_scope->decl_table.put_unique(target_tld_name, target_tld);
   3316         if (existing_entry) {
   3317             Tld *existing_decl = existing_entry->value;
   3318             if (existing_decl != target_tld) {
   3319                 ErrorMsg *msg = add_node_error(g, dst_using_namespace->base.source_node,
   3320                         buf_sprintf("import of '%s' overrides existing definition",
   3321                             buf_ptr(target_tld_name)));
   3322                 add_error_note(g, msg, existing_decl->source_node, buf_sprintf("previous definition here"));
   3323                 add_error_note(g, msg, target_tld->source_node, buf_sprintf("imported definition here"));
   3324             }
   3325         }
   3326     }
   3327 
   3328     for (size_t i = 0; i < src_scope->use_decls.length; i += 1) {
   3329         TldUsingNamespace *tld_using_namespace = src_scope->use_decls.at(i);
   3330         if (tld_using_namespace->base.visib_mod != VisibModPrivate)
   3331             add_symbols_from_container(g, tld_using_namespace, dst_using_namespace, dest_decls_scope);
   3332     }
   3333 }
   3334 
   3335 static void resolve_use_decl(CodeGen *g, TldUsingNamespace *tld_using_namespace, ScopeDecls *dest_decls_scope) {
   3336     if (tld_using_namespace->base.resolution == TldResolutionOk ||
   3337         tld_using_namespace->base.resolution == TldResolutionInvalid)
   3338     {
   3339         return;
   3340     }
   3341     add_symbols_from_container(g, tld_using_namespace, tld_using_namespace, dest_decls_scope);
   3342 }
   3343 
   3344 static void preview_use_decl(CodeGen *g, TldUsingNamespace *using_namespace, ScopeDecls *dest_decls_scope) {
   3345     if (using_namespace->base.resolution == TldResolutionOk ||
   3346         using_namespace->base.resolution == TldResolutionInvalid ||
   3347         using_namespace->using_namespace_value != nullptr)
   3348     {
   3349         return;
   3350     }
   3351 
   3352     using_namespace->base.resolution = TldResolutionResolving;
   3353     assert(using_namespace->base.source_node->type == NodeTypeUsingNamespace);
   3354     ConstExprValue *result = analyze_const_value(g, &dest_decls_scope->base,
   3355         using_namespace->base.source_node->data.using_namespace.expr, g->builtin_types.entry_type, nullptr);
   3356     using_namespace->using_namespace_value = result;
   3357 
   3358     if (type_is_invalid(result->type)) {
   3359         dest_decls_scope->any_imports_failed = true;
   3360         using_namespace->base.resolution = TldResolutionInvalid;
   3361         using_namespace->using_namespace_value = &g->invalid_instruction->value;
   3362         return;
   3363     }
   3364 
   3365     if (!is_container(result->data.x_type)) {
   3366         add_node_error(g, using_namespace->base.source_node,
   3367             buf_sprintf("expected struct, enum, or union; found '%s'", buf_ptr(&result->data.x_type->name)));
   3368         dest_decls_scope->any_imports_failed = true;
   3369         using_namespace->base.resolution = TldResolutionInvalid;
   3370         using_namespace->using_namespace_value = &g->invalid_instruction->value;
   3371         return;
   3372     }
   3373 }
   3374 
   3375 void resolve_top_level_decl(CodeGen *g, Tld *tld, AstNode *source_node) {
   3376     if (tld->resolution != TldResolutionUnresolved)
   3377         return;
   3378 
   3379     assert(tld->resolution != TldResolutionResolving);
   3380     tld->resolution = TldResolutionResolving;
   3381     g->tld_ref_source_node_stack.append(source_node);
   3382 
   3383     switch (tld->id) {
   3384         case TldIdVar:
   3385             {
   3386                 TldVar *tld_var = (TldVar *)tld;
   3387                 resolve_decl_var(g, tld_var);
   3388                 break;
   3389             }
   3390         case TldIdFn:
   3391             {
   3392                 TldFn *tld_fn = (TldFn *)tld;
   3393                 resolve_decl_fn(g, tld_fn);
   3394                 break;
   3395             }
   3396         case TldIdContainer:
   3397             {
   3398                 TldContainer *tld_container = (TldContainer *)tld;
   3399                 resolve_decl_container(g, tld_container);
   3400                 break;
   3401             }
   3402         case TldIdCompTime:
   3403             {
   3404                 TldCompTime *tld_comptime = (TldCompTime *)tld;
   3405                 resolve_decl_comptime(g, tld_comptime);
   3406                 break;
   3407             }
   3408         case TldIdUsingNamespace: {
   3409             TldUsingNamespace *tld_using_namespace = (TldUsingNamespace *)tld;
   3410             assert(tld_using_namespace->base.parent_scope->id == ScopeIdDecls);
   3411             ScopeDecls *dest_decls_scope = (ScopeDecls *)tld_using_namespace->base.parent_scope;
   3412             preview_use_decl(g, tld_using_namespace, dest_decls_scope);
   3413             resolve_use_decl(g, tld_using_namespace, dest_decls_scope);
   3414             break;
   3415         }
   3416     }
   3417 
   3418     tld->resolution = TldResolutionOk;
   3419     g->tld_ref_source_node_stack.pop();
   3420 }
   3421 
   3422 Tld *find_container_decl(CodeGen *g, ScopeDecls *decls_scope, Buf *name) {
   3423     // resolve all the using_namespace decls
   3424     for (size_t i = 0; i < decls_scope->use_decls.length; i += 1) {
   3425         TldUsingNamespace *tld_using_namespace = decls_scope->use_decls.at(i);
   3426         if (tld_using_namespace->base.resolution == TldResolutionUnresolved) {
   3427             preview_use_decl(g, tld_using_namespace, decls_scope);
   3428             resolve_use_decl(g, tld_using_namespace, decls_scope);
   3429         }
   3430     }
   3431 
   3432     auto entry = decls_scope->decl_table.maybe_get(name);
   3433     return (entry == nullptr) ? nullptr : entry->value;
   3434 }
   3435 
   3436 Tld *find_decl(CodeGen *g, Scope *scope, Buf *name) {
   3437     while (scope) {
   3438         if (scope->id == ScopeIdDecls) {
   3439             ScopeDecls *decls_scope = (ScopeDecls *)scope;
   3440 
   3441             Tld *result = find_container_decl(g, decls_scope, name);
   3442             if (result != nullptr)
   3443                 return result;
   3444         }
   3445         scope = scope->parent;
   3446     }
   3447     return nullptr;
   3448 }
   3449 
   3450 ZigVar *find_variable(CodeGen *g, Scope *scope, Buf *name, ScopeFnDef **crossed_fndef_scope) {
   3451     ScopeFnDef *my_crossed_fndef_scope = nullptr;
   3452     while (scope) {
   3453         if (scope->id == ScopeIdVarDecl) {
   3454             ScopeVarDecl *var_scope = (ScopeVarDecl *)scope;
   3455             if (buf_eql_buf(name, &var_scope->var->name)) {
   3456                 if (crossed_fndef_scope != nullptr)
   3457                     *crossed_fndef_scope = my_crossed_fndef_scope;
   3458                 return var_scope->var;
   3459             }
   3460         } else if (scope->id == ScopeIdDecls) {
   3461             ScopeDecls *decls_scope = (ScopeDecls *)scope;
   3462             auto entry = decls_scope->decl_table.maybe_get(name);
   3463             if (entry) {
   3464                 Tld *tld = entry->value;
   3465                 if (tld->id == TldIdVar) {
   3466                     TldVar *tld_var = (TldVar *)tld;
   3467                     if (tld_var->var) {
   3468                         if (crossed_fndef_scope != nullptr)
   3469                             *crossed_fndef_scope = nullptr;
   3470                         return tld_var->var;
   3471                     }
   3472                 }
   3473             }
   3474         } else if (scope->id == ScopeIdFnDef) {
   3475             my_crossed_fndef_scope = (ScopeFnDef *)scope;
   3476         }
   3477         scope = scope->parent;
   3478     }
   3479 
   3480     return nullptr;
   3481 }
   3482 
   3483 ZigFn *scope_fn_entry(Scope *scope) {
   3484     while (scope) {
   3485         if (scope->id == ScopeIdFnDef) {
   3486             ScopeFnDef *fn_scope = (ScopeFnDef *)scope;
   3487             return fn_scope->fn_entry;
   3488         }
   3489         scope = scope->parent;
   3490     }
   3491     return nullptr;
   3492 }
   3493 
   3494 ZigPackage *scope_package(Scope *scope) {
   3495     ZigType *import = get_scope_import(scope);
   3496     assert(is_top_level_struct(import));
   3497     return import->data.structure.root_struct->package;
   3498 }
   3499 
   3500 TypeEnumField *find_enum_type_field(ZigType *enum_type, Buf *name) {
   3501     assert(enum_type->id == ZigTypeIdEnum);
   3502     if (enum_type->data.enumeration.src_field_count == 0)
   3503         return nullptr;
   3504     auto entry = enum_type->data.enumeration.fields_by_name.maybe_get(name);
   3505     if (entry == nullptr)
   3506         return nullptr;
   3507     return entry->value;
   3508 }
   3509 
   3510 TypeStructField *find_struct_type_field(ZigType *type_entry, Buf *name) {
   3511     assert(type_entry->id == ZigTypeIdStruct);
   3512     assert(type_is_resolved(type_entry, ResolveStatusZeroBitsKnown));
   3513     if (type_entry->data.structure.src_field_count == 0)
   3514         return nullptr;
   3515     auto entry = type_entry->data.structure.fields_by_name.maybe_get(name);
   3516     if (entry == nullptr)
   3517         return nullptr;
   3518     return entry->value;
   3519 }
   3520 
   3521 TypeUnionField *find_union_type_field(ZigType *type_entry, Buf *name) {
   3522     assert(type_entry->id == ZigTypeIdUnion);
   3523     assert(type_is_resolved(type_entry, ResolveStatusZeroBitsKnown));
   3524     if (type_entry->data.unionation.src_field_count == 0)
   3525         return nullptr;
   3526     auto entry = type_entry->data.unionation.fields_by_name.maybe_get(name);
   3527     if (entry == nullptr)
   3528         return nullptr;
   3529     return entry->value;
   3530 }
   3531 
   3532 TypeUnionField *find_union_field_by_tag(ZigType *type_entry, const BigInt *tag) {
   3533     assert(type_entry->id == ZigTypeIdUnion);
   3534     assert(type_is_resolved(type_entry, ResolveStatusZeroBitsKnown));
   3535     for (uint32_t i = 0; i < type_entry->data.unionation.src_field_count; i += 1) {
   3536         TypeUnionField *field = &type_entry->data.unionation.fields[i];
   3537         if (bigint_cmp(&field->enum_field->value, tag) == CmpEQ) {
   3538             return field;
   3539         }
   3540     }
   3541     return nullptr;
   3542 }
   3543 
   3544 TypeEnumField *find_enum_field_by_tag(ZigType *enum_type, const BigInt *tag) {
   3545     assert(enum_type->data.enumeration.zero_bits_known);
   3546     for (uint32_t i = 0; i < enum_type->data.enumeration.src_field_count; i += 1) {
   3547         TypeEnumField *field = &enum_type->data.enumeration.fields[i];
   3548         if (bigint_cmp(&field->value, tag) == CmpEQ) {
   3549             return field;
   3550         }
   3551     }
   3552     return nullptr;
   3553 }
   3554 
   3555 
   3556 bool is_container(ZigType *type_entry) {
   3557     switch (type_entry->id) {
   3558         case ZigTypeIdInvalid:
   3559             zig_unreachable();
   3560         case ZigTypeIdStruct:
   3561             return !type_entry->data.structure.is_slice;
   3562         case ZigTypeIdEnum:
   3563         case ZigTypeIdUnion:
   3564             return true;
   3565         case ZigTypeIdPointer:
   3566         case ZigTypeIdMetaType:
   3567         case ZigTypeIdVoid:
   3568         case ZigTypeIdBool:
   3569         case ZigTypeIdUnreachable:
   3570         case ZigTypeIdInt:
   3571         case ZigTypeIdFloat:
   3572         case ZigTypeIdArray:
   3573         case ZigTypeIdComptimeFloat:
   3574         case ZigTypeIdComptimeInt:
   3575         case ZigTypeIdEnumLiteral:
   3576         case ZigTypeIdUndefined:
   3577         case ZigTypeIdNull:
   3578         case ZigTypeIdOptional:
   3579         case ZigTypeIdErrorUnion:
   3580         case ZigTypeIdErrorSet:
   3581         case ZigTypeIdFn:
   3582         case ZigTypeIdBoundFn:
   3583         case ZigTypeIdArgTuple:
   3584         case ZigTypeIdOpaque:
   3585         case ZigTypeIdVector:
   3586         case ZigTypeIdCoroFrame:
   3587         case ZigTypeIdAnyFrame:
   3588             return false;
   3589     }
   3590     zig_unreachable();
   3591 }
   3592 
   3593 bool is_ref(ZigType *type_entry) {
   3594     return type_entry->id == ZigTypeIdPointer && type_entry->data.pointer.ptr_len == PtrLenSingle;
   3595 }
   3596 
   3597 bool is_array_ref(ZigType *type_entry) {
   3598     ZigType *array = is_ref(type_entry) ?
   3599         type_entry->data.pointer.child_type : type_entry;
   3600     return array->id == ZigTypeIdArray;
   3601 }
   3602 
   3603 bool is_container_ref(ZigType *parent_ty) {
   3604     ZigType *ty = is_ref(parent_ty) ? parent_ty->data.pointer.child_type : parent_ty;
   3605     return is_slice(ty) || is_container(ty);
   3606 }
   3607 
   3608 ZigType *container_ref_type(ZigType *type_entry) {
   3609     assert(is_container_ref(type_entry));
   3610     return is_ref(type_entry) ?
   3611         type_entry->data.pointer.child_type : type_entry;
   3612 }
   3613 
   3614 Error resolve_container_type(CodeGen *g, ZigType *type_entry) {
   3615     switch (type_entry->id) {
   3616         case ZigTypeIdStruct:
   3617             return resolve_struct_type(g, type_entry);
   3618         case ZigTypeIdEnum:
   3619             return resolve_enum_zero_bits(g, type_entry);
   3620         case ZigTypeIdUnion:
   3621             return resolve_union_type(g, type_entry);
   3622         case ZigTypeIdPointer:
   3623         case ZigTypeIdMetaType:
   3624         case ZigTypeIdVoid:
   3625         case ZigTypeIdBool:
   3626         case ZigTypeIdUnreachable:
   3627         case ZigTypeIdInt:
   3628         case ZigTypeIdFloat:
   3629         case ZigTypeIdArray:
   3630         case ZigTypeIdComptimeFloat:
   3631         case ZigTypeIdComptimeInt:
   3632         case ZigTypeIdEnumLiteral:
   3633         case ZigTypeIdUndefined:
   3634         case ZigTypeIdNull:
   3635         case ZigTypeIdOptional:
   3636         case ZigTypeIdErrorUnion:
   3637         case ZigTypeIdErrorSet:
   3638         case ZigTypeIdFn:
   3639         case ZigTypeIdBoundFn:
   3640         case ZigTypeIdInvalid:
   3641         case ZigTypeIdArgTuple:
   3642         case ZigTypeIdOpaque:
   3643         case ZigTypeIdVector:
   3644         case ZigTypeIdCoroFrame:
   3645         case ZigTypeIdAnyFrame:
   3646             zig_unreachable();
   3647     }
   3648     zig_unreachable();
   3649 }
   3650 
   3651 ZigType *get_src_ptr_type(ZigType *type) {
   3652     if (type->id == ZigTypeIdPointer) return type;
   3653     if (type->id == ZigTypeIdFn) return type;
   3654     if (type->id == ZigTypeIdAnyFrame) return type;
   3655     if (type->id == ZigTypeIdOptional) {
   3656         if (type->data.maybe.child_type->id == ZigTypeIdPointer) {
   3657             return type->data.maybe.child_type->data.pointer.allow_zero ? nullptr : type->data.maybe.child_type;
   3658         }
   3659         if (type->data.maybe.child_type->id == ZigTypeIdFn) return type->data.maybe.child_type;
   3660         if (type->data.maybe.child_type->id == ZigTypeIdAnyFrame) return type->data.maybe.child_type;
   3661     }
   3662     return nullptr;
   3663 }
   3664 
   3665 ZigType *get_codegen_ptr_type(ZigType *type) {
   3666     ZigType *ty = get_src_ptr_type(type);
   3667     if (ty == nullptr || !type_has_bits(ty))
   3668         return nullptr;
   3669     return ty;
   3670 }
   3671 
   3672 bool type_is_nonnull_ptr(ZigType *type) {
   3673     return get_codegen_ptr_type(type) == type && !ptr_allows_addr_zero(type);
   3674 }
   3675 
   3676 static uint32_t get_coro_frame_align_bytes(CodeGen *g) {
   3677     uint32_t a = g->pointer_size_bytes * 2;
   3678     // promises have at least alignment 8 so that we can have 3 extra bits when doing atomicrmw
   3679     if (a < 8) a = 8;
   3680     return a;
   3681 }
   3682 
   3683 uint32_t get_ptr_align(CodeGen *g, ZigType *type) {
   3684     ZigType *ptr_type = get_src_ptr_type(type);
   3685     if (ptr_type->id == ZigTypeIdPointer) {
   3686         return (ptr_type->data.pointer.explicit_alignment == 0) ?
   3687             get_abi_alignment(g, ptr_type->data.pointer.child_type) : ptr_type->data.pointer.explicit_alignment;
   3688     } else if (ptr_type->id == ZigTypeIdFn) {
   3689         // I tried making this use LLVMABIAlignmentOfType but it trips this assertion in LLVM:
   3690         // "Cannot getTypeInfo() on a type that is unsized!"
   3691         // when getting the alignment of `?extern fn() void`.
   3692         // See http://lists.llvm.org/pipermail/llvm-dev/2018-September/126142.html
   3693         return (ptr_type->data.fn.fn_type_id.alignment == 0) ? 1 : ptr_type->data.fn.fn_type_id.alignment;
   3694     } else if (ptr_type->id == ZigTypeIdAnyFrame) {
   3695         return get_coro_frame_align_bytes(g);
   3696     } else {
   3697         zig_unreachable();
   3698     }
   3699 }
   3700 
   3701 bool get_ptr_const(ZigType *type) {
   3702     ZigType *ptr_type = get_src_ptr_type(type);
   3703     if (ptr_type->id == ZigTypeIdPointer) {
   3704         return ptr_type->data.pointer.is_const;
   3705     } else if (ptr_type->id == ZigTypeIdFn) {
   3706         return true;
   3707     } else if (ptr_type->id == ZigTypeIdAnyFrame) {
   3708         return true;
   3709     } else {
   3710         zig_unreachable();
   3711     }
   3712 }
   3713 
   3714 AstNode *get_param_decl_node(ZigFn *fn_entry, size_t index) {
   3715     if (fn_entry->param_source_nodes)
   3716         return fn_entry->param_source_nodes[index];
   3717     else if (fn_entry->proto_node)
   3718         return fn_entry->proto_node->data.fn_proto.params.at(index);
   3719     else
   3720         return nullptr;
   3721 }
   3722 
   3723 static void define_local_param_variables(CodeGen *g, ZigFn *fn_table_entry) {
   3724     ZigType *fn_type = fn_table_entry->type_entry;
   3725     assert(!fn_type->data.fn.is_generic);
   3726     FnTypeId *fn_type_id = &fn_type->data.fn.fn_type_id;
   3727     for (size_t i = 0; i < fn_type_id->param_count; i += 1) {
   3728         FnTypeParamInfo *param_info = &fn_type_id->param_info[i];
   3729         AstNode *param_decl_node = get_param_decl_node(fn_table_entry, i);
   3730         Buf *param_name;
   3731         bool is_var_args = param_decl_node && param_decl_node->data.param_decl.is_var_args;
   3732         if (param_decl_node && !is_var_args) {
   3733             param_name = param_decl_node->data.param_decl.name;
   3734         } else {
   3735             param_name = buf_sprintf("arg%" ZIG_PRI_usize "", i);
   3736         }
   3737         if (param_name == nullptr) {
   3738             continue;
   3739         }
   3740 
   3741         ZigType *param_type = param_info->type;
   3742         bool is_noalias = param_info->is_noalias;
   3743 
   3744         if (is_noalias && get_codegen_ptr_type(param_type) == nullptr) {
   3745             add_node_error(g, param_decl_node, buf_sprintf("noalias on non-pointer parameter"));
   3746         }
   3747 
   3748         ZigVar *var = add_variable(g, param_decl_node, fn_table_entry->child_scope,
   3749                 param_name, true, create_const_runtime(param_type), nullptr, param_type);
   3750         var->src_arg_index = i;
   3751         fn_table_entry->child_scope = var->child_scope;
   3752         var->shadowable = var->shadowable || is_var_args;
   3753 
   3754         if (type_has_bits(param_type)) {
   3755             fn_table_entry->variable_list.append(var);
   3756         }
   3757     }
   3758 }
   3759 
   3760 bool resolve_inferred_error_set(CodeGen *g, ZigType *err_set_type, AstNode *source_node) {
   3761     assert(err_set_type->id == ZigTypeIdErrorSet);
   3762     ZigFn *infer_fn = err_set_type->data.error_set.infer_fn;
   3763     if (infer_fn != nullptr) {
   3764         if (infer_fn->anal_state == FnAnalStateInvalid) {
   3765             return false;
   3766         } else if (infer_fn->anal_state == FnAnalStateReady) {
   3767             analyze_fn_body(g, infer_fn);
   3768             if (err_set_type->data.error_set.infer_fn != nullptr) {
   3769                 assert(g->errors.length != 0);
   3770                 return false;
   3771             }
   3772         } else {
   3773             add_node_error(g, source_node,
   3774                 buf_sprintf("cannot resolve inferred error set '%s': function '%s' not fully analyzed yet",
   3775                     buf_ptr(&err_set_type->name), buf_ptr(&err_set_type->data.error_set.infer_fn->symbol_name)));
   3776             return false;
   3777         }
   3778     }
   3779     return true;
   3780 }
   3781 
   3782 static void resolve_async_fn_frame(CodeGen *g, ZigFn *fn) {
   3783     ZigType *frame_type = get_coro_frame_type(g, fn);
   3784     Error err;
   3785     if ((err = type_resolve(g, frame_type, ResolveStatusSizeKnown))) {
   3786         fn->anal_state = FnAnalStateInvalid;
   3787         return;
   3788     }
   3789 }
   3790 
   3791 bool fn_is_async(ZigFn *fn) {
   3792     assert(fn->inferred_async_node != nullptr);
   3793     assert(fn->inferred_async_node != inferred_async_checking);
   3794     return fn->inferred_async_node != inferred_async_none;
   3795 }
   3796 
   3797 static void add_async_error_notes(CodeGen *g, ErrorMsg *msg, ZigFn *fn) {
   3798     assert(fn->inferred_async_node != nullptr);
   3799     assert(fn->inferred_async_node != inferred_async_checking);
   3800     assert(fn->inferred_async_node != inferred_async_none);
   3801     if (fn->inferred_async_fn != nullptr) {
   3802         ErrorMsg *new_msg = add_error_note(g, msg, fn->inferred_async_node,
   3803             buf_sprintf("async function call here"));
   3804         return add_async_error_notes(g, new_msg, fn->inferred_async_fn);
   3805     } else if (fn->inferred_async_node->type == NodeTypeFnProto) {
   3806         add_error_note(g, msg, fn->inferred_async_node,
   3807             buf_sprintf("async calling convention here"));
   3808     } else if (fn->inferred_async_node->type == NodeTypeSuspend) {
   3809         add_error_note(g, msg, fn->inferred_async_node,
   3810             buf_sprintf("suspends here"));
   3811     } else if (fn->inferred_async_node->type == NodeTypeAwaitExpr) {
   3812         add_error_note(g, msg, fn->inferred_async_node,
   3813             buf_sprintf("await is a suspend point"));
   3814     } else if (fn->inferred_async_node->type == NodeTypeCancel) {
   3815         add_error_note(g, msg, fn->inferred_async_node,
   3816             buf_sprintf("cancel is a suspend point"));
   3817     } else {
   3818         zig_unreachable();
   3819     }
   3820 }
   3821 
   3822 // This function resolves functions being inferred async.
   3823 static void analyze_fn_async(CodeGen *g, ZigFn *fn) {
   3824     if (fn->inferred_async_node == inferred_async_checking) {
   3825         // TODO call graph cycle detected, disallow the recursion
   3826         fn->inferred_async_node = inferred_async_none;
   3827         return;
   3828     }
   3829     if (fn->inferred_async_node == inferred_async_none) {
   3830         return;
   3831     }
   3832     if (fn->inferred_async_node != nullptr) {
   3833         resolve_async_fn_frame(g, fn);
   3834         return;
   3835     }
   3836     fn->inferred_async_node = inferred_async_checking;
   3837 
   3838     bool must_not_be_async = false;
   3839     if (fn->type_entry->data.fn.fn_type_id.cc != CallingConventionUnspecified) {
   3840         must_not_be_async = true;
   3841         fn->inferred_async_node = inferred_async_none;
   3842     }
   3843 
   3844     for (size_t i = 0; i < fn->call_list.length; i += 1) {
   3845         IrInstructionCallGen *call = fn->call_list.at(i);
   3846         ZigFn *callee = call->fn_entry;
   3847         if (callee == nullptr) {
   3848             // TODO function pointer call here, could be anything
   3849             continue;
   3850         }
   3851 
   3852         if (callee->type_entry->data.fn.fn_type_id.cc != CallingConventionUnspecified)
   3853             continue;
   3854         if (callee->anal_state == FnAnalStateReady) {
   3855             analyze_fn_body(g, callee);
   3856             if (callee->anal_state == FnAnalStateInvalid) {
   3857                 fn->anal_state = FnAnalStateInvalid;
   3858                 return;
   3859             }
   3860         }
   3861         assert(callee->anal_state == FnAnalStateComplete);
   3862         analyze_fn_async(g, callee);
   3863         if (callee->anal_state == FnAnalStateInvalid) {
   3864             fn->anal_state = FnAnalStateInvalid;
   3865             return;
   3866         }
   3867         if (fn_is_async(callee)) {
   3868             fn->inferred_async_node = call->base.source_node;
   3869             fn->inferred_async_fn = callee;
   3870             if (must_not_be_async) {
   3871                 ErrorMsg *msg = add_node_error(g, fn->proto_node,
   3872                     buf_sprintf("function with calling convention '%s' cannot be async",
   3873                         calling_convention_name(fn->type_entry->data.fn.fn_type_id.cc)));
   3874                 add_async_error_notes(g, msg, fn);
   3875                 fn->anal_state = FnAnalStateInvalid;
   3876                 return;
   3877             }
   3878             resolve_async_fn_frame(g, fn);
   3879             return;
   3880         }
   3881     }
   3882     fn->inferred_async_node = inferred_async_none;
   3883 }
   3884 
   3885 static void analyze_fn_ir(CodeGen *g, ZigFn *fn_table_entry, AstNode *return_type_node) {
   3886     ZigType *fn_type = fn_table_entry->type_entry;
   3887     assert(!fn_type->data.fn.is_generic);
   3888     FnTypeId *fn_type_id = &fn_type->data.fn.fn_type_id;
   3889 
   3890     ZigType *block_return_type = ir_analyze(g, &fn_table_entry->ir_executable,
   3891             &fn_table_entry->analyzed_executable, fn_type_id->return_type, return_type_node);
   3892     fn_table_entry->src_implicit_return_type = block_return_type;
   3893 
   3894     if (type_is_invalid(block_return_type) || fn_table_entry->analyzed_executable.invalid) {
   3895         assert(g->errors.length > 0);
   3896         fn_table_entry->anal_state = FnAnalStateInvalid;
   3897         return;
   3898     }
   3899 
   3900     if (fn_type_id->return_type->id == ZigTypeIdErrorUnion) {
   3901         ZigType *return_err_set_type = fn_type_id->return_type->data.error_union.err_set_type;
   3902         if (return_err_set_type->data.error_set.infer_fn != nullptr) {
   3903             ZigType *inferred_err_set_type;
   3904             if (fn_table_entry->src_implicit_return_type->id == ZigTypeIdErrorSet) {
   3905                 inferred_err_set_type = fn_table_entry->src_implicit_return_type;
   3906             } else if (fn_table_entry->src_implicit_return_type->id == ZigTypeIdErrorUnion) {
   3907                 inferred_err_set_type = fn_table_entry->src_implicit_return_type->data.error_union.err_set_type;
   3908             } else {
   3909                 add_node_error(g, return_type_node,
   3910                         buf_sprintf("function with inferred error set must return at least one possible error"));
   3911                 fn_table_entry->anal_state = FnAnalStateInvalid;
   3912                 return;
   3913             }
   3914 
   3915             if (inferred_err_set_type->data.error_set.infer_fn != nullptr) {
   3916                 if (!resolve_inferred_error_set(g, inferred_err_set_type, return_type_node)) {
   3917                     fn_table_entry->anal_state = FnAnalStateInvalid;
   3918                     return;
   3919                 }
   3920             }
   3921 
   3922             return_err_set_type->data.error_set.infer_fn = nullptr;
   3923             if (type_is_global_error_set(inferred_err_set_type)) {
   3924                 return_err_set_type->data.error_set.err_count = UINT32_MAX;
   3925             } else {
   3926                 return_err_set_type->data.error_set.err_count = inferred_err_set_type->data.error_set.err_count;
   3927                 if (inferred_err_set_type->data.error_set.err_count > 0) {
   3928                     return_err_set_type->data.error_set.errors = allocate<ErrorTableEntry *>(inferred_err_set_type->data.error_set.err_count);
   3929                     for (uint32_t i = 0; i < inferred_err_set_type->data.error_set.err_count; i += 1) {
   3930                         return_err_set_type->data.error_set.errors[i] = inferred_err_set_type->data.error_set.errors[i];
   3931                     }
   3932                 }
   3933             }
   3934         }
   3935     }
   3936 
   3937     if (g->verbose_ir) {
   3938         fprintf(stderr, "fn %s() { // (analyzed)\n", buf_ptr(&fn_table_entry->symbol_name));
   3939         ir_print(g, stderr, &fn_table_entry->analyzed_executable, 4);
   3940         fprintf(stderr, "}\n");
   3941     }
   3942     fn_table_entry->anal_state = FnAnalStateComplete;
   3943 }
   3944 
   3945 static void analyze_fn_body(CodeGen *g, ZigFn *fn_table_entry) {
   3946     assert(fn_table_entry->anal_state != FnAnalStateProbing);
   3947     if (fn_table_entry->anal_state != FnAnalStateReady)
   3948         return;
   3949 
   3950     fn_table_entry->anal_state = FnAnalStateProbing;
   3951 
   3952     AstNode *return_type_node = (fn_table_entry->proto_node != nullptr) ?
   3953         fn_table_entry->proto_node->data.fn_proto.return_type : fn_table_entry->fndef_scope->base.source_node;
   3954 
   3955     assert(fn_table_entry->fndef_scope);
   3956     if (!fn_table_entry->child_scope)
   3957         fn_table_entry->child_scope = &fn_table_entry->fndef_scope->base;
   3958 
   3959     define_local_param_variables(g, fn_table_entry);
   3960 
   3961     ZigType *fn_type = fn_table_entry->type_entry;
   3962     assert(!fn_type->data.fn.is_generic);
   3963 
   3964     ir_gen_fn(g, fn_table_entry);
   3965     if (fn_table_entry->ir_executable.invalid) {
   3966         fn_table_entry->anal_state = FnAnalStateInvalid;
   3967         return;
   3968     }
   3969     if (g->verbose_ir) {
   3970         fprintf(stderr, "\n");
   3971         ast_render(stderr, fn_table_entry->body_node, 4);
   3972         fprintf(stderr, "\n{ // (IR)\n");
   3973         ir_print(g, stderr, &fn_table_entry->ir_executable, 4);
   3974         fprintf(stderr, "}\n");
   3975     }
   3976 
   3977     analyze_fn_ir(g, fn_table_entry, return_type_node);
   3978 }
   3979 
   3980 ZigType *add_source_file(CodeGen *g, ZigPackage *package, Buf *resolved_path, Buf *source_code,
   3981         SourceKind source_kind)
   3982 {
   3983     if (g->verbose_tokenize) {
   3984         fprintf(stderr, "\nOriginal Source (%s):\n", buf_ptr(resolved_path));
   3985         fprintf(stderr, "----------------\n");
   3986         fprintf(stderr, "%s\n", buf_ptr(source_code));
   3987 
   3988         fprintf(stderr, "\nTokens:\n");
   3989         fprintf(stderr, "---------\n");
   3990     }
   3991 
   3992     Tokenization tokenization = {0};
   3993     tokenize(source_code, &tokenization);
   3994 
   3995     if (tokenization.err) {
   3996         ErrorMsg *err = err_msg_create_with_line(resolved_path, tokenization.err_line, tokenization.err_column,
   3997                 source_code, tokenization.line_offsets, tokenization.err);
   3998 
   3999         print_err_msg(err, g->err_color);
   4000         exit(1);
   4001     }
   4002 
   4003     if (g->verbose_tokenize) {
   4004         print_tokens(source_code, tokenization.tokens);
   4005 
   4006         fprintf(stderr, "\nAST:\n");
   4007         fprintf(stderr, "------\n");
   4008     }
   4009 
   4010     Buf *src_dirname = buf_alloc();
   4011     Buf *src_basename = buf_alloc();
   4012     os_path_split(resolved_path, src_dirname, src_basename);
   4013 
   4014     Buf noextname = BUF_INIT;
   4015     os_path_extname(resolved_path, &noextname, nullptr);
   4016 
   4017     Buf *pkg_root_src_dir = &package->root_src_dir;
   4018     Buf resolved_root_src_dir = os_path_resolve(&pkg_root_src_dir, 1);
   4019 
   4020     Buf *namespace_name = buf_create_from_buf(&package->pkg_path);
   4021     if (source_kind == SourceKindNonRoot) {
   4022         assert(buf_starts_with_buf(resolved_path, &resolved_root_src_dir));
   4023         if (buf_len(namespace_name) != 0) {
   4024             buf_append_char(namespace_name, NAMESPACE_SEP_CHAR);
   4025         }
   4026         // The namespace components are obtained from the relative path to the
   4027         // source directory
   4028         if (buf_len(&noextname) > buf_len(&resolved_root_src_dir)) {
   4029             // Skip the trailing separator
   4030             buf_append_mem(namespace_name,
   4031                 buf_ptr(&noextname) + buf_len(&resolved_root_src_dir) + 1,
   4032                 buf_len(&noextname) - buf_len(&resolved_root_src_dir) - 1);
   4033         }
   4034         buf_replace(namespace_name, ZIG_OS_SEP_CHAR, NAMESPACE_SEP_CHAR);
   4035     }
   4036     Buf *bare_name = buf_alloc();
   4037     os_path_extname(src_basename, bare_name, nullptr);
   4038 
   4039     RootStruct *root_struct = allocate<RootStruct>(1);
   4040     root_struct->package = package;
   4041     root_struct->source_code = source_code;
   4042     root_struct->line_offsets = tokenization.line_offsets;
   4043     root_struct->path = resolved_path;
   4044     root_struct->di_file = ZigLLVMCreateFile(g->dbuilder, buf_ptr(src_basename), buf_ptr(src_dirname));
   4045     ZigType *import_entry = get_root_container_type(g, buf_ptr(namespace_name), bare_name, root_struct);
   4046     if (source_kind == SourceKindRoot) {
   4047         assert(g->root_import == nullptr);
   4048         g->root_import = import_entry;
   4049     }
   4050     g->import_table.put(resolved_path, import_entry);
   4051 
   4052     AstNode *root_node = ast_parse(source_code, tokenization.tokens, import_entry, g->err_color);
   4053     assert(root_node != nullptr);
   4054     assert(root_node->type == NodeTypeContainerDecl);
   4055     import_entry->data.structure.decl_node = root_node;
   4056     import_entry->data.structure.decls_scope->base.source_node = root_node;
   4057     if (g->verbose_ast) {
   4058         ast_print(stderr, root_node, 0);
   4059     }
   4060 
   4061     if (source_kind == SourceKindRoot || package == g->panic_package) {
   4062         // Look for panic and main
   4063         for (size_t decl_i = 0; decl_i < root_node->data.container_decl.decls.length; decl_i += 1) {
   4064             AstNode *top_level_decl = root_node->data.container_decl.decls.at(decl_i);
   4065 
   4066             if (top_level_decl->type == NodeTypeFnDef) {
   4067                 AstNode *proto_node = top_level_decl->data.fn_def.fn_proto;
   4068                 assert(proto_node->type == NodeTypeFnProto);
   4069                 Buf *proto_name = proto_node->data.fn_proto.name;
   4070 
   4071                 bool is_pub = (proto_node->data.fn_proto.visib_mod == VisibModPub);
   4072                 if (is_pub) {
   4073                     if (buf_eql_str(proto_name, "main")) {
   4074                         g->have_pub_main = true;
   4075                     } else if (buf_eql_str(proto_name, "panic")) {
   4076                         g->have_pub_panic = true;
   4077                     }
   4078                 }
   4079             }
   4080         }
   4081     }
   4082 
   4083     for (size_t decl_i = 0; decl_i < root_node->data.container_decl.decls.length; decl_i += 1) {
   4084         AstNode *top_level_decl = root_node->data.container_decl.decls.at(decl_i);
   4085         scan_decls(g, import_entry->data.structure.decls_scope, top_level_decl);
   4086     }
   4087 
   4088     TldContainer *tld_container = allocate<TldContainer>(1);
   4089     init_tld(&tld_container->base, TldIdContainer, namespace_name, VisibModPub, root_node, nullptr);
   4090     tld_container->type_entry = import_entry;
   4091     tld_container->decls_scope = import_entry->data.structure.decls_scope;
   4092     g->resolve_queue.append(&tld_container->base);
   4093 
   4094     return import_entry;
   4095 }
   4096 
   4097 void semantic_analyze(CodeGen *g) {
   4098     while (g->resolve_queue_index < g->resolve_queue.length ||
   4099            g->fn_defs_index < g->fn_defs.length)
   4100     {
   4101         for (; g->resolve_queue_index < g->resolve_queue.length; g->resolve_queue_index += 1) {
   4102             Tld *tld = g->resolve_queue.at(g->resolve_queue_index);
   4103             AstNode *source_node = nullptr;
   4104             resolve_top_level_decl(g, tld, source_node);
   4105         }
   4106 
   4107         for (; g->fn_defs_index < g->fn_defs.length; g->fn_defs_index += 1) {
   4108             ZigFn *fn_entry = g->fn_defs.at(g->fn_defs_index);
   4109             analyze_fn_body(g, fn_entry);
   4110         }
   4111     }
   4112 
   4113     if (g->errors.length != 0) {
   4114         return;
   4115     }
   4116 
   4117     // second pass over functions for detecting async
   4118     for (g->fn_defs_index = 0; g->fn_defs_index < g->fn_defs.length; g->fn_defs_index += 1) {
   4119         ZigFn *fn_entry = g->fn_defs.at(g->fn_defs_index);
   4120         analyze_fn_async(g, fn_entry);
   4121     }
   4122 }
   4123 
   4124 ZigType *get_int_type(CodeGen *g, bool is_signed, uint32_t size_in_bits) {
   4125     assert(size_in_bits <= 65535);
   4126     TypeId type_id = {};
   4127     type_id.id = ZigTypeIdInt;
   4128     type_id.data.integer.is_signed = is_signed;
   4129     type_id.data.integer.bit_count = size_in_bits;
   4130 
   4131     {
   4132         auto entry = g->type_table.maybe_get(type_id);
   4133         if (entry)
   4134             return entry->value;
   4135     }
   4136 
   4137     ZigType *new_entry = make_int_type(g, is_signed, size_in_bits);
   4138     g->type_table.put(type_id, new_entry);
   4139     return new_entry;
   4140 }
   4141 
   4142 bool is_valid_vector_elem_type(ZigType *elem_type) {
   4143     return elem_type->id == ZigTypeIdInt ||
   4144         elem_type->id == ZigTypeIdFloat ||
   4145         get_codegen_ptr_type(elem_type) != nullptr;
   4146 }
   4147 
   4148 ZigType *get_vector_type(CodeGen *g, uint32_t len, ZigType *elem_type) {
   4149     assert(is_valid_vector_elem_type(elem_type));
   4150 
   4151     TypeId type_id = {};
   4152     type_id.id = ZigTypeIdVector;
   4153     type_id.data.vector.len = len;
   4154     type_id.data.vector.elem_type = elem_type;
   4155 
   4156     {
   4157         auto entry = g->type_table.maybe_get(type_id);
   4158         if (entry)
   4159             return entry->value;
   4160     }
   4161 
   4162     ZigType *entry = new_type_table_entry(ZigTypeIdVector);
   4163     if ((len != 0) && type_has_bits(elem_type)) {
   4164         // Vectors can only be ints, floats, or pointers. ints and floats have trivially resolvable
   4165         // llvm type refs. pointers we will use usize instead.
   4166         LLVMTypeRef example_vector_llvm_type;
   4167         if (elem_type->id == ZigTypeIdPointer) {
   4168             example_vector_llvm_type = LLVMVectorType(g->builtin_types.entry_usize->llvm_type, len);
   4169         } else {
   4170             example_vector_llvm_type = LLVMVectorType(elem_type->llvm_type, len);
   4171         }
   4172         assert(example_vector_llvm_type != nullptr);
   4173         entry->size_in_bits = elem_type->size_in_bits * len;
   4174         entry->abi_size = LLVMABISizeOfType(g->target_data_ref, example_vector_llvm_type);
   4175         entry->abi_align = LLVMABIAlignmentOfType(g->target_data_ref, example_vector_llvm_type);
   4176     }
   4177     entry->data.vector.len = len;
   4178     entry->data.vector.elem_type = elem_type;
   4179 
   4180     buf_resize(&entry->name, 0);
   4181     buf_appendf(&entry->name, "@Vector(%u, %s)", len, buf_ptr(&elem_type->name));
   4182 
   4183     g->type_table.put(type_id, entry);
   4184     return entry;
   4185 }
   4186 
   4187 ZigType **get_c_int_type_ptr(CodeGen *g, CIntType c_int_type) {
   4188     return &g->builtin_types.entry_c_int[c_int_type];
   4189 }
   4190 
   4191 ZigType *get_c_int_type(CodeGen *g, CIntType c_int_type) {
   4192     return *get_c_int_type_ptr(g, c_int_type);
   4193 }
   4194 
   4195 bool handle_is_ptr(ZigType *type_entry) {
   4196     switch (type_entry->id) {
   4197         case ZigTypeIdInvalid:
   4198         case ZigTypeIdMetaType:
   4199         case ZigTypeIdComptimeFloat:
   4200         case ZigTypeIdComptimeInt:
   4201         case ZigTypeIdEnumLiteral:
   4202         case ZigTypeIdUndefined:
   4203         case ZigTypeIdNull:
   4204         case ZigTypeIdBoundFn:
   4205         case ZigTypeIdArgTuple:
   4206         case ZigTypeIdOpaque:
   4207              zig_unreachable();
   4208         case ZigTypeIdUnreachable:
   4209         case ZigTypeIdVoid:
   4210         case ZigTypeIdBool:
   4211         case ZigTypeIdInt:
   4212         case ZigTypeIdFloat:
   4213         case ZigTypeIdPointer:
   4214         case ZigTypeIdErrorSet:
   4215         case ZigTypeIdFn:
   4216         case ZigTypeIdEnum:
   4217         case ZigTypeIdVector:
   4218         case ZigTypeIdAnyFrame:
   4219              return false;
   4220         case ZigTypeIdArray:
   4221         case ZigTypeIdStruct:
   4222         case ZigTypeIdCoroFrame:
   4223              return type_has_bits(type_entry);
   4224         case ZigTypeIdErrorUnion:
   4225              return type_has_bits(type_entry->data.error_union.payload_type);
   4226         case ZigTypeIdOptional:
   4227              return type_has_bits(type_entry->data.maybe.child_type) &&
   4228                     !type_is_nonnull_ptr(type_entry->data.maybe.child_type) &&
   4229                     type_entry->data.maybe.child_type->id != ZigTypeIdErrorSet;
   4230         case ZigTypeIdUnion:
   4231              return type_has_bits(type_entry) && type_entry->data.unionation.gen_field_count != 0;
   4232 
   4233     }
   4234     zig_unreachable();
   4235 }
   4236 
   4237 static uint32_t hash_ptr(void *ptr) {
   4238     return (uint32_t)(((uintptr_t)ptr) % UINT32_MAX);
   4239 }
   4240 
   4241 static uint32_t hash_size(size_t x) {
   4242     return (uint32_t)(x % UINT32_MAX);
   4243 }
   4244 
   4245 uint32_t fn_table_entry_hash(ZigFn* value) {
   4246     return ptr_hash(value);
   4247 }
   4248 
   4249 bool fn_table_entry_eql(ZigFn *a, ZigFn *b) {
   4250     return ptr_eq(a, b);
   4251 }
   4252 
   4253 uint32_t fn_type_id_hash(FnTypeId *id) {
   4254     uint32_t result = 0;
   4255     result += ((uint32_t)(id->cc)) * (uint32_t)3349388391;
   4256     result += id->is_var_args ? (uint32_t)1931444534 : 0;
   4257     result += hash_ptr(id->return_type);
   4258     result += id->alignment * 0xd3b3f3e2;
   4259     for (size_t i = 0; i < id->param_count; i += 1) {
   4260         FnTypeParamInfo *info = &id->param_info[i];
   4261         result += info->is_noalias ? (uint32_t)892356923 : 0;
   4262         result += hash_ptr(info->type);
   4263     }
   4264     return result;
   4265 }
   4266 
   4267 bool fn_type_id_eql(FnTypeId *a, FnTypeId *b) {
   4268     if (a->cc != b->cc ||
   4269         a->return_type != b->return_type ||
   4270         a->is_var_args != b->is_var_args ||
   4271         a->param_count != b->param_count ||
   4272         a->alignment != b->alignment)
   4273     {
   4274         return false;
   4275     }
   4276     for (size_t i = 0; i < a->param_count; i += 1) {
   4277         FnTypeParamInfo *a_param_info = &a->param_info[i];
   4278         FnTypeParamInfo *b_param_info = &b->param_info[i];
   4279 
   4280         if (a_param_info->type != b_param_info->type ||
   4281             a_param_info->is_noalias != b_param_info->is_noalias)
   4282         {
   4283             return false;
   4284         }
   4285     }
   4286     return true;
   4287 }
   4288 
   4289 static uint32_t hash_const_val_error_set(ConstExprValue *const_val) {
   4290     assert(const_val->data.x_err_set != nullptr);
   4291     return const_val->data.x_err_set->value ^ 2630160122;
   4292 }
   4293 
   4294 static uint32_t hash_const_val_ptr(ConstExprValue *const_val) {
   4295     uint32_t hash_val = 0;
   4296     switch (const_val->data.x_ptr.mut) {
   4297         case ConstPtrMutRuntimeVar:
   4298             hash_val += (uint32_t)3500721036;
   4299             break;
   4300         case ConstPtrMutComptimeConst:
   4301             hash_val += (uint32_t)4214318515;
   4302             break;
   4303         case ConstPtrMutInfer:
   4304         case ConstPtrMutComptimeVar:
   4305             hash_val += (uint32_t)1103195694;
   4306             break;
   4307     }
   4308     switch (const_val->data.x_ptr.special) {
   4309         case ConstPtrSpecialInvalid:
   4310             zig_unreachable();
   4311         case ConstPtrSpecialRef:
   4312             hash_val += (uint32_t)2478261866;
   4313             hash_val += hash_ptr(const_val->data.x_ptr.data.ref.pointee);
   4314             return hash_val;
   4315         case ConstPtrSpecialBaseArray:
   4316             hash_val += (uint32_t)1764906839;
   4317             hash_val += hash_ptr(const_val->data.x_ptr.data.base_array.array_val);
   4318             hash_val += hash_size(const_val->data.x_ptr.data.base_array.elem_index);
   4319             hash_val += const_val->data.x_ptr.data.base_array.is_cstr ? 1297263887 : 200363492;
   4320             return hash_val;
   4321         case ConstPtrSpecialBaseStruct:
   4322             hash_val += (uint32_t)3518317043;
   4323             hash_val += hash_ptr(const_val->data.x_ptr.data.base_struct.struct_val);
   4324             hash_val += hash_size(const_val->data.x_ptr.data.base_struct.field_index);
   4325             return hash_val;
   4326         case ConstPtrSpecialBaseErrorUnionCode:
   4327             hash_val += (uint32_t)2994743799;
   4328             hash_val += hash_ptr(const_val->data.x_ptr.data.base_err_union_code.err_union_val);
   4329             return hash_val;
   4330         case ConstPtrSpecialBaseErrorUnionPayload:
   4331             hash_val += (uint32_t)3456080131;
   4332             hash_val += hash_ptr(const_val->data.x_ptr.data.base_err_union_payload.err_union_val);
   4333             return hash_val;
   4334         case ConstPtrSpecialBaseOptionalPayload:
   4335             hash_val += (uint32_t)3163140517;
   4336             hash_val += hash_ptr(const_val->data.x_ptr.data.base_optional_payload.optional_val);
   4337             return hash_val;
   4338         case ConstPtrSpecialHardCodedAddr:
   4339             hash_val += (uint32_t)4048518294;
   4340             hash_val += hash_size(const_val->data.x_ptr.data.hard_coded_addr.addr);
   4341             return hash_val;
   4342         case ConstPtrSpecialDiscard:
   4343             hash_val += 2010123162;
   4344             return hash_val;
   4345         case ConstPtrSpecialFunction:
   4346             hash_val += (uint32_t)2590901619;
   4347             hash_val += hash_ptr(const_val->data.x_ptr.data.fn.fn_entry);
   4348             return hash_val;
   4349         case ConstPtrSpecialNull:
   4350             hash_val += (uint32_t)1486246455;
   4351             return hash_val;
   4352     }
   4353     zig_unreachable();
   4354 }
   4355 
   4356 static uint32_t hash_const_val(ConstExprValue *const_val) {
   4357     assert(const_val->special == ConstValSpecialStatic);
   4358     switch (const_val->type->id) {
   4359         case ZigTypeIdOpaque:
   4360             zig_unreachable();
   4361         case ZigTypeIdBool:
   4362             return const_val->data.x_bool ? (uint32_t)127863866 : (uint32_t)215080464;
   4363         case ZigTypeIdMetaType:
   4364             return hash_ptr(const_val->data.x_type);
   4365         case ZigTypeIdVoid:
   4366             return (uint32_t)4149439618;
   4367         case ZigTypeIdInt:
   4368         case ZigTypeIdComptimeInt:
   4369             {
   4370                 uint32_t result = 1331471175;
   4371                 for (size_t i = 0; i < const_val->data.x_bigint.digit_count; i += 1) {
   4372                     uint64_t digit = bigint_ptr(&const_val->data.x_bigint)[i];
   4373                     result ^= ((uint32_t)(digit >> 32)) ^ (uint32_t)(result);
   4374                 }
   4375                 return result;
   4376             }
   4377         case ZigTypeIdEnumLiteral:
   4378             return buf_hash(const_val->data.x_enum_literal) * 2691276464;
   4379         case ZigTypeIdEnum:
   4380             {
   4381                 uint32_t result = 31643936;
   4382                 for (size_t i = 0; i < const_val->data.x_enum_tag.digit_count; i += 1) {
   4383                     uint64_t digit = bigint_ptr(&const_val->data.x_enum_tag)[i];
   4384                     result ^= ((uint32_t)(digit >> 32)) ^ (uint32_t)(result);
   4385                 }
   4386                 return result;
   4387             }
   4388         case ZigTypeIdFloat:
   4389             switch (const_val->type->data.floating.bit_count) {
   4390                 case 16:
   4391                     {
   4392                         uint16_t result;
   4393                         static_assert(sizeof(result) == sizeof(const_val->data.x_f16), "");
   4394                         memcpy(&result, &const_val->data.x_f16, sizeof(result));
   4395                         return result * 65537u;
   4396                     }
   4397                 case 32:
   4398                     {
   4399                         uint32_t result;
   4400                         memcpy(&result, &const_val->data.x_f32, 4);
   4401                         return result ^ 4084870010;
   4402                     }
   4403                 case 64:
   4404                     {
   4405                         uint32_t ints[2];
   4406                         memcpy(&ints[0], &const_val->data.x_f64, 8);
   4407                         return ints[0] ^ ints[1] ^ 0x22ed43c6;
   4408                     }
   4409                 case 128:
   4410                     {
   4411                         uint32_t ints[4];
   4412                         memcpy(&ints[0], &const_val->data.x_f128, 16);
   4413                         return ints[0] ^ ints[1] ^ ints[2] ^ ints[3] ^ 0xb5ffef27;
   4414                     }
   4415                 default:
   4416                     zig_unreachable();
   4417             }
   4418         case ZigTypeIdComptimeFloat:
   4419             {
   4420                 float128_t f128 = bigfloat_to_f128(&const_val->data.x_bigfloat);
   4421                 uint32_t ints[4];
   4422                 memcpy(&ints[0], &f128, 16);
   4423                 return ints[0] ^ ints[1] ^ ints[2] ^ ints[3] ^ 0xed8b3dfb;
   4424             }
   4425         case ZigTypeIdArgTuple:
   4426             return (uint32_t)const_val->data.x_arg_tuple.start_index * (uint32_t)281907309 +
   4427                 (uint32_t)const_val->data.x_arg_tuple.end_index * (uint32_t)2290442768;
   4428         case ZigTypeIdFn:
   4429             assert(const_val->data.x_ptr.mut == ConstPtrMutComptimeConst);
   4430             assert(const_val->data.x_ptr.special == ConstPtrSpecialFunction);
   4431             return 3677364617 ^ hash_ptr(const_val->data.x_ptr.data.fn.fn_entry);
   4432         case ZigTypeIdPointer:
   4433             return hash_const_val_ptr(const_val);
   4434         case ZigTypeIdUndefined:
   4435             return 162837799;
   4436         case ZigTypeIdNull:
   4437             return 844854567;
   4438         case ZigTypeIdArray:
   4439             // TODO better hashing algorithm
   4440             return 1166190605;
   4441         case ZigTypeIdStruct:
   4442             // TODO better hashing algorithm
   4443             return 1532530855;
   4444         case ZigTypeIdUnion:
   4445             // TODO better hashing algorithm
   4446             return 2709806591;
   4447         case ZigTypeIdOptional:
   4448             if (get_codegen_ptr_type(const_val->type) != nullptr) {
   4449                 return hash_const_val_ptr(const_val) * 1992916303;
   4450             } else if (const_val->type->data.maybe.child_type->id == ZigTypeIdErrorSet) {
   4451                 return hash_const_val_error_set(const_val) * 3147031929;
   4452             } else {
   4453                 if (const_val->data.x_optional) {
   4454                     return hash_const_val(const_val->data.x_optional) * 1992916303;
   4455                 } else {
   4456                     return 4016830364;
   4457                 }
   4458             }
   4459         case ZigTypeIdErrorUnion:
   4460             // TODO better hashing algorithm
   4461             return 3415065496;
   4462         case ZigTypeIdErrorSet:
   4463             return hash_const_val_error_set(const_val);
   4464         case ZigTypeIdVector:
   4465             // TODO better hashing algorithm
   4466             return 3647867726;
   4467         case ZigTypeIdCoroFrame:
   4468             // TODO better hashing algorithm
   4469             return 675741936;
   4470         case ZigTypeIdAnyFrame:
   4471             // TODO better hashing algorithm
   4472             return 3747294894;
   4473         case ZigTypeIdBoundFn:
   4474         case ZigTypeIdInvalid:
   4475         case ZigTypeIdUnreachable:
   4476             zig_unreachable();
   4477     }
   4478     zig_unreachable();
   4479 }
   4480 
   4481 uint32_t generic_fn_type_id_hash(GenericFnTypeId *id) {
   4482     uint32_t result = 0;
   4483     result += hash_ptr(id->fn_entry);
   4484     for (size_t i = 0; i < id->param_count; i += 1) {
   4485         ConstExprValue *generic_param = &id->params[i];
   4486         if (generic_param->special != ConstValSpecialRuntime) {
   4487             result += hash_const_val(generic_param);
   4488             result += hash_ptr(generic_param->type);
   4489         }
   4490     }
   4491     return result;
   4492 }
   4493 
   4494 bool generic_fn_type_id_eql(GenericFnTypeId *a, GenericFnTypeId *b) {
   4495     assert(a->fn_entry);
   4496     if (a->fn_entry != b->fn_entry) return false;
   4497     if (a->param_count != b->param_count) return false;
   4498     for (size_t i = 0; i < a->param_count; i += 1) {
   4499         ConstExprValue *a_val = &a->params[i];
   4500         ConstExprValue *b_val = &b->params[i];
   4501         if (a_val->type != b_val->type) return false;
   4502         if (a_val->special != ConstValSpecialRuntime && b_val->special != ConstValSpecialRuntime) {
   4503             assert(a_val->special == ConstValSpecialStatic);
   4504             assert(b_val->special == ConstValSpecialStatic);
   4505             if (!const_values_equal(a->codegen, a_val, b_val)) {
   4506                 return false;
   4507             }
   4508         } else {
   4509             assert(a_val->special == ConstValSpecialRuntime && b_val->special == ConstValSpecialRuntime);
   4510         }
   4511     }
   4512     return true;
   4513 }
   4514 
   4515 static bool can_mutate_comptime_var_state(ConstExprValue *value) {
   4516     assert(value != nullptr);
   4517     switch (value->type->id) {
   4518         case ZigTypeIdInvalid:
   4519             zig_unreachable();
   4520         case ZigTypeIdMetaType:
   4521         case ZigTypeIdVoid:
   4522         case ZigTypeIdBool:
   4523         case ZigTypeIdUnreachable:
   4524         case ZigTypeIdInt:
   4525         case ZigTypeIdVector:
   4526         case ZigTypeIdFloat:
   4527         case ZigTypeIdComptimeFloat:
   4528         case ZigTypeIdComptimeInt:
   4529         case ZigTypeIdEnumLiteral:
   4530         case ZigTypeIdUndefined:
   4531         case ZigTypeIdNull:
   4532         case ZigTypeIdBoundFn:
   4533         case ZigTypeIdFn:
   4534         case ZigTypeIdOpaque:
   4535         case ZigTypeIdErrorSet:
   4536         case ZigTypeIdEnum:
   4537         case ZigTypeIdCoroFrame:
   4538         case ZigTypeIdAnyFrame:
   4539             return false;
   4540 
   4541         case ZigTypeIdPointer:
   4542             return value->data.x_ptr.mut == ConstPtrMutComptimeVar;
   4543 
   4544         case ZigTypeIdArray:
   4545             if (value->type->data.array.len == 0)
   4546                 return false;
   4547             switch (value->data.x_array.special) {
   4548                 case ConstArraySpecialUndef:
   4549                 case ConstArraySpecialBuf:
   4550                     return false;
   4551                 case ConstArraySpecialNone:
   4552                     for (uint32_t i = 0; i < value->type->data.array.len; i += 1) {
   4553                         if (can_mutate_comptime_var_state(&value->data.x_array.data.s_none.elements[i]))
   4554                             return true;
   4555                     }
   4556                     return false;
   4557             }
   4558             zig_unreachable();
   4559         case ZigTypeIdStruct:
   4560             for (uint32_t i = 0; i < value->type->data.structure.src_field_count; i += 1) {
   4561                 if (can_mutate_comptime_var_state(&value->data.x_struct.fields[i]))
   4562                     return true;
   4563             }
   4564             return false;
   4565 
   4566         case ZigTypeIdOptional:
   4567             if (get_codegen_ptr_type(value->type) != nullptr)
   4568                 return value->data.x_ptr.mut == ConstPtrMutComptimeVar;
   4569             if (value->data.x_optional == nullptr)
   4570                 return false;
   4571             return can_mutate_comptime_var_state(value->data.x_optional);
   4572 
   4573         case ZigTypeIdErrorUnion:
   4574             if (value->data.x_err_union.error_set->data.x_err_set != nullptr)
   4575                 return false;
   4576             assert(value->data.x_err_union.payload != nullptr);
   4577             return can_mutate_comptime_var_state(value->data.x_err_union.payload);
   4578 
   4579         case ZigTypeIdUnion:
   4580             return can_mutate_comptime_var_state(value->data.x_union.payload);
   4581 
   4582         case ZigTypeIdArgTuple:
   4583             zig_panic("TODO var args at comptime is currently not supported");
   4584     }
   4585     zig_unreachable();
   4586 }
   4587 
   4588 static bool return_type_is_cacheable(ZigType *return_type) {
   4589     switch (return_type->id) {
   4590         case ZigTypeIdInvalid:
   4591             zig_unreachable();
   4592         case ZigTypeIdMetaType:
   4593         case ZigTypeIdVoid:
   4594         case ZigTypeIdBool:
   4595         case ZigTypeIdUnreachable:
   4596         case ZigTypeIdInt:
   4597         case ZigTypeIdFloat:
   4598         case ZigTypeIdComptimeFloat:
   4599         case ZigTypeIdComptimeInt:
   4600         case ZigTypeIdEnumLiteral:
   4601         case ZigTypeIdUndefined:
   4602         case ZigTypeIdNull:
   4603         case ZigTypeIdBoundFn:
   4604         case ZigTypeIdFn:
   4605         case ZigTypeIdOpaque:
   4606         case ZigTypeIdErrorSet:
   4607         case ZigTypeIdEnum:
   4608         case ZigTypeIdPointer:
   4609         case ZigTypeIdVector:
   4610         case ZigTypeIdCoroFrame:
   4611         case ZigTypeIdAnyFrame:
   4612             return true;
   4613 
   4614         case ZigTypeIdArray:
   4615         case ZigTypeIdStruct:
   4616         case ZigTypeIdUnion:
   4617             return false;
   4618 
   4619         case ZigTypeIdOptional:
   4620             return return_type_is_cacheable(return_type->data.maybe.child_type);
   4621 
   4622         case ZigTypeIdErrorUnion:
   4623             return return_type_is_cacheable(return_type->data.error_union.payload_type);
   4624 
   4625         case ZigTypeIdArgTuple:
   4626             zig_panic("TODO var args at comptime is currently not supported");
   4627     }
   4628     zig_unreachable();
   4629 }
   4630 
   4631 bool fn_eval_cacheable(Scope *scope, ZigType *return_type) {
   4632     if (!return_type_is_cacheable(return_type))
   4633         return false;
   4634     while (scope) {
   4635         if (scope->id == ScopeIdVarDecl) {
   4636             ScopeVarDecl *var_scope = (ScopeVarDecl *)scope;
   4637             if (type_is_invalid(var_scope->var->var_type))
   4638                 return false;
   4639             if (var_scope->var->const_value->special == ConstValSpecialUndef)
   4640                 return false;
   4641             if (can_mutate_comptime_var_state(var_scope->var->const_value))
   4642                 return false;
   4643         } else if (scope->id == ScopeIdFnDef) {
   4644             return true;
   4645         } else {
   4646             zig_unreachable();
   4647         }
   4648 
   4649         scope = scope->parent;
   4650     }
   4651     zig_unreachable();
   4652 }
   4653 
   4654 uint32_t fn_eval_hash(Scope* scope) {
   4655     uint32_t result = 0;
   4656     while (scope) {
   4657         if (scope->id == ScopeIdVarDecl) {
   4658             ScopeVarDecl *var_scope = (ScopeVarDecl *)scope;
   4659             result += hash_const_val(var_scope->var->const_value);
   4660         } else if (scope->id == ScopeIdFnDef) {
   4661             ScopeFnDef *fn_scope = (ScopeFnDef *)scope;
   4662             result += hash_ptr(fn_scope->fn_entry);
   4663             return result;
   4664         } else {
   4665             zig_unreachable();
   4666         }
   4667 
   4668         scope = scope->parent;
   4669     }
   4670     zig_unreachable();
   4671 }
   4672 
   4673 bool fn_eval_eql(Scope *a, Scope *b) {
   4674     assert(a->codegen != nullptr);
   4675     assert(b->codegen != nullptr);
   4676     while (a && b) {
   4677         if (a->id != b->id)
   4678             return false;
   4679 
   4680         if (a->id == ScopeIdVarDecl) {
   4681             ScopeVarDecl *a_var_scope = (ScopeVarDecl *)a;
   4682             ScopeVarDecl *b_var_scope = (ScopeVarDecl *)b;
   4683             if (a_var_scope->var->var_type != b_var_scope->var->var_type)
   4684                 return false;
   4685             if (a_var_scope->var->var_type == a_var_scope->var->const_value->type &&
   4686                 b_var_scope->var->var_type == b_var_scope->var->const_value->type)
   4687             {
   4688                 if (!const_values_equal(a->codegen, a_var_scope->var->const_value, b_var_scope->var->const_value))
   4689                     return false;
   4690             } else {
   4691                 zig_panic("TODO comptime ptr reinterpret for fn_eval_eql");
   4692             }
   4693         } else if (a->id == ScopeIdFnDef) {
   4694             ScopeFnDef *a_fn_scope = (ScopeFnDef *)a;
   4695             ScopeFnDef *b_fn_scope = (ScopeFnDef *)b;
   4696             if (a_fn_scope->fn_entry != b_fn_scope->fn_entry)
   4697                 return false;
   4698 
   4699             return true;
   4700         } else {
   4701             zig_unreachable();
   4702         }
   4703 
   4704         a = a->parent;
   4705         b = b->parent;
   4706     }
   4707     return false;
   4708 }
   4709 
   4710 // Whether the type has bits at runtime.
   4711 bool type_has_bits(ZigType *type_entry) {
   4712     assert(type_entry != nullptr);
   4713     assert(!type_is_invalid(type_entry));
   4714     assert(type_is_resolved(type_entry, ResolveStatusZeroBitsKnown));
   4715     return type_entry->abi_size != 0;
   4716 }
   4717 
   4718 // Whether you can infer the value based solely on the type.
   4719 OnePossibleValue type_has_one_possible_value(CodeGen *g, ZigType *type_entry) {
   4720     assert(type_entry != nullptr);
   4721 
   4722     if (type_entry->one_possible_value != OnePossibleValueInvalid)
   4723         return type_entry->one_possible_value;
   4724 
   4725     Error err;
   4726     if ((err = type_resolve(g, type_entry, ResolveStatusZeroBitsKnown)))
   4727         return OnePossibleValueInvalid;
   4728     switch (type_entry->id) {
   4729         case ZigTypeIdInvalid:
   4730             zig_unreachable();
   4731         case ZigTypeIdOpaque:
   4732         case ZigTypeIdComptimeFloat:
   4733         case ZigTypeIdComptimeInt:
   4734         case ZigTypeIdEnumLiteral:
   4735         case ZigTypeIdMetaType:
   4736         case ZigTypeIdBoundFn:
   4737         case ZigTypeIdArgTuple:
   4738         case ZigTypeIdOptional:
   4739         case ZigTypeIdFn:
   4740         case ZigTypeIdBool:
   4741         case ZigTypeIdFloat:
   4742         case ZigTypeIdErrorUnion:
   4743         case ZigTypeIdCoroFrame:
   4744         case ZigTypeIdAnyFrame:
   4745             return OnePossibleValueNo;
   4746         case ZigTypeIdUndefined:
   4747         case ZigTypeIdNull:
   4748         case ZigTypeIdVoid:
   4749         case ZigTypeIdUnreachable:
   4750             return OnePossibleValueYes;
   4751         case ZigTypeIdArray:
   4752             if (type_entry->data.array.len == 0)
   4753                 return OnePossibleValueYes;
   4754             return type_has_one_possible_value(g, type_entry->data.array.child_type);
   4755         case ZigTypeIdStruct:
   4756             for (size_t i = 0; i < type_entry->data.structure.src_field_count; i += 1) {
   4757                 TypeStructField *field = &type_entry->data.structure.fields[i];
   4758                 switch (type_has_one_possible_value(g, field->type_entry)) {
   4759                     case OnePossibleValueInvalid:
   4760                         return OnePossibleValueInvalid;
   4761                     case OnePossibleValueNo:
   4762                         return OnePossibleValueNo;
   4763                     case OnePossibleValueYes:
   4764                         continue;
   4765                 }
   4766             }
   4767             return OnePossibleValueYes;
   4768         case ZigTypeIdErrorSet:
   4769         case ZigTypeIdEnum:
   4770         case ZigTypeIdInt:
   4771         case ZigTypeIdVector:
   4772             return type_has_bits(type_entry) ? OnePossibleValueNo : OnePossibleValueYes;
   4773         case ZigTypeIdPointer: {
   4774             ZigType *elem_type = type_entry->data.pointer.child_type;
   4775             // If the recursive function call asks, then we are not one possible value.
   4776             type_entry->one_possible_value = OnePossibleValueNo;
   4777             // Now update it to be the value of the recursive call.
   4778             type_entry->one_possible_value = type_has_one_possible_value(g, elem_type);
   4779             return type_entry->one_possible_value;
   4780         }
   4781         case ZigTypeIdUnion:
   4782             if (type_entry->data.unionation.src_field_count > 1)
   4783                 return OnePossibleValueNo;
   4784             return type_has_one_possible_value(g, type_entry->data.unionation.fields[0].type_entry);
   4785     }
   4786     zig_unreachable();
   4787 }
   4788 
   4789 ReqCompTime type_requires_comptime(CodeGen *g, ZigType *type_entry) {
   4790     Error err;
   4791     if ((err = type_resolve(g, type_entry, ResolveStatusZeroBitsKnown)))
   4792         return ReqCompTimeInvalid;
   4793     switch (type_entry->id) {
   4794         case ZigTypeIdInvalid:
   4795         case ZigTypeIdOpaque:
   4796             zig_unreachable();
   4797         case ZigTypeIdComptimeFloat:
   4798         case ZigTypeIdComptimeInt:
   4799         case ZigTypeIdEnumLiteral:
   4800         case ZigTypeIdUndefined:
   4801         case ZigTypeIdNull:
   4802         case ZigTypeIdMetaType:
   4803         case ZigTypeIdBoundFn:
   4804         case ZigTypeIdArgTuple:
   4805             return ReqCompTimeYes;
   4806         case ZigTypeIdArray:
   4807             return type_requires_comptime(g, type_entry->data.array.child_type);
   4808         case ZigTypeIdStruct:
   4809             return type_entry->data.structure.requires_comptime ? ReqCompTimeYes : ReqCompTimeNo;
   4810         case ZigTypeIdUnion:
   4811             return type_entry->data.unionation.requires_comptime ? ReqCompTimeYes : ReqCompTimeNo;
   4812         case ZigTypeIdOptional:
   4813             return type_requires_comptime(g, type_entry->data.maybe.child_type);
   4814         case ZigTypeIdErrorUnion:
   4815             return type_requires_comptime(g, type_entry->data.error_union.payload_type);
   4816         case ZigTypeIdPointer:
   4817             if (type_entry->data.pointer.child_type->id == ZigTypeIdOpaque) {
   4818                 return ReqCompTimeNo;
   4819             } else {
   4820                 return type_requires_comptime(g, type_entry->data.pointer.child_type);
   4821             }
   4822         case ZigTypeIdFn:
   4823             return type_entry->data.fn.is_generic ? ReqCompTimeYes : ReqCompTimeNo;
   4824         case ZigTypeIdEnum:
   4825         case ZigTypeIdErrorSet:
   4826         case ZigTypeIdBool:
   4827         case ZigTypeIdInt:
   4828         case ZigTypeIdVector:
   4829         case ZigTypeIdFloat:
   4830         case ZigTypeIdVoid:
   4831         case ZigTypeIdUnreachable:
   4832         case ZigTypeIdCoroFrame:
   4833         case ZigTypeIdAnyFrame:
   4834             return ReqCompTimeNo;
   4835     }
   4836     zig_unreachable();
   4837 }
   4838 
   4839 void init_const_str_lit(CodeGen *g, ConstExprValue *const_val, Buf *str) {
   4840     auto entry = g->string_literals_table.maybe_get(str);
   4841     if (entry != nullptr) {
   4842         memcpy(const_val, entry->value, sizeof(ConstExprValue));
   4843         return;
   4844     }
   4845 
   4846     const_val->special = ConstValSpecialStatic;
   4847     const_val->type = get_array_type(g, g->builtin_types.entry_u8, buf_len(str));
   4848     const_val->data.x_array.special = ConstArraySpecialBuf;
   4849     const_val->data.x_array.data.s_buf = str;
   4850 
   4851     g->string_literals_table.put(str, const_val);
   4852 }
   4853 
   4854 ConstExprValue *create_const_str_lit(CodeGen *g, Buf *str) {
   4855     ConstExprValue *const_val = create_const_vals(1);
   4856     init_const_str_lit(g, const_val, str);
   4857     return const_val;
   4858 }
   4859 
   4860 void init_const_c_str_lit(CodeGen *g, ConstExprValue *const_val, Buf *str) {
   4861     // first we build the underlying array
   4862     size_t len_with_null = buf_len(str) + 1;
   4863     ConstExprValue *array_val = create_const_vals(1);
   4864     array_val->special = ConstValSpecialStatic;
   4865     array_val->type = get_array_type(g, g->builtin_types.entry_u8, len_with_null);
   4866     // TODO buf optimization
   4867     array_val->data.x_array.data.s_none.elements = create_const_vals(len_with_null);
   4868     for (size_t i = 0; i < buf_len(str); i += 1) {
   4869         ConstExprValue *this_char = &array_val->data.x_array.data.s_none.elements[i];
   4870         this_char->special = ConstValSpecialStatic;
   4871         this_char->type = g->builtin_types.entry_u8;
   4872         bigint_init_unsigned(&this_char->data.x_bigint, (uint8_t)buf_ptr(str)[i]);
   4873     }
   4874     ConstExprValue *null_char = &array_val->data.x_array.data.s_none.elements[len_with_null - 1];
   4875     null_char->special = ConstValSpecialStatic;
   4876     null_char->type = g->builtin_types.entry_u8;
   4877     bigint_init_unsigned(&null_char->data.x_bigint, 0);
   4878 
   4879     // then make the pointer point to it
   4880     const_val->special = ConstValSpecialStatic;
   4881     // TODO make this `[*]null u8` instead of `[*]u8`
   4882     const_val->type = get_pointer_to_type_extra(g, g->builtin_types.entry_u8, true, false,
   4883             PtrLenUnknown, 0, 0, 0, false);
   4884     const_val->data.x_ptr.special = ConstPtrSpecialBaseArray;
   4885     const_val->data.x_ptr.data.base_array.array_val = array_val;
   4886     const_val->data.x_ptr.data.base_array.elem_index = 0;
   4887     const_val->data.x_ptr.data.base_array.is_cstr = true;
   4888 }
   4889 ConstExprValue *create_const_c_str_lit(CodeGen *g, Buf *str) {
   4890     ConstExprValue *const_val = create_const_vals(1);
   4891     init_const_c_str_lit(g, const_val, str);
   4892     return const_val;
   4893 }
   4894 
   4895 void init_const_bigint(ConstExprValue *const_val, ZigType *type, const BigInt *bigint) {
   4896     const_val->special = ConstValSpecialStatic;
   4897     const_val->type = type;
   4898     bigint_init_bigint(&const_val->data.x_bigint, bigint);
   4899 }
   4900 
   4901 ConstExprValue *create_const_bigint(ZigType *type, const BigInt *bigint) {
   4902     ConstExprValue *const_val = create_const_vals(1);
   4903     init_const_bigint(const_val, type, bigint);
   4904     return const_val;
   4905 }
   4906 
   4907 
   4908 void init_const_unsigned_negative(ConstExprValue *const_val, ZigType *type, uint64_t x, bool negative) {
   4909     const_val->special = ConstValSpecialStatic;
   4910     const_val->type = type;
   4911     bigint_init_unsigned(&const_val->data.x_bigint, x);
   4912     const_val->data.x_bigint.is_negative = negative;
   4913 }
   4914 
   4915 ConstExprValue *create_const_unsigned_negative(ZigType *type, uint64_t x, bool negative) {
   4916     ConstExprValue *const_val = create_const_vals(1);
   4917     init_const_unsigned_negative(const_val, type, x, negative);
   4918     return const_val;
   4919 }
   4920 
   4921 void init_const_usize(CodeGen *g, ConstExprValue *const_val, uint64_t x) {
   4922     return init_const_unsigned_negative(const_val, g->builtin_types.entry_usize, x, false);
   4923 }
   4924 
   4925 ConstExprValue *create_const_usize(CodeGen *g, uint64_t x) {
   4926     return create_const_unsigned_negative(g->builtin_types.entry_usize, x, false);
   4927 }
   4928 
   4929 void init_const_signed(ConstExprValue *const_val, ZigType *type, int64_t x) {
   4930     const_val->special = ConstValSpecialStatic;
   4931     const_val->type = type;
   4932     bigint_init_signed(&const_val->data.x_bigint, x);
   4933 }
   4934 
   4935 ConstExprValue *create_const_signed(ZigType *type, int64_t x) {
   4936     ConstExprValue *const_val = create_const_vals(1);
   4937     init_const_signed(const_val, type, x);
   4938     return const_val;
   4939 }
   4940 
   4941 void init_const_float(ConstExprValue *const_val, ZigType *type, double value) {
   4942     const_val->special = ConstValSpecialStatic;
   4943     const_val->type = type;
   4944     if (type->id == ZigTypeIdComptimeFloat) {
   4945         bigfloat_init_64(&const_val->data.x_bigfloat, value);
   4946     } else if (type->id == ZigTypeIdFloat) {
   4947         switch (type->data.floating.bit_count) {
   4948             case 16:
   4949                 const_val->data.x_f16 = zig_double_to_f16(value);
   4950                 break;
   4951             case 32:
   4952                 const_val->data.x_f32 = value;
   4953                 break;
   4954             case 64:
   4955                 const_val->data.x_f64 = value;
   4956                 break;
   4957             case 128:
   4958                 // if we need this, we should add a function that accepts a float128_t param
   4959                 zig_unreachable();
   4960             default:
   4961                 zig_unreachable();
   4962         }
   4963     } else {
   4964         zig_unreachable();
   4965     }
   4966 }
   4967 
   4968 ConstExprValue *create_const_float(ZigType *type, double value) {
   4969     ConstExprValue *const_val = create_const_vals(1);
   4970     init_const_float(const_val, type, value);
   4971     return const_val;
   4972 }
   4973 
   4974 void init_const_enum(ConstExprValue *const_val, ZigType *type, const BigInt *tag) {
   4975     const_val->special = ConstValSpecialStatic;
   4976     const_val->type = type;
   4977     bigint_init_bigint(&const_val->data.x_enum_tag, tag);
   4978 }
   4979 
   4980 ConstExprValue *create_const_enum(ZigType *type, const BigInt *tag) {
   4981     ConstExprValue *const_val = create_const_vals(1);
   4982     init_const_enum(const_val, type, tag);
   4983     return const_val;
   4984 }
   4985 
   4986 
   4987 void init_const_bool(CodeGen *g, ConstExprValue *const_val, bool value) {
   4988     const_val->special = ConstValSpecialStatic;
   4989     const_val->type = g->builtin_types.entry_bool;
   4990     const_val->data.x_bool = value;
   4991 }
   4992 
   4993 ConstExprValue *create_const_bool(CodeGen *g, bool value) {
   4994     ConstExprValue *const_val = create_const_vals(1);
   4995     init_const_bool(g, const_val, value);
   4996     return const_val;
   4997 }
   4998 
   4999 void init_const_runtime(ConstExprValue *const_val, ZigType *type) {
   5000     const_val->special = ConstValSpecialRuntime;
   5001     const_val->type = type;
   5002 }
   5003 
   5004 ConstExprValue *create_const_runtime(ZigType *type) {
   5005     ConstExprValue *const_val = create_const_vals(1);
   5006     init_const_runtime(const_val, type);
   5007     return const_val;
   5008 }
   5009 
   5010 void init_const_type(CodeGen *g, ConstExprValue *const_val, ZigType *type_value) {
   5011     const_val->special = ConstValSpecialStatic;
   5012     const_val->type = g->builtin_types.entry_type;
   5013     const_val->data.x_type = type_value;
   5014 }
   5015 
   5016 ConstExprValue *create_const_type(CodeGen *g, ZigType *type_value) {
   5017     ConstExprValue *const_val = create_const_vals(1);
   5018     init_const_type(g, const_val, type_value);
   5019     return const_val;
   5020 }
   5021 
   5022 void init_const_slice(CodeGen *g, ConstExprValue *const_val, ConstExprValue *array_val,
   5023         size_t start, size_t len, bool is_const)
   5024 {
   5025     assert(array_val->type->id == ZigTypeIdArray);
   5026 
   5027     ZigType *ptr_type = get_pointer_to_type_extra(g, array_val->type->data.array.child_type,
   5028             is_const, false, PtrLenUnknown, 0, 0, 0, false);
   5029 
   5030     const_val->special = ConstValSpecialStatic;
   5031     const_val->type = get_slice_type(g, ptr_type);
   5032     const_val->data.x_struct.fields = create_const_vals(2);
   5033 
   5034     init_const_ptr_array(g, &const_val->data.x_struct.fields[slice_ptr_index], array_val, start, is_const,
   5035             PtrLenUnknown);
   5036     init_const_usize(g, &const_val->data.x_struct.fields[slice_len_index], len);
   5037 }
   5038 
   5039 ConstExprValue *create_const_slice(CodeGen *g, ConstExprValue *array_val, size_t start, size_t len, bool is_const) {
   5040     ConstExprValue *const_val = create_const_vals(1);
   5041     init_const_slice(g, const_val, array_val, start, len, is_const);
   5042     return const_val;
   5043 }
   5044 
   5045 void init_const_ptr_array(CodeGen *g, ConstExprValue *const_val, ConstExprValue *array_val,
   5046         size_t elem_index, bool is_const, PtrLen ptr_len)
   5047 {
   5048     assert(array_val->type->id == ZigTypeIdArray);
   5049     ZigType *child_type = array_val->type->data.array.child_type;
   5050 
   5051     const_val->special = ConstValSpecialStatic;
   5052     const_val->type = get_pointer_to_type_extra(g, child_type, is_const, false,
   5053             ptr_len, 0, 0, 0, false);
   5054     const_val->data.x_ptr.special = ConstPtrSpecialBaseArray;
   5055     const_val->data.x_ptr.data.base_array.array_val = array_val;
   5056     const_val->data.x_ptr.data.base_array.elem_index = elem_index;
   5057 }
   5058 
   5059 ConstExprValue *create_const_ptr_array(CodeGen *g, ConstExprValue *array_val, size_t elem_index, bool is_const,
   5060         PtrLen ptr_len)
   5061 {
   5062     ConstExprValue *const_val = create_const_vals(1);
   5063     init_const_ptr_array(g, const_val, array_val, elem_index, is_const, ptr_len);
   5064     return const_val;
   5065 }
   5066 
   5067 void init_const_ptr_ref(CodeGen *g, ConstExprValue *const_val, ConstExprValue *pointee_val, bool is_const) {
   5068     const_val->special = ConstValSpecialStatic;
   5069     const_val->type = get_pointer_to_type(g, pointee_val->type, is_const);
   5070     const_val->data.x_ptr.special = ConstPtrSpecialRef;
   5071     const_val->data.x_ptr.data.ref.pointee = pointee_val;
   5072 }
   5073 
   5074 ConstExprValue *create_const_ptr_ref(CodeGen *g, ConstExprValue *pointee_val, bool is_const) {
   5075     ConstExprValue *const_val = create_const_vals(1);
   5076     init_const_ptr_ref(g, const_val, pointee_val, is_const);
   5077     return const_val;
   5078 }
   5079 
   5080 void init_const_ptr_hard_coded_addr(CodeGen *g, ConstExprValue *const_val, ZigType *pointee_type,
   5081         size_t addr, bool is_const)
   5082 {
   5083     const_val->special = ConstValSpecialStatic;
   5084     const_val->type = get_pointer_to_type(g, pointee_type, is_const);
   5085     const_val->data.x_ptr.special = ConstPtrSpecialHardCodedAddr;
   5086     const_val->data.x_ptr.data.hard_coded_addr.addr = addr;
   5087 }
   5088 
   5089 ConstExprValue *create_const_ptr_hard_coded_addr(CodeGen *g, ZigType *pointee_type,
   5090         size_t addr, bool is_const)
   5091 {
   5092     ConstExprValue *const_val = create_const_vals(1);
   5093     init_const_ptr_hard_coded_addr(g, const_val, pointee_type, addr, is_const);
   5094     return const_val;
   5095 }
   5096 
   5097 void init_const_arg_tuple(CodeGen *g, ConstExprValue *const_val, size_t arg_index_start, size_t arg_index_end) {
   5098     const_val->special = ConstValSpecialStatic;
   5099     const_val->type = g->builtin_types.entry_arg_tuple;
   5100     const_val->data.x_arg_tuple.start_index = arg_index_start;
   5101     const_val->data.x_arg_tuple.end_index = arg_index_end;
   5102 }
   5103 
   5104 ConstExprValue *create_const_arg_tuple(CodeGen *g, size_t arg_index_start, size_t arg_index_end) {
   5105     ConstExprValue *const_val = create_const_vals(1);
   5106     init_const_arg_tuple(g, const_val, arg_index_start, arg_index_end);
   5107     return const_val;
   5108 }
   5109 
   5110 
   5111 void init_const_undefined(CodeGen *g, ConstExprValue *const_val) {
   5112     Error err;
   5113     ZigType *wanted_type = const_val->type;
   5114     if (wanted_type->id == ZigTypeIdArray) {
   5115         const_val->special = ConstValSpecialStatic;
   5116         const_val->data.x_array.special = ConstArraySpecialUndef;
   5117     } else if (wanted_type->id == ZigTypeIdStruct) {
   5118         if ((err = ensure_complete_type(g, wanted_type))) {
   5119             return;
   5120         }
   5121 
   5122         const_val->special = ConstValSpecialStatic;
   5123         size_t field_count = wanted_type->data.structure.src_field_count;
   5124         const_val->data.x_struct.fields = create_const_vals(field_count);
   5125         for (size_t i = 0; i < field_count; i += 1) {
   5126             ConstExprValue *field_val = &const_val->data.x_struct.fields[i];
   5127             field_val->type = wanted_type->data.structure.fields[i].type_entry;
   5128             assert(field_val->type);
   5129             init_const_undefined(g, field_val);
   5130             field_val->parent.id = ConstParentIdStruct;
   5131             field_val->parent.data.p_struct.struct_val = const_val;
   5132             field_val->parent.data.p_struct.field_index = i;
   5133         }
   5134     } else {
   5135         const_val->special = ConstValSpecialUndef;
   5136     }
   5137 }
   5138 
   5139 ConstExprValue *create_const_vals(size_t count) {
   5140     ConstGlobalRefs *global_refs = allocate<ConstGlobalRefs>(count);
   5141     ConstExprValue *vals = allocate<ConstExprValue>(count);
   5142     for (size_t i = 0; i < count; i += 1) {
   5143         vals[i].global_refs = &global_refs[i];
   5144     }
   5145     return vals;
   5146 }
   5147 
   5148 Error ensure_complete_type(CodeGen *g, ZigType *type_entry) {
   5149     return type_resolve(g, type_entry, ResolveStatusSizeKnown);
   5150 }
   5151 
   5152 static ZigType *get_async_fn_type(CodeGen *g, ZigType *orig_fn_type) {
   5153     if (orig_fn_type->data.fn.fn_type_id.cc == CallingConventionAsync)
   5154         return orig_fn_type;
   5155 
   5156     ZigType *fn_type = allocate_nonzero<ZigType>(1);
   5157     *fn_type = *orig_fn_type;
   5158     fn_type->data.fn.fn_type_id.cc = CallingConventionAsync;
   5159     fn_type->llvm_type = nullptr;
   5160     fn_type->llvm_di_type = nullptr;
   5161 
   5162     return fn_type;
   5163 }
   5164 
   5165 static Error resolve_coro_frame(CodeGen *g, ZigType *frame_type) {
   5166     Error err;
   5167 
   5168     if (frame_type->data.frame.locals_struct != nullptr)
   5169         return ErrorNone;
   5170 
   5171     ZigFn *fn = frame_type->data.frame.fn;
   5172     switch (fn->anal_state) {
   5173         case FnAnalStateInvalid:
   5174             return ErrorSemanticAnalyzeFail;
   5175         case FnAnalStateComplete:
   5176             break;
   5177         case FnAnalStateReady:
   5178             analyze_fn_body(g, fn);
   5179             if (fn->anal_state == FnAnalStateInvalid)
   5180                 return ErrorSemanticAnalyzeFail;
   5181             break;
   5182         case FnAnalStateProbing:
   5183             add_node_error(g, fn->proto_node,
   5184                     buf_sprintf("cannot resolve '%s': function not fully analyzed yet",
   5185                         buf_ptr(&frame_type->name)));
   5186             return ErrorSemanticAnalyzeFail;
   5187     }
   5188     ZigType *fn_type = get_async_fn_type(g, fn->type_entry);
   5189 
   5190     for (size_t i = 0; i < fn->call_list.length; i += 1) {
   5191         IrInstructionCallGen *call = fn->call_list.at(i);
   5192         ZigFn *callee = call->fn_entry;
   5193         if (callee == nullptr) {
   5194             add_node_error(g, call->base.source_node,
   5195                 buf_sprintf("function is not comptime-known; @asyncCall required"));
   5196             return ErrorSemanticAnalyzeFail;
   5197         }
   5198         if (callee->body_node == nullptr) {
   5199             continue;
   5200         }
   5201 
   5202         analyze_fn_body(g, callee);
   5203         if (callee->anal_state == FnAnalStateInvalid) {
   5204             frame_type->data.frame.locals_struct = g->builtin_types.entry_invalid;
   5205             return ErrorSemanticAnalyzeFail;
   5206         }
   5207         analyze_fn_async(g, callee);
   5208         if (!fn_is_async(callee))
   5209             continue;
   5210 
   5211         ZigType *callee_frame_type = get_coro_frame_type(g, callee);
   5212 
   5213         IrInstructionAllocaGen *alloca_gen = allocate<IrInstructionAllocaGen>(1);
   5214         alloca_gen->base.id = IrInstructionIdAllocaGen;
   5215         alloca_gen->base.source_node = call->base.source_node;
   5216         alloca_gen->base.scope = call->base.scope;
   5217         alloca_gen->base.value.type = get_pointer_to_type(g, callee_frame_type, false);
   5218         alloca_gen->base.ref_count = 1;
   5219         alloca_gen->name_hint = "";
   5220         fn->alloca_gen_list.append(alloca_gen);
   5221         call->frame_result_loc = &alloca_gen->base;
   5222     }
   5223 
   5224     // label (grep this): [coro_frame_struct_layout]
   5225     ZigList<ZigType *> field_types = {};
   5226     ZigList<const char *> field_names = {};
   5227 
   5228     field_names.append("@fn_ptr");
   5229     field_types.append(fn_type);
   5230 
   5231     field_names.append("@resume_index");
   5232     field_types.append(g->builtin_types.entry_usize);
   5233 
   5234     field_names.append("@awaiter");
   5235     field_types.append(g->builtin_types.entry_usize);
   5236 
   5237     FnTypeId *fn_type_id = &fn_type->data.fn.fn_type_id;
   5238     ZigType *ptr_return_type = get_pointer_to_type(g, fn_type_id->return_type, false);
   5239     field_names.append("@result_ptr_callee");
   5240     field_types.append(ptr_return_type);
   5241 
   5242     field_names.append("@result_ptr_awaiter");
   5243     field_types.append(ptr_return_type);
   5244 
   5245     field_names.append("@result");
   5246     field_types.append(fn_type_id->return_type);
   5247 
   5248     if (codegen_fn_has_err_ret_tracing_arg(g, fn_type_id->return_type)) {
   5249         field_names.append("@ptr_stack_trace");
   5250         field_types.append(get_ptr_to_stack_trace_type(g));
   5251     }
   5252 
   5253     for (size_t arg_i = 0; arg_i < fn_type_id->param_count; arg_i += 1) {
   5254         FnTypeParamInfo *param_info = &fn_type_id->param_info[arg_i];
   5255         AstNode *param_decl_node = get_param_decl_node(fn, arg_i);
   5256         Buf *param_name;
   5257         bool is_var_args = param_decl_node && param_decl_node->data.param_decl.is_var_args;
   5258         if (param_decl_node && !is_var_args) {
   5259             param_name = param_decl_node->data.param_decl.name;
   5260         } else {
   5261             param_name = buf_sprintf("@arg%" ZIG_PRI_usize, arg_i);
   5262         }
   5263         ZigType *param_type = param_info->type;
   5264         field_names.append(buf_ptr(param_name));
   5265         field_types.append(param_type);
   5266     }
   5267 
   5268     if (codegen_fn_has_err_ret_tracing_stack(g, fn, true)) {
   5269         (void)get_ptr_to_stack_trace_type(g); // populate g->stack_trace_type
   5270 
   5271         field_names.append("@stack_trace");
   5272         field_types.append(g->stack_trace_type);
   5273 
   5274         field_names.append("@instruction_addresses");
   5275         field_types.append(get_array_type(g, g->builtin_types.entry_usize, stack_trace_ptr_count));
   5276     }
   5277 
   5278     for (size_t alloca_i = 0; alloca_i < fn->alloca_gen_list.length; alloca_i += 1) {
   5279         IrInstructionAllocaGen *instruction = fn->alloca_gen_list.at(alloca_i);
   5280         ZigType *ptr_type = instruction->base.value.type;
   5281         assert(ptr_type->id == ZigTypeIdPointer);
   5282         ZigType *child_type = ptr_type->data.pointer.child_type;
   5283         if (!type_has_bits(child_type))
   5284             continue;
   5285         if (instruction->base.ref_count == 0)
   5286             continue;
   5287         if (instruction->base.value.special != ConstValSpecialRuntime) {
   5288             if (const_ptr_pointee(nullptr, g, &instruction->base.value, nullptr)->special !=
   5289                     ConstValSpecialRuntime)
   5290             {
   5291                 continue;
   5292             }
   5293         }
   5294         if ((err = type_resolve(g, child_type, ResolveStatusSizeKnown))) {
   5295             return err;
   5296         }
   5297         const char *name;
   5298         if (*instruction->name_hint == 0) {
   5299             name = buf_ptr(buf_sprintf("@local%" ZIG_PRI_usize, alloca_i));
   5300         } else {
   5301             name = instruction->name_hint;
   5302         }
   5303         field_names.append(name);
   5304         field_types.append(child_type);
   5305     }
   5306 
   5307 
   5308     assert(field_names.length == field_types.length);
   5309     frame_type->data.frame.locals_struct = get_struct_type(g, buf_ptr(&frame_type->name),
   5310             field_names.items, field_types.items, field_names.length);
   5311     frame_type->abi_size = frame_type->data.frame.locals_struct->abi_size;
   5312     frame_type->abi_align = frame_type->data.frame.locals_struct->abi_align;
   5313     frame_type->size_in_bits = frame_type->data.frame.locals_struct->size_in_bits;
   5314     return ErrorNone;
   5315 }
   5316 
   5317 Error type_resolve(CodeGen *g, ZigType *ty, ResolveStatus status) {
   5318     if (type_is_invalid(ty))
   5319         return ErrorSemanticAnalyzeFail;
   5320     switch (status) {
   5321         case ResolveStatusUnstarted:
   5322             return ErrorNone;
   5323         case ResolveStatusInvalid:
   5324             zig_unreachable();
   5325         case ResolveStatusZeroBitsKnown:
   5326             if (ty->id == ZigTypeIdStruct) {
   5327                 return resolve_struct_zero_bits(g, ty);
   5328             } else if (ty->id == ZigTypeIdEnum) {
   5329                 return resolve_enum_zero_bits(g, ty);
   5330             } else if (ty->id == ZigTypeIdUnion) {
   5331                 return resolve_union_zero_bits(g, ty);
   5332             }
   5333             return ErrorNone;
   5334         case ResolveStatusAlignmentKnown:
   5335             if (ty->id == ZigTypeIdStruct) {
   5336                 return resolve_struct_alignment(g, ty);
   5337             } else if (ty->id == ZigTypeIdEnum) {
   5338                 return resolve_enum_zero_bits(g, ty);
   5339             } else if (ty->id == ZigTypeIdUnion) {
   5340                 return resolve_union_alignment(g, ty);
   5341             } else if (ty->id == ZigTypeIdCoroFrame) {
   5342                 return resolve_coro_frame(g, ty);
   5343             }
   5344             return ErrorNone;
   5345         case ResolveStatusSizeKnown:
   5346             if (ty->id == ZigTypeIdStruct) {
   5347                 return resolve_struct_type(g, ty);
   5348             } else if (ty->id == ZigTypeIdEnum) {
   5349                 return resolve_enum_zero_bits(g, ty);
   5350             } else if (ty->id == ZigTypeIdUnion) {
   5351                 return resolve_union_type(g, ty);
   5352             } else if (ty->id == ZigTypeIdCoroFrame) {
   5353                 return resolve_coro_frame(g, ty);
   5354             }
   5355             return ErrorNone;
   5356         case ResolveStatusLLVMFwdDecl:
   5357         case ResolveStatusLLVMFull:
   5358             resolve_llvm_types(g, ty, status);
   5359             return ErrorNone;
   5360     }
   5361     zig_unreachable();
   5362 }
   5363 
   5364 bool ir_get_var_is_comptime(ZigVar *var) {
   5365     // The is_comptime field can be left null, which means not comptime.
   5366     if (var->is_comptime == nullptr)
   5367         return false;
   5368     // When the is_comptime field references an instruction that has to get analyzed, this
   5369     // is the value.
   5370     if (var->is_comptime->child != nullptr) {
   5371         assert(var->is_comptime->child->value.type->id == ZigTypeIdBool);
   5372         return var->is_comptime->child->value.data.x_bool;
   5373     }
   5374     // As an optimization, is_comptime values which are constant are allowed
   5375     // to be omitted from analysis. In this case, there is no child instruction
   5376     // and we simply look at the unanalyzed const parent instruction.
   5377     assert(var->is_comptime->value.type->id == ZigTypeIdBool);
   5378     return var->is_comptime->value.data.x_bool;
   5379 }
   5380 
   5381 bool const_values_equal_ptr(ConstExprValue *a, ConstExprValue *b) {
   5382     if (a->data.x_ptr.special != b->data.x_ptr.special)
   5383         return false;
   5384     if (a->data.x_ptr.mut != b->data.x_ptr.mut)
   5385         return false;
   5386     switch (a->data.x_ptr.special) {
   5387         case ConstPtrSpecialInvalid:
   5388             zig_unreachable();
   5389         case ConstPtrSpecialRef:
   5390             if (a->data.x_ptr.data.ref.pointee != b->data.x_ptr.data.ref.pointee)
   5391                 return false;
   5392             return true;
   5393         case ConstPtrSpecialBaseArray:
   5394             if (a->data.x_ptr.data.base_array.array_val != b->data.x_ptr.data.base_array.array_val &&
   5395                 a->data.x_ptr.data.base_array.array_val->global_refs !=
   5396                 b->data.x_ptr.data.base_array.array_val->global_refs)
   5397             {
   5398                 return false;
   5399             }
   5400             if (a->data.x_ptr.data.base_array.elem_index != b->data.x_ptr.data.base_array.elem_index)
   5401                 return false;
   5402             if (a->data.x_ptr.data.base_array.is_cstr != b->data.x_ptr.data.base_array.is_cstr)
   5403                 return false;
   5404             return true;
   5405         case ConstPtrSpecialBaseStruct:
   5406             if (a->data.x_ptr.data.base_struct.struct_val != b->data.x_ptr.data.base_struct.struct_val &&
   5407                 a->data.x_ptr.data.base_struct.struct_val->global_refs !=
   5408                 b->data.x_ptr.data.base_struct.struct_val->global_refs)
   5409             {
   5410                 return false;
   5411             }
   5412             if (a->data.x_ptr.data.base_struct.field_index != b->data.x_ptr.data.base_struct.field_index)
   5413                 return false;
   5414             return true;
   5415         case ConstPtrSpecialBaseErrorUnionCode:
   5416             if (a->data.x_ptr.data.base_err_union_code.err_union_val !=
   5417                 b->data.x_ptr.data.base_err_union_code.err_union_val &&
   5418                 a->data.x_ptr.data.base_err_union_code.err_union_val->global_refs !=
   5419                 b->data.x_ptr.data.base_err_union_code.err_union_val->global_refs)
   5420             {
   5421                 return false;
   5422             }
   5423             return true;
   5424         case ConstPtrSpecialBaseErrorUnionPayload:
   5425             if (a->data.x_ptr.data.base_err_union_payload.err_union_val !=
   5426                 b->data.x_ptr.data.base_err_union_payload.err_union_val &&
   5427                 a->data.x_ptr.data.base_err_union_payload.err_union_val->global_refs !=
   5428                 b->data.x_ptr.data.base_err_union_payload.err_union_val->global_refs)
   5429             {
   5430                 return false;
   5431             }
   5432             return true;
   5433         case ConstPtrSpecialBaseOptionalPayload:
   5434             if (a->data.x_ptr.data.base_optional_payload.optional_val !=
   5435                 b->data.x_ptr.data.base_optional_payload.optional_val &&
   5436                 a->data.x_ptr.data.base_optional_payload.optional_val->global_refs !=
   5437                 b->data.x_ptr.data.base_optional_payload.optional_val->global_refs)
   5438             {
   5439                 return false;
   5440             }
   5441             return true;
   5442         case ConstPtrSpecialHardCodedAddr:
   5443             if (a->data.x_ptr.data.hard_coded_addr.addr != b->data.x_ptr.data.hard_coded_addr.addr)
   5444                 return false;
   5445             return true;
   5446         case ConstPtrSpecialDiscard:
   5447             return true;
   5448         case ConstPtrSpecialFunction:
   5449             return a->data.x_ptr.data.fn.fn_entry == b->data.x_ptr.data.fn.fn_entry;
   5450         case ConstPtrSpecialNull:
   5451             return true;
   5452     }
   5453     zig_unreachable();
   5454 }
   5455 
   5456 static bool const_values_equal_array(CodeGen *g, ConstExprValue *a, ConstExprValue *b, size_t len) {
   5457     assert(a->data.x_array.special != ConstArraySpecialUndef);
   5458     assert(b->data.x_array.special != ConstArraySpecialUndef);
   5459     if (a->data.x_array.special == ConstArraySpecialBuf &&
   5460         b->data.x_array.special == ConstArraySpecialBuf)
   5461     {
   5462         return buf_eql_buf(a->data.x_array.data.s_buf, b->data.x_array.data.s_buf);
   5463     }
   5464     expand_undef_array(g, a);
   5465     expand_undef_array(g, b);
   5466 
   5467     ConstExprValue *a_elems = a->data.x_array.data.s_none.elements;
   5468     ConstExprValue *b_elems = b->data.x_array.data.s_none.elements;
   5469 
   5470     for (size_t i = 0; i < len; i += 1) {
   5471         if (!const_values_equal(g, &a_elems[i], &b_elems[i]))
   5472             return false;
   5473     }
   5474 
   5475     return true;
   5476 }
   5477 
   5478 bool const_values_equal(CodeGen *g, ConstExprValue *a, ConstExprValue *b) {
   5479     assert(a->type->id == b->type->id);
   5480     assert(a->special == ConstValSpecialStatic);
   5481     assert(b->special == ConstValSpecialStatic);
   5482     switch (a->type->id) {
   5483         case ZigTypeIdOpaque:
   5484             zig_unreachable();
   5485         case ZigTypeIdEnum:
   5486             return bigint_cmp(&a->data.x_enum_tag, &b->data.x_enum_tag) == CmpEQ;
   5487         case ZigTypeIdUnion: {
   5488             ConstUnionValue *union1 = &a->data.x_union;
   5489             ConstUnionValue *union2 = &b->data.x_union;
   5490 
   5491             if (bigint_cmp(&union1->tag, &union2->tag) == CmpEQ) {
   5492                 TypeUnionField *field = find_union_field_by_tag(a->type, &union1->tag);
   5493                 assert(field != nullptr);
   5494                 if (!type_has_bits(field->type_entry))
   5495                     return true;
   5496                 assert(find_union_field_by_tag(a->type, &union2->tag) != nullptr);
   5497                 return const_values_equal(g, union1->payload, union2->payload);
   5498             }
   5499             return false;
   5500         }
   5501         case ZigTypeIdMetaType:
   5502             return a->data.x_type == b->data.x_type;
   5503         case ZigTypeIdVoid:
   5504             return true;
   5505         case ZigTypeIdErrorSet:
   5506             return a->data.x_err_set->value == b->data.x_err_set->value;
   5507         case ZigTypeIdBool:
   5508             return a->data.x_bool == b->data.x_bool;
   5509         case ZigTypeIdFloat:
   5510             assert(a->type->data.floating.bit_count == b->type->data.floating.bit_count);
   5511             switch (a->type->data.floating.bit_count) {
   5512                 case 16:
   5513                     return f16_eq(a->data.x_f16, b->data.x_f16);
   5514                 case 32:
   5515                     return a->data.x_f32 == b->data.x_f32;
   5516                 case 64:
   5517                     return a->data.x_f64 == b->data.x_f64;
   5518                 case 128:
   5519                     return f128M_eq(&a->data.x_f128, &b->data.x_f128);
   5520                 default:
   5521                     zig_unreachable();
   5522             }
   5523         case ZigTypeIdComptimeFloat:
   5524             return bigfloat_cmp(&a->data.x_bigfloat, &b->data.x_bigfloat) == CmpEQ;
   5525         case ZigTypeIdInt:
   5526         case ZigTypeIdComptimeInt:
   5527             return bigint_cmp(&a->data.x_bigint, &b->data.x_bigint) == CmpEQ;
   5528         case ZigTypeIdEnumLiteral:
   5529             return buf_eql_buf(a->data.x_enum_literal, b->data.x_enum_literal);
   5530         case ZigTypeIdPointer:
   5531         case ZigTypeIdFn:
   5532             return const_values_equal_ptr(a, b);
   5533         case ZigTypeIdVector:
   5534             assert(a->type->data.vector.len == b->type->data.vector.len);
   5535             return const_values_equal_array(g, a, b, a->type->data.vector.len);
   5536         case ZigTypeIdArray: {
   5537             assert(a->type->data.array.len == b->type->data.array.len);
   5538             return const_values_equal_array(g, a, b, a->type->data.array.len);
   5539         }
   5540         case ZigTypeIdStruct:
   5541             for (size_t i = 0; i < a->type->data.structure.src_field_count; i += 1) {
   5542                 ConstExprValue *field_a = &a->data.x_struct.fields[i];
   5543                 ConstExprValue *field_b = &b->data.x_struct.fields[i];
   5544                 if (!const_values_equal(g, field_a, field_b))
   5545                     return false;
   5546             }
   5547             return true;
   5548         case ZigTypeIdCoroFrame:
   5549             zig_panic("TODO");
   5550         case ZigTypeIdAnyFrame:
   5551             zig_panic("TODO");
   5552         case ZigTypeIdUndefined:
   5553             zig_panic("TODO");
   5554         case ZigTypeIdNull:
   5555             zig_panic("TODO");
   5556         case ZigTypeIdOptional:
   5557             if (get_codegen_ptr_type(a->type) != nullptr)
   5558                 return const_values_equal_ptr(a, b);
   5559             if (a->data.x_optional == nullptr || b->data.x_optional == nullptr) {
   5560                 return (a->data.x_optional == nullptr && b->data.x_optional == nullptr);
   5561             } else {
   5562                 return const_values_equal(g, a->data.x_optional, b->data.x_optional);
   5563             }
   5564         case ZigTypeIdErrorUnion:
   5565             zig_panic("TODO");
   5566         case ZigTypeIdArgTuple:
   5567             return a->data.x_arg_tuple.start_index == b->data.x_arg_tuple.start_index &&
   5568                    a->data.x_arg_tuple.end_index == b->data.x_arg_tuple.end_index;
   5569         case ZigTypeIdBoundFn:
   5570         case ZigTypeIdInvalid:
   5571         case ZigTypeIdUnreachable:
   5572             zig_unreachable();
   5573     }
   5574     zig_unreachable();
   5575 }
   5576 
   5577 void eval_min_max_value_int(CodeGen *g, ZigType *int_type, BigInt *bigint, bool is_max) {
   5578     assert(int_type->id == ZigTypeIdInt);
   5579     if (int_type->data.integral.bit_count == 0) {
   5580         bigint_init_unsigned(bigint, 0);
   5581         return;
   5582     }
   5583     if (is_max) {
   5584         // is_signed=true   (1 << (bit_count - 1)) - 1
   5585         // is_signed=false  (1 << (bit_count - 0)) - 1
   5586         BigInt one = {0};
   5587         bigint_init_unsigned(&one, 1);
   5588 
   5589         size_t shift_amt = int_type->data.integral.bit_count - (int_type->data.integral.is_signed ? 1 : 0);
   5590         BigInt bit_count_bi = {0};
   5591         bigint_init_unsigned(&bit_count_bi, shift_amt);
   5592 
   5593         BigInt shifted_bi = {0};
   5594         bigint_shl(&shifted_bi, &one, &bit_count_bi);
   5595 
   5596         bigint_sub(bigint, &shifted_bi, &one);
   5597     } else if (int_type->data.integral.is_signed) {
   5598         // - (1 << (bit_count - 1))
   5599         BigInt one = {0};
   5600         bigint_init_unsigned(&one, 1);
   5601 
   5602         BigInt bit_count_bi = {0};
   5603         bigint_init_unsigned(&bit_count_bi, int_type->data.integral.bit_count - 1);
   5604 
   5605         BigInt shifted_bi = {0};
   5606         bigint_shl(&shifted_bi, &one, &bit_count_bi);
   5607 
   5608         bigint_negate(bigint, &shifted_bi);
   5609     } else {
   5610         bigint_init_unsigned(bigint, 0);
   5611     }
   5612 }
   5613 
   5614 void eval_min_max_value(CodeGen *g, ZigType *type_entry, ConstExprValue *const_val, bool is_max) {
   5615     if (type_entry->id == ZigTypeIdInt) {
   5616         const_val->special = ConstValSpecialStatic;
   5617         eval_min_max_value_int(g, type_entry, &const_val->data.x_bigint, is_max);
   5618     } else if (type_entry->id == ZigTypeIdBool) {
   5619         const_val->special = ConstValSpecialStatic;
   5620         const_val->data.x_bool = is_max;
   5621     } else if (type_entry->id == ZigTypeIdVoid) {
   5622         // nothing to do
   5623     } else {
   5624         zig_unreachable();
   5625     }
   5626 }
   5627 
   5628 static void render_const_val_ptr(CodeGen *g, Buf *buf, ConstExprValue *const_val, ZigType *type_entry) {
   5629     assert(type_entry->id == ZigTypeIdPointer);
   5630 
   5631     if (type_entry->data.pointer.child_type->id == ZigTypeIdOpaque) {
   5632         buf_append_buf(buf, &type_entry->name);
   5633         return;
   5634     }
   5635 
   5636     switch (const_val->data.x_ptr.special) {
   5637         case ConstPtrSpecialInvalid:
   5638             zig_unreachable();
   5639         case ConstPtrSpecialRef:
   5640         case ConstPtrSpecialBaseStruct:
   5641         case ConstPtrSpecialBaseErrorUnionCode:
   5642         case ConstPtrSpecialBaseErrorUnionPayload:
   5643         case ConstPtrSpecialBaseOptionalPayload:
   5644             buf_appendf(buf, "*");
   5645             // TODO we need a source node for const_ptr_pointee because it can generate compile errors
   5646             render_const_value(g, buf, const_ptr_pointee(nullptr, g, const_val, nullptr));
   5647             return;
   5648         case ConstPtrSpecialBaseArray:
   5649             if (const_val->data.x_ptr.data.base_array.is_cstr) {
   5650                 buf_appendf(buf, "*(c str lit)");
   5651                 return;
   5652             } else {
   5653                 buf_appendf(buf, "*");
   5654                 // TODO we need a source node for const_ptr_pointee because it can generate compile errors
   5655                 render_const_value(g, buf, const_ptr_pointee(nullptr, g, const_val, nullptr));
   5656                 return;
   5657             }
   5658         case ConstPtrSpecialHardCodedAddr:
   5659             buf_appendf(buf, "(%s)(%" ZIG_PRI_x64 ")", buf_ptr(&type_entry->name),
   5660                     const_val->data.x_ptr.data.hard_coded_addr.addr);
   5661             return;
   5662         case ConstPtrSpecialDiscard:
   5663             buf_append_str(buf, "*_");
   5664             return;
   5665         case ConstPtrSpecialFunction:
   5666             {
   5667                 ZigFn *fn_entry = const_val->data.x_ptr.data.fn.fn_entry;
   5668                 buf_appendf(buf, "@ptrCast(%s, %s)", buf_ptr(&const_val->type->name), buf_ptr(&fn_entry->symbol_name));
   5669                 return;
   5670             }
   5671         case ConstPtrSpecialNull:
   5672             buf_append_str(buf, "null");
   5673             return;
   5674     }
   5675     zig_unreachable();
   5676 }
   5677 
   5678 static void render_const_val_err_set(CodeGen *g, Buf *buf, ConstExprValue *const_val, ZigType *type_entry) {
   5679     if (const_val->data.x_err_set == nullptr) {
   5680         buf_append_str(buf, "null");
   5681     } else {
   5682         buf_appendf(buf, "%s.%s", buf_ptr(&type_entry->name), buf_ptr(&const_val->data.x_err_set->name));
   5683     }
   5684 }
   5685 
   5686 static void render_const_val_array(CodeGen *g, Buf *buf, Buf *type_name, ConstExprValue *const_val, uint64_t start, uint64_t len) {
   5687     ConstArrayValue *array = &const_val->data.x_array;
   5688     switch (array->special) {
   5689         case ConstArraySpecialUndef:
   5690             buf_append_str(buf, "undefined");
   5691             return;
   5692         case ConstArraySpecialBuf: {
   5693             Buf *array_buf = array->data.s_buf;
   5694             const char *base = &buf_ptr(array_buf)[start];
   5695             assert(start + len <= buf_len(array_buf));
   5696 
   5697             buf_append_char(buf, '"');
   5698             for (size_t i = 0; i < len; i += 1) {
   5699                 uint8_t c = base[i];
   5700                 if (c == '"') {
   5701                     buf_append_str(buf, "\\\"");
   5702                 } else {
   5703                     buf_append_char(buf, c);
   5704                 }
   5705             }
   5706             buf_append_char(buf, '"');
   5707             return;
   5708         }
   5709         case ConstArraySpecialNone: {
   5710             ConstExprValue *base = &array->data.s_none.elements[start];
   5711             assert(start + len <= const_val->type->data.array.len);
   5712 
   5713             buf_appendf(buf, "%s{", buf_ptr(type_name));
   5714             for (uint64_t i = 0; i < len; i += 1) {
   5715                 if (i != 0) buf_appendf(buf, ",");
   5716                 render_const_value(g, buf, &base[i]);
   5717             }
   5718             buf_appendf(buf, "}");
   5719             return;
   5720         }
   5721     }
   5722     zig_unreachable();
   5723 }
   5724 
   5725 void render_const_value(CodeGen *g, Buf *buf, ConstExprValue *const_val) {
   5726     switch (const_val->special) {
   5727         case ConstValSpecialRuntime:
   5728             buf_appendf(buf, "(runtime value)");
   5729             return;
   5730         case ConstValSpecialUndef:
   5731             buf_appendf(buf, "undefined");
   5732             return;
   5733         case ConstValSpecialStatic:
   5734             break;
   5735     }
   5736     assert(const_val->type);
   5737 
   5738     ZigType *type_entry = const_val->type;
   5739     switch (type_entry->id) {
   5740         case ZigTypeIdOpaque:
   5741             zig_unreachable();
   5742         case ZigTypeIdInvalid:
   5743             buf_appendf(buf, "(invalid)");
   5744             return;
   5745         case ZigTypeIdVoid:
   5746             buf_appendf(buf, "{}");
   5747             return;
   5748         case ZigTypeIdComptimeFloat:
   5749             bigfloat_append_buf(buf, &const_val->data.x_bigfloat);
   5750             return;
   5751         case ZigTypeIdFloat:
   5752             switch (type_entry->data.floating.bit_count) {
   5753                 case 16:
   5754                     buf_appendf(buf, "%f", zig_f16_to_double(const_val->data.x_f16));
   5755                     return;
   5756                 case 32:
   5757                     buf_appendf(buf, "%f", const_val->data.x_f32);
   5758                     return;
   5759                 case 64:
   5760                     buf_appendf(buf, "%f", const_val->data.x_f64);
   5761                     return;
   5762                 case 128:
   5763                     {
   5764                         const size_t extra_len = 100;
   5765                         size_t old_len = buf_len(buf);
   5766                         buf_resize(buf, old_len + extra_len);
   5767                         float64_t f64_value = f128M_to_f64(&const_val->data.x_f128);
   5768                         double double_value;
   5769                         memcpy(&double_value, &f64_value, sizeof(double));
   5770                         // TODO actual f128 printing to decimal
   5771                         int len = snprintf(buf_ptr(buf) + old_len, extra_len, "%f", double_value);
   5772                         assert(len > 0);
   5773                         buf_resize(buf, old_len + len);
   5774                         return;
   5775                     }
   5776                 default:
   5777                     zig_unreachable();
   5778             }
   5779         case ZigTypeIdComptimeInt:
   5780         case ZigTypeIdInt:
   5781             bigint_append_buf(buf, &const_val->data.x_bigint, 10);
   5782             return;
   5783         case ZigTypeIdEnumLiteral:
   5784             buf_append_buf(buf, const_val->data.x_enum_literal);
   5785             return;
   5786         case ZigTypeIdMetaType:
   5787             buf_appendf(buf, "%s", buf_ptr(&const_val->data.x_type->name));
   5788             return;
   5789         case ZigTypeIdUnreachable:
   5790             buf_appendf(buf, "unreachable");
   5791             return;
   5792         case ZigTypeIdBool:
   5793             {
   5794                 const char *value = const_val->data.x_bool ? "true" : "false";
   5795                 buf_appendf(buf, "%s", value);
   5796                 return;
   5797             }
   5798         case ZigTypeIdFn:
   5799             {
   5800                 assert(const_val->data.x_ptr.mut == ConstPtrMutComptimeConst);
   5801                 assert(const_val->data.x_ptr.special == ConstPtrSpecialFunction);
   5802                 ZigFn *fn_entry = const_val->data.x_ptr.data.fn.fn_entry;
   5803                 buf_appendf(buf, "%s", buf_ptr(&fn_entry->symbol_name));
   5804                 return;
   5805             }
   5806         case ZigTypeIdPointer:
   5807             return render_const_val_ptr(g, buf, const_val, type_entry);
   5808         case ZigTypeIdArray: {
   5809             uint64_t len = type_entry->data.array.len;
   5810             render_const_val_array(g, buf, &type_entry->name, const_val, 0, len);
   5811             return;
   5812         }
   5813         case ZigTypeIdVector: {
   5814             uint32_t len = type_entry->data.vector.len;
   5815             render_const_val_array(g, buf, &type_entry->name, const_val, 0, len);
   5816             return;
   5817         }
   5818         case ZigTypeIdNull:
   5819             {
   5820                 buf_appendf(buf, "null");
   5821                 return;
   5822             }
   5823         case ZigTypeIdUndefined:
   5824             {
   5825                 buf_appendf(buf, "undefined");
   5826                 return;
   5827             }
   5828         case ZigTypeIdOptional:
   5829             {
   5830                 if (get_codegen_ptr_type(const_val->type) != nullptr)
   5831                     return render_const_val_ptr(g, buf, const_val, type_entry->data.maybe.child_type);
   5832                 if (type_entry->data.maybe.child_type->id == ZigTypeIdErrorSet)
   5833                     return render_const_val_err_set(g, buf, const_val, type_entry->data.maybe.child_type);
   5834                 if (const_val->data.x_optional) {
   5835                     render_const_value(g, buf, const_val->data.x_optional);
   5836                 } else {
   5837                     buf_appendf(buf, "null");
   5838                 }
   5839                 return;
   5840             }
   5841         case ZigTypeIdBoundFn:
   5842             {
   5843                 ZigFn *fn_entry = const_val->data.x_bound_fn.fn;
   5844                 buf_appendf(buf, "(bound fn %s)", buf_ptr(&fn_entry->symbol_name));
   5845                 return;
   5846             }
   5847         case ZigTypeIdStruct:
   5848             {
   5849                 if (is_slice(type_entry)) {
   5850                     ConstExprValue *len_val = &const_val->data.x_struct.fields[slice_len_index];
   5851                     size_t len = bigint_as_unsigned(&len_val->data.x_bigint);
   5852 
   5853                     ConstExprValue *ptr_val = &const_val->data.x_struct.fields[slice_ptr_index];
   5854                     if (ptr_val->special == ConstValSpecialUndef) {
   5855                         assert(len == 0);
   5856                         buf_appendf(buf, "((%s)(undefined))[0..0]", buf_ptr(&type_entry->name));
   5857                         return;
   5858                     }
   5859                     assert(ptr_val->data.x_ptr.special == ConstPtrSpecialBaseArray);
   5860                     ConstExprValue *array = ptr_val->data.x_ptr.data.base_array.array_val;
   5861                     size_t start = ptr_val->data.x_ptr.data.base_array.elem_index;
   5862 
   5863                     render_const_val_array(g, buf, &type_entry->name, array, start, len);
   5864                 } else {
   5865                     buf_appendf(buf, "(struct %s constant)", buf_ptr(&type_entry->name));
   5866                 }
   5867                 return;
   5868             }
   5869         case ZigTypeIdEnum:
   5870             {
   5871                 TypeEnumField *field = find_enum_field_by_tag(type_entry, &const_val->data.x_enum_tag);
   5872                 buf_appendf(buf, "%s.%s", buf_ptr(&type_entry->name), buf_ptr(field->name));
   5873                 return;
   5874             }
   5875         case ZigTypeIdErrorUnion:
   5876             {
   5877                 buf_appendf(buf, "%s(", buf_ptr(&type_entry->name));
   5878                 ErrorTableEntry *err_set = const_val->data.x_err_union.error_set->data.x_err_set;
   5879                 if (err_set == nullptr) {
   5880                     render_const_value(g, buf, const_val->data.x_err_union.payload);
   5881                 } else {
   5882                     buf_appendf(buf, "%s.%s", buf_ptr(&type_entry->data.error_union.err_set_type->name),
   5883                             buf_ptr(&err_set->name));
   5884                 }
   5885                 buf_appendf(buf, ")");
   5886                 return;
   5887             }
   5888         case ZigTypeIdUnion:
   5889             {
   5890                 const BigInt *tag = &const_val->data.x_union.tag;
   5891                 TypeUnionField *field = find_union_field_by_tag(type_entry, tag);
   5892                 buf_appendf(buf, "%s { .%s = ", buf_ptr(&type_entry->name), buf_ptr(field->name));
   5893                 render_const_value(g, buf, const_val->data.x_union.payload);
   5894                 buf_append_str(buf, "}");
   5895                 return;
   5896             }
   5897         case ZigTypeIdErrorSet:
   5898             return render_const_val_err_set(g, buf, const_val, type_entry);
   5899         case ZigTypeIdArgTuple:
   5900             {
   5901                 buf_appendf(buf, "(args value)");
   5902                 return;
   5903             }
   5904         case ZigTypeIdCoroFrame:
   5905             buf_appendf(buf, "(TODO: async function frame value)");
   5906             return;
   5907 
   5908         case ZigTypeIdAnyFrame:
   5909             buf_appendf(buf, "(TODO: anyframe value)");
   5910             return;
   5911 
   5912     }
   5913     zig_unreachable();
   5914 }
   5915 
   5916 ZigType *make_int_type(CodeGen *g, bool is_signed, uint32_t size_in_bits) {
   5917     assert(size_in_bits <= 65535);
   5918     ZigType *entry = new_type_table_entry(ZigTypeIdInt);
   5919 
   5920     entry->size_in_bits = size_in_bits;
   5921     if (size_in_bits != 0) {
   5922         entry->llvm_type = LLVMIntType(size_in_bits);
   5923         entry->abi_size = LLVMABISizeOfType(g->target_data_ref, entry->llvm_type);
   5924         entry->abi_align = LLVMABIAlignmentOfType(g->target_data_ref, entry->llvm_type);
   5925     }
   5926 
   5927     const char u_or_i = is_signed ? 'i' : 'u';
   5928     buf_resize(&entry->name, 0);
   5929     buf_appendf(&entry->name, "%c%" PRIu32, u_or_i, size_in_bits);
   5930 
   5931     entry->data.integral.is_signed = is_signed;
   5932     entry->data.integral.bit_count = size_in_bits;
   5933     return entry;
   5934 }
   5935 
   5936 uint32_t type_id_hash(TypeId x) {
   5937     switch (x.id) {
   5938         case ZigTypeIdInvalid:
   5939         case ZigTypeIdOpaque:
   5940         case ZigTypeIdMetaType:
   5941         case ZigTypeIdVoid:
   5942         case ZigTypeIdBool:
   5943         case ZigTypeIdUnreachable:
   5944         case ZigTypeIdFloat:
   5945         case ZigTypeIdStruct:
   5946         case ZigTypeIdComptimeFloat:
   5947         case ZigTypeIdComptimeInt:
   5948         case ZigTypeIdEnumLiteral:
   5949         case ZigTypeIdUndefined:
   5950         case ZigTypeIdNull:
   5951         case ZigTypeIdOptional:
   5952         case ZigTypeIdErrorSet:
   5953         case ZigTypeIdEnum:
   5954         case ZigTypeIdUnion:
   5955         case ZigTypeIdFn:
   5956         case ZigTypeIdBoundFn:
   5957         case ZigTypeIdArgTuple:
   5958         case ZigTypeIdCoroFrame:
   5959         case ZigTypeIdAnyFrame:
   5960             zig_unreachable();
   5961         case ZigTypeIdErrorUnion:
   5962             return hash_ptr(x.data.error_union.err_set_type) ^ hash_ptr(x.data.error_union.payload_type);
   5963         case ZigTypeIdPointer:
   5964             return hash_ptr(x.data.pointer.child_type) +
   5965                 ((x.data.pointer.ptr_len == PtrLenSingle) ? (uint32_t)1120226602 : (uint32_t)3200913342) +
   5966                 (x.data.pointer.is_const ? (uint32_t)2749109194 : (uint32_t)4047371087) +
   5967                 (x.data.pointer.is_volatile ? (uint32_t)536730450 : (uint32_t)1685612214) +
   5968                 (x.data.pointer.allow_zero ? (uint32_t)3324284834 : (uint32_t)3584904923) +
   5969                 (((uint32_t)x.data.pointer.alignment) ^ (uint32_t)0x777fbe0e) +
   5970                 (((uint32_t)x.data.pointer.bit_offset_in_host) ^ (uint32_t)2639019452) +
   5971                 (((uint32_t)x.data.pointer.host_int_bytes) ^ (uint32_t)529908881);
   5972         case ZigTypeIdArray:
   5973             return hash_ptr(x.data.array.child_type) +
   5974                 ((uint32_t)x.data.array.size ^ (uint32_t)2122979968);
   5975         case ZigTypeIdInt:
   5976             return (x.data.integer.is_signed ? (uint32_t)2652528194 : (uint32_t)163929201) +
   5977                     (((uint32_t)x.data.integer.bit_count) ^ (uint32_t)2998081557);
   5978         case ZigTypeIdVector:
   5979             return hash_ptr(x.data.vector.elem_type) * (x.data.vector.len * 526582681);
   5980     }
   5981     zig_unreachable();
   5982 }
   5983 
   5984 bool type_id_eql(TypeId a, TypeId b) {
   5985     if (a.id != b.id)
   5986         return false;
   5987     switch (a.id) {
   5988         case ZigTypeIdInvalid:
   5989         case ZigTypeIdMetaType:
   5990         case ZigTypeIdVoid:
   5991         case ZigTypeIdBool:
   5992         case ZigTypeIdUnreachable:
   5993         case ZigTypeIdFloat:
   5994         case ZigTypeIdStruct:
   5995         case ZigTypeIdComptimeFloat:
   5996         case ZigTypeIdComptimeInt:
   5997         case ZigTypeIdEnumLiteral:
   5998         case ZigTypeIdUndefined:
   5999         case ZigTypeIdNull:
   6000         case ZigTypeIdOptional:
   6001         case ZigTypeIdErrorSet:
   6002         case ZigTypeIdEnum:
   6003         case ZigTypeIdUnion:
   6004         case ZigTypeIdFn:
   6005         case ZigTypeIdBoundFn:
   6006         case ZigTypeIdArgTuple:
   6007         case ZigTypeIdOpaque:
   6008         case ZigTypeIdCoroFrame:
   6009         case ZigTypeIdAnyFrame:
   6010             zig_unreachable();
   6011         case ZigTypeIdErrorUnion:
   6012             return a.data.error_union.err_set_type == b.data.error_union.err_set_type &&
   6013                 a.data.error_union.payload_type == b.data.error_union.payload_type;
   6014 
   6015         case ZigTypeIdPointer:
   6016             return a.data.pointer.child_type == b.data.pointer.child_type &&
   6017                 a.data.pointer.ptr_len == b.data.pointer.ptr_len &&
   6018                 a.data.pointer.is_const == b.data.pointer.is_const &&
   6019                 a.data.pointer.is_volatile == b.data.pointer.is_volatile &&
   6020                 a.data.pointer.allow_zero == b.data.pointer.allow_zero &&
   6021                 a.data.pointer.alignment == b.data.pointer.alignment &&
   6022                 a.data.pointer.bit_offset_in_host == b.data.pointer.bit_offset_in_host &&
   6023                 a.data.pointer.host_int_bytes == b.data.pointer.host_int_bytes;
   6024         case ZigTypeIdArray:
   6025             return a.data.array.child_type == b.data.array.child_type &&
   6026                 a.data.array.size == b.data.array.size;
   6027         case ZigTypeIdInt:
   6028             return a.data.integer.is_signed == b.data.integer.is_signed &&
   6029                 a.data.integer.bit_count == b.data.integer.bit_count;
   6030         case ZigTypeIdVector:
   6031             return a.data.vector.elem_type == b.data.vector.elem_type &&
   6032                 a.data.vector.len == b.data.vector.len;
   6033     }
   6034     zig_unreachable();
   6035 }
   6036 
   6037 uint32_t zig_llvm_fn_key_hash(ZigLLVMFnKey x) {
   6038     switch (x.id) {
   6039         case ZigLLVMFnIdCtz:
   6040             return (uint32_t)(x.data.ctz.bit_count) * (uint32_t)810453934;
   6041         case ZigLLVMFnIdClz:
   6042             return (uint32_t)(x.data.clz.bit_count) * (uint32_t)2428952817;
   6043         case ZigLLVMFnIdPopCount:
   6044             return (uint32_t)(x.data.clz.bit_count) * (uint32_t)101195049;
   6045         case ZigLLVMFnIdFloatOp:
   6046             return (uint32_t)(x.data.floating.bit_count) * ((uint32_t)x.id + 1025) +
   6047                    (uint32_t)(x.data.floating.vector_len) * (((uint32_t)x.id << 5) + 1025) +
   6048                    (uint32_t)(x.data.floating.op) * (uint32_t)43789879;
   6049         case ZigLLVMFnIdFMA:
   6050             return (uint32_t)(x.data.floating.bit_count) * ((uint32_t)x.id + 1025) +
   6051                    (uint32_t)(x.data.floating.vector_len) * (((uint32_t)x.id << 5) + 1025);
   6052         case ZigLLVMFnIdBswap:
   6053             return (uint32_t)(x.data.bswap.bit_count) * (uint32_t)3661994335;
   6054         case ZigLLVMFnIdBitReverse:
   6055             return (uint32_t)(x.data.bit_reverse.bit_count) * (uint32_t)2621398431;
   6056         case ZigLLVMFnIdOverflowArithmetic:
   6057             return ((uint32_t)(x.data.overflow_arithmetic.bit_count) * 87135777) +
   6058                 ((uint32_t)(x.data.overflow_arithmetic.add_sub_mul) * 31640542) +
   6059                 ((uint32_t)(x.data.overflow_arithmetic.is_signed) ? 1062315172 : 314955820) +
   6060                 x.data.overflow_arithmetic.vector_len * 1435156945;
   6061     }
   6062     zig_unreachable();
   6063 }
   6064 
   6065 bool zig_llvm_fn_key_eql(ZigLLVMFnKey a, ZigLLVMFnKey b) {
   6066     if (a.id != b.id)
   6067         return false;
   6068     switch (a.id) {
   6069         case ZigLLVMFnIdCtz:
   6070             return a.data.ctz.bit_count == b.data.ctz.bit_count;
   6071         case ZigLLVMFnIdClz:
   6072             return a.data.clz.bit_count == b.data.clz.bit_count;
   6073         case ZigLLVMFnIdPopCount:
   6074             return a.data.pop_count.bit_count == b.data.pop_count.bit_count;
   6075         case ZigLLVMFnIdBswap:
   6076             return a.data.bswap.bit_count == b.data.bswap.bit_count;
   6077         case ZigLLVMFnIdBitReverse:
   6078             return a.data.bit_reverse.bit_count == b.data.bit_reverse.bit_count;
   6079         case ZigLLVMFnIdFloatOp:
   6080             return a.data.floating.bit_count == b.data.floating.bit_count &&
   6081                    a.data.floating.vector_len == b.data.floating.vector_len &&
   6082                    a.data.floating.op == b.data.floating.op;
   6083         case ZigLLVMFnIdFMA:
   6084             return a.data.floating.bit_count == b.data.floating.bit_count &&
   6085                    a.data.floating.vector_len == b.data.floating.vector_len;
   6086         case ZigLLVMFnIdOverflowArithmetic:
   6087             return (a.data.overflow_arithmetic.bit_count == b.data.overflow_arithmetic.bit_count) &&
   6088                 (a.data.overflow_arithmetic.add_sub_mul == b.data.overflow_arithmetic.add_sub_mul) &&
   6089                 (a.data.overflow_arithmetic.is_signed == b.data.overflow_arithmetic.is_signed) &&
   6090                 (a.data.overflow_arithmetic.vector_len == b.data.overflow_arithmetic.vector_len);
   6091     }
   6092     zig_unreachable();
   6093 }
   6094 
   6095 // Canonicalize the array value as ConstArraySpecialNone
   6096 void expand_undef_array(CodeGen *g, ConstExprValue *const_val) {
   6097     size_t elem_count;
   6098     ZigType *elem_type;
   6099     if (const_val->type->id == ZigTypeIdArray) {
   6100         elem_count = const_val->type->data.array.len;
   6101         elem_type = const_val->type->data.array.child_type;
   6102     } else if (const_val->type->id == ZigTypeIdVector) {
   6103         elem_count = const_val->type->data.vector.len;
   6104         elem_type = const_val->type->data.vector.elem_type;
   6105     } else {
   6106         zig_unreachable();
   6107     }
   6108     if (const_val->special == ConstValSpecialUndef) {
   6109         const_val->special = ConstValSpecialStatic;
   6110         const_val->data.x_array.special = ConstArraySpecialUndef;
   6111     }
   6112     switch (const_val->data.x_array.special) {
   6113         case ConstArraySpecialNone:
   6114             return;
   6115         case ConstArraySpecialUndef: {
   6116             const_val->data.x_array.special = ConstArraySpecialNone;
   6117             const_val->data.x_array.data.s_none.elements = create_const_vals(elem_count);
   6118             for (size_t i = 0; i < elem_count; i += 1) {
   6119                 ConstExprValue *element_val = &const_val->data.x_array.data.s_none.elements[i];
   6120                 element_val->type = elem_type;
   6121                 init_const_undefined(g, element_val);
   6122                 element_val->parent.id = ConstParentIdArray;
   6123                 element_val->parent.data.p_array.array_val = const_val;
   6124                 element_val->parent.data.p_array.elem_index = i;
   6125             }
   6126             return;
   6127         }
   6128         case ConstArraySpecialBuf: {
   6129             Buf *buf = const_val->data.x_array.data.s_buf;
   6130             // If we're doing this it means that we are potentially modifying the data,
   6131             // so we can't have it be in the string literals table
   6132             g->string_literals_table.maybe_remove(buf);
   6133 
   6134             const_val->data.x_array.special = ConstArraySpecialNone;
   6135             assert(elem_count == buf_len(buf));
   6136             const_val->data.x_array.data.s_none.elements = create_const_vals(elem_count);
   6137             for (size_t i = 0; i < elem_count; i += 1) {
   6138                 ConstExprValue *this_char = &const_val->data.x_array.data.s_none.elements[i];
   6139                 this_char->special = ConstValSpecialStatic;
   6140                 this_char->type = g->builtin_types.entry_u8;
   6141                 bigint_init_unsigned(&this_char->data.x_bigint, (uint8_t)buf_ptr(buf)[i]);
   6142                 this_char->parent.id = ConstParentIdArray;
   6143                 this_char->parent.data.p_array.array_val = const_val;
   6144                 this_char->parent.data.p_array.elem_index = i;
   6145             }
   6146             return;
   6147         }
   6148     }
   6149     zig_unreachable();
   6150 }
   6151 
   6152 static const ZigTypeId all_type_ids[] = {
   6153     ZigTypeIdMetaType,
   6154     ZigTypeIdVoid,
   6155     ZigTypeIdBool,
   6156     ZigTypeIdUnreachable,
   6157     ZigTypeIdInt,
   6158     ZigTypeIdFloat,
   6159     ZigTypeIdPointer,
   6160     ZigTypeIdArray,
   6161     ZigTypeIdStruct,
   6162     ZigTypeIdComptimeFloat,
   6163     ZigTypeIdComptimeInt,
   6164     ZigTypeIdUndefined,
   6165     ZigTypeIdNull,
   6166     ZigTypeIdOptional,
   6167     ZigTypeIdErrorUnion,
   6168     ZigTypeIdErrorSet,
   6169     ZigTypeIdEnum,
   6170     ZigTypeIdUnion,
   6171     ZigTypeIdFn,
   6172     ZigTypeIdBoundFn,
   6173     ZigTypeIdArgTuple,
   6174     ZigTypeIdOpaque,
   6175     ZigTypeIdCoroFrame,
   6176     ZigTypeIdAnyFrame,
   6177     ZigTypeIdVector,
   6178     ZigTypeIdEnumLiteral,
   6179 };
   6180 
   6181 ZigTypeId type_id_at_index(size_t index) {
   6182     assert(index < array_length(all_type_ids));
   6183     return all_type_ids[index];
   6184 }
   6185 
   6186 size_t type_id_len() {
   6187     return array_length(all_type_ids);
   6188 }
   6189 
   6190 size_t type_id_index(ZigType *entry) {
   6191     switch (entry->id) {
   6192         case ZigTypeIdInvalid:
   6193             zig_unreachable();
   6194         case ZigTypeIdMetaType:
   6195             return 0;
   6196         case ZigTypeIdVoid:
   6197             return 1;
   6198         case ZigTypeIdBool:
   6199             return 2;
   6200         case ZigTypeIdUnreachable:
   6201             return 3;
   6202         case ZigTypeIdInt:
   6203             return 4;
   6204         case ZigTypeIdFloat:
   6205             return 5;
   6206         case ZigTypeIdPointer:
   6207             return 6;
   6208         case ZigTypeIdArray:
   6209             return 7;
   6210         case ZigTypeIdStruct:
   6211             if (entry->data.structure.is_slice)
   6212                 return 6;
   6213             return 8;
   6214         case ZigTypeIdComptimeFloat:
   6215             return 9;
   6216         case ZigTypeIdComptimeInt:
   6217             return 10;
   6218         case ZigTypeIdUndefined:
   6219             return 11;
   6220         case ZigTypeIdNull:
   6221             return 12;
   6222         case ZigTypeIdOptional:
   6223             return 13;
   6224         case ZigTypeIdErrorUnion:
   6225             return 14;
   6226         case ZigTypeIdErrorSet:
   6227             return 15;
   6228         case ZigTypeIdEnum:
   6229             return 16;
   6230         case ZigTypeIdUnion:
   6231             return 17;
   6232         case ZigTypeIdFn:
   6233             return 18;
   6234         case ZigTypeIdBoundFn:
   6235             return 19;
   6236         case ZigTypeIdArgTuple:
   6237             return 20;
   6238         case ZigTypeIdOpaque:
   6239             return 21;
   6240         case ZigTypeIdCoroFrame:
   6241             return 22;
   6242         case ZigTypeIdAnyFrame:
   6243             return 23;
   6244         case ZigTypeIdVector:
   6245             return 24;
   6246         case ZigTypeIdEnumLiteral:
   6247             return 25;
   6248     }
   6249     zig_unreachable();
   6250 }
   6251 
   6252 const char *type_id_name(ZigTypeId id) {
   6253     switch (id) {
   6254         case ZigTypeIdInvalid:
   6255             zig_unreachable();
   6256         case ZigTypeIdMetaType:
   6257             return "Type";
   6258         case ZigTypeIdVoid:
   6259             return "Void";
   6260         case ZigTypeIdBool:
   6261             return "Bool";
   6262         case ZigTypeIdUnreachable:
   6263             return "NoReturn";
   6264         case ZigTypeIdInt:
   6265             return "Int";
   6266         case ZigTypeIdFloat:
   6267             return "Float";
   6268         case ZigTypeIdPointer:
   6269             return "Pointer";
   6270         case ZigTypeIdArray:
   6271             return "Array";
   6272         case ZigTypeIdStruct:
   6273             return "Struct";
   6274         case ZigTypeIdComptimeFloat:
   6275             return "ComptimeFloat";
   6276         case ZigTypeIdComptimeInt:
   6277             return "ComptimeInt";
   6278         case ZigTypeIdEnumLiteral:
   6279             return "EnumLiteral";
   6280         case ZigTypeIdUndefined:
   6281             return "Undefined";
   6282         case ZigTypeIdNull:
   6283             return "Null";
   6284         case ZigTypeIdOptional:
   6285             return "Optional";
   6286         case ZigTypeIdErrorUnion:
   6287             return "ErrorUnion";
   6288         case ZigTypeIdErrorSet:
   6289             return "ErrorSet";
   6290         case ZigTypeIdEnum:
   6291             return "Enum";
   6292         case ZigTypeIdUnion:
   6293             return "Union";
   6294         case ZigTypeIdFn:
   6295             return "Fn";
   6296         case ZigTypeIdBoundFn:
   6297             return "BoundFn";
   6298         case ZigTypeIdArgTuple:
   6299             return "ArgTuple";
   6300         case ZigTypeIdOpaque:
   6301             return "Opaque";
   6302         case ZigTypeIdVector:
   6303             return "Vector";
   6304         case ZigTypeIdCoroFrame:
   6305             return "Frame";
   6306         case ZigTypeIdAnyFrame:
   6307             return "AnyFrame";
   6308     }
   6309     zig_unreachable();
   6310 }
   6311 
   6312 LinkLib *create_link_lib(Buf *name) {
   6313     LinkLib *link_lib = allocate<LinkLib>(1);
   6314     link_lib->name = name;
   6315     return link_lib;
   6316 }
   6317 
   6318 LinkLib *add_link_lib(CodeGen *g, Buf *name) {
   6319     bool is_libc = buf_eql_str(name, "c");
   6320 
   6321     if (is_libc && g->libc_link_lib != nullptr)
   6322         return g->libc_link_lib;
   6323 
   6324     for (size_t i = 0; i < g->link_libs_list.length; i += 1) {
   6325         LinkLib *existing_lib = g->link_libs_list.at(i);
   6326         if (buf_eql_buf(existing_lib->name, name)) {
   6327             return existing_lib;
   6328         }
   6329     }
   6330 
   6331     LinkLib *link_lib = create_link_lib(name);
   6332     g->link_libs_list.append(link_lib);
   6333 
   6334     if (is_libc)
   6335         g->libc_link_lib = link_lib;
   6336 
   6337     return link_lib;
   6338 }
   6339 
   6340 ZigType *get_align_amt_type(CodeGen *g) {
   6341     if (g->align_amt_type == nullptr) {
   6342         // according to LLVM the maximum alignment is 1 << 29.
   6343         g->align_amt_type = get_int_type(g, false, 29);
   6344     }
   6345     return g->align_amt_type;
   6346 }
   6347 
   6348 uint32_t type_ptr_hash(const ZigType *ptr) {
   6349     return hash_ptr((void*)ptr);
   6350 }
   6351 
   6352 bool type_ptr_eql(const ZigType *a, const ZigType *b) {
   6353     return a == b;
   6354 }
   6355 
   6356 ConstExprValue *get_builtin_value(CodeGen *codegen, const char *name) {
   6357     Tld *tld = get_container_scope(codegen->compile_var_import)->decl_table.get(buf_create_from_str(name));
   6358     resolve_top_level_decl(codegen, tld, nullptr);
   6359     assert(tld->id == TldIdVar);
   6360     TldVar *tld_var = (TldVar *)tld;
   6361     ConstExprValue *var_value = tld_var->var->const_value;
   6362     assert(var_value != nullptr);
   6363     return var_value;
   6364 }
   6365 
   6366 bool type_is_global_error_set(ZigType *err_set_type) {
   6367     assert(err_set_type->id == ZigTypeIdErrorSet);
   6368     assert(err_set_type->data.error_set.infer_fn == nullptr);
   6369     return err_set_type->data.error_set.err_count == UINT32_MAX;
   6370 }
   6371 
   6372 bool type_can_fail(ZigType *type_entry) {
   6373     return type_entry->id == ZigTypeIdErrorUnion || type_entry->id == ZigTypeIdErrorSet;
   6374 }
   6375 
   6376 bool fn_type_can_fail(FnTypeId *fn_type_id) {
   6377     return type_can_fail(fn_type_id->return_type);
   6378 }
   6379 
   6380 // ErrorNone - result pointer has the type
   6381 // ErrorOverflow - an integer primitive type has too large a bit width
   6382 // ErrorPrimitiveTypeNotFound - result pointer unchanged
   6383 Error get_primitive_type(CodeGen *g, Buf *name, ZigType **result) {
   6384     if (buf_len(name) >= 2) {
   6385         uint8_t first_c = buf_ptr(name)[0];
   6386         if (first_c == 'i' || first_c == 'u') {
   6387             for (size_t i = 1; i < buf_len(name); i += 1) {
   6388                 uint8_t c = buf_ptr(name)[i];
   6389                 if (c < '0' || c > '9') {
   6390                     goto not_integer;
   6391                 }
   6392             }
   6393             bool is_signed = (first_c == 'i');
   6394             unsigned long int bit_count = strtoul(buf_ptr(name) + 1, nullptr, 10);
   6395             // strtoul returns ULONG_MAX on errors, so this comparison catches that as well.
   6396             if (bit_count >= 65536) return ErrorOverflow;
   6397             *result = get_int_type(g, is_signed, bit_count);
   6398             return ErrorNone;
   6399         }
   6400     }
   6401 
   6402 not_integer:
   6403 
   6404     auto primitive_table_entry = g->primitive_type_table.maybe_get(name);
   6405     if (primitive_table_entry == nullptr)
   6406         return ErrorPrimitiveTypeNotFound;
   6407 
   6408     *result = primitive_table_entry->value;
   6409     return ErrorNone;
   6410 }
   6411 
   6412 Error file_fetch(CodeGen *g, Buf *resolved_path, Buf *contents) {
   6413     if (g->enable_cache) {
   6414         return cache_add_file_fetch(&g->cache_hash, resolved_path, contents);
   6415     } else {
   6416         return os_fetch_file_path(resolved_path, contents);
   6417     }
   6418 }
   6419 
   6420 static X64CABIClass type_windows_abi_x86_64_class(CodeGen *g, ZigType *ty, size_t ty_size) {
   6421     // https://docs.microsoft.com/en-gb/cpp/build/x64-calling-convention?view=vs-2017
   6422     switch (ty->id) {
   6423         case ZigTypeIdEnum:
   6424         case ZigTypeIdInt:
   6425         case ZigTypeIdBool:
   6426             return X64CABIClass_INTEGER;
   6427         case ZigTypeIdFloat:
   6428         case ZigTypeIdVector:
   6429             return X64CABIClass_SSE;
   6430         case ZigTypeIdStruct:
   6431         case ZigTypeIdUnion: {
   6432             if (ty_size <= 8)
   6433                 return X64CABIClass_INTEGER;
   6434             return X64CABIClass_MEMORY;
   6435         }
   6436         default:
   6437             return X64CABIClass_Unknown;
   6438     }
   6439 }
   6440 
   6441 static X64CABIClass type_system_V_abi_x86_64_class(CodeGen *g, ZigType *ty, size_t ty_size) {
   6442     switch (ty->id) {
   6443         case ZigTypeIdEnum:
   6444         case ZigTypeIdInt:
   6445         case ZigTypeIdBool:
   6446             return X64CABIClass_INTEGER;
   6447         case ZigTypeIdFloat:
   6448         case ZigTypeIdVector:
   6449             return X64CABIClass_SSE;
   6450         case ZigTypeIdStruct: {
   6451             // "If the size of an object is larger than four eightbytes, or it contains unaligned
   6452             // fields, it has class MEMORY"
   6453             if (ty_size > 32)
   6454                 return X64CABIClass_MEMORY;
   6455             if (ty->data.structure.layout != ContainerLayoutExtern) {
   6456                 // TODO determine whether packed structs have any unaligned fields
   6457                 return X64CABIClass_Unknown;
   6458             }
   6459             // "If the size of the aggregate exceeds two eightbytes and the first eight-
   6460             // byte isn’t SSE or any other eightbyte isn’t SSEUP, the whole argument
   6461             // is passed in memory."
   6462             if (ty_size > 16) {
   6463                 // Zig doesn't support vectors and large fp registers yet, so this will always
   6464                 // be memory.
   6465                 return X64CABIClass_MEMORY;
   6466             }
   6467             X64CABIClass working_class = X64CABIClass_Unknown;
   6468             for (uint32_t i = 0; i < ty->data.structure.src_field_count; i += 1) {
   6469                 X64CABIClass field_class = type_c_abi_x86_64_class(g, ty->data.structure.fields->type_entry);
   6470                 if (field_class == X64CABIClass_Unknown)
   6471                     return X64CABIClass_Unknown;
   6472                 if (i == 0 || field_class == X64CABIClass_MEMORY || working_class == X64CABIClass_SSE) {
   6473                     working_class = field_class;
   6474                 }
   6475             }
   6476             return working_class;
   6477         }
   6478         case ZigTypeIdUnion: {
   6479             // "If the size of an object is larger than four eightbytes, or it contains unaligned
   6480             // fields, it has class MEMORY"
   6481             if (ty_size > 32)
   6482                 return X64CABIClass_MEMORY;
   6483             if (ty->data.unionation.layout != ContainerLayoutExtern)
   6484                 return X64CABIClass_MEMORY;
   6485             // "If the size of the aggregate exceeds two eightbytes and the first eight-
   6486             // byte isn’t SSE or any other eightbyte isn’t SSEUP, the whole argument
   6487             // is passed in memory."
   6488             if (ty_size > 16) {
   6489                 // Zig doesn't support vectors and large fp registers yet, so this will always
   6490                 // be memory.
   6491                 return X64CABIClass_MEMORY;
   6492             }
   6493             X64CABIClass working_class = X64CABIClass_Unknown;
   6494             for (uint32_t i = 0; i < ty->data.unionation.src_field_count; i += 1) {
   6495                 X64CABIClass field_class = type_c_abi_x86_64_class(g, ty->data.unionation.fields->type_entry);
   6496                 if (field_class == X64CABIClass_Unknown)
   6497                     return X64CABIClass_Unknown;
   6498                 if (i == 0 || field_class == X64CABIClass_MEMORY || working_class == X64CABIClass_SSE) {
   6499                     working_class = field_class;
   6500                 }
   6501             }
   6502             return working_class;
   6503         }
   6504         default:
   6505             return X64CABIClass_Unknown;
   6506     }
   6507 }
   6508 
   6509 X64CABIClass type_c_abi_x86_64_class(CodeGen *g, ZigType *ty) {
   6510     const size_t ty_size = type_size(g, ty);
   6511     if (get_codegen_ptr_type(ty) != nullptr)
   6512         return X64CABIClass_INTEGER;
   6513 
   6514     if (g->zig_target->os == OsWindows || g->zig_target->os == OsUefi) {
   6515         return type_windows_abi_x86_64_class(g, ty, ty_size);
   6516     } else {
   6517         return type_system_V_abi_x86_64_class(g, ty, ty_size);
   6518     }
   6519 }
   6520 
   6521 // NOTE this does not depend on x86_64
   6522 bool type_is_c_abi_int(CodeGen *g, ZigType *ty) {
   6523     return (ty->id == ZigTypeIdInt ||
   6524         ty->id == ZigTypeIdFloat ||
   6525         ty->id == ZigTypeIdBool ||
   6526         ty->id == ZigTypeIdEnum ||
   6527         ty->id == ZigTypeIdVoid ||
   6528         ty->id == ZigTypeIdUnreachable ||
   6529         get_codegen_ptr_type(ty) != nullptr);
   6530 }
   6531 
   6532 uint32_t get_host_int_bytes(CodeGen *g, ZigType *struct_type, TypeStructField *field) {
   6533     assert(struct_type->id == ZigTypeIdStruct);
   6534     assert(type_is_resolved(struct_type, ResolveStatusSizeKnown));
   6535     if (struct_type->data.structure.host_int_bytes == nullptr)
   6536         return 0;
   6537     return struct_type->data.structure.host_int_bytes[field->gen_index];
   6538 }
   6539 
   6540 Error ensure_const_val_repr(IrAnalyze *ira, CodeGen *codegen, AstNode *source_node,
   6541         ConstExprValue *const_val, ZigType *wanted_type)
   6542 {
   6543     ConstExprValue ptr_val = {};
   6544     ptr_val.special = ConstValSpecialStatic;
   6545     ptr_val.type = get_pointer_to_type(codegen, wanted_type, true);
   6546     ptr_val.data.x_ptr.mut = ConstPtrMutComptimeConst;
   6547     ptr_val.data.x_ptr.special = ConstPtrSpecialRef;
   6548     ptr_val.data.x_ptr.data.ref.pointee = const_val;
   6549     if (const_ptr_pointee(ira, codegen, &ptr_val, source_node) == nullptr)
   6550         return ErrorSemanticAnalyzeFail;
   6551 
   6552     return ErrorNone;
   6553 }
   6554 
   6555 const char *container_string(ContainerKind kind) {
   6556     switch (kind) {
   6557         case ContainerKindEnum: return "enum";
   6558         case ContainerKindStruct: return "struct";
   6559         case ContainerKindUnion: return "union";
   6560     }
   6561     zig_unreachable();
   6562 }
   6563 
   6564 bool ptr_allows_addr_zero(ZigType *ptr_type) {
   6565     if (ptr_type->id == ZigTypeIdPointer) {
   6566         return ptr_type->data.pointer.allow_zero;
   6567     } else if (ptr_type->id == ZigTypeIdOptional) {
   6568         return true;
   6569     }
   6570     return false;
   6571 }
   6572 
   6573 void emit_error_notes_for_ref_stack(CodeGen *g, ErrorMsg *msg) {
   6574     size_t i = g->tld_ref_source_node_stack.length;
   6575     for (;;) {
   6576         if (i == 0)
   6577             break;
   6578         i -= 1;
   6579         AstNode *source_node = g->tld_ref_source_node_stack.at(i);
   6580         if (source_node) {
   6581             msg = add_error_note(g, msg, source_node, buf_sprintf("referenced here"));
   6582         }
   6583     }
   6584 }
   6585 
   6586 Buf *type_bare_name(ZigType *type_entry) {
   6587     if (is_slice(type_entry)) {
   6588         return &type_entry->name;
   6589     } else if (is_container(type_entry)) {
   6590         return get_container_scope(type_entry)->bare_name;
   6591     } else if (type_entry->id == ZigTypeIdOpaque) {
   6592         return type_entry->data.opaque.bare_name;
   6593     } else {
   6594         return &type_entry->name;
   6595     }
   6596 }
   6597 
   6598 // TODO this will have to be more clever, probably using the full name
   6599 // and replacing '.' with '_' or something like that
   6600 Buf *type_h_name(ZigType *t) {
   6601     return type_bare_name(t);
   6602 }
   6603 
   6604 static void resolve_llvm_types_slice(CodeGen *g, ZigType *type, ResolveStatus wanted_resolve_status) {
   6605     if (type->data.structure.resolve_status >= wanted_resolve_status) return;
   6606 
   6607     ZigType *ptr_type = type->data.structure.fields[slice_ptr_index].type_entry;
   6608     ZigType *child_type = ptr_type->data.pointer.child_type;
   6609     ZigType *usize_type = g->builtin_types.entry_usize;
   6610 
   6611     bool done = false;
   6612     if (ptr_type->data.pointer.is_const || ptr_type->data.pointer.is_volatile ||
   6613         ptr_type->data.pointer.explicit_alignment != 0 || ptr_type->data.pointer.allow_zero)
   6614     {
   6615         ZigType *peer_ptr_type = get_pointer_to_type_extra(g, child_type, false, false,
   6616                 PtrLenUnknown, 0, 0, 0, false);
   6617         ZigType *peer_slice_type = get_slice_type(g, peer_ptr_type);
   6618 
   6619         assertNoError(type_resolve(g, peer_slice_type, wanted_resolve_status));
   6620         type->llvm_type = peer_slice_type->llvm_type;
   6621         type->llvm_di_type = peer_slice_type->llvm_di_type;
   6622         type->data.structure.resolve_status = peer_slice_type->data.structure.resolve_status;
   6623         done = true;
   6624     }
   6625 
   6626     // If the child type is []const T then we need to make sure the type ref
   6627     // and debug info is the same as if the child type were []T.
   6628     if (is_slice(child_type)) {
   6629         ZigType *child_ptr_type = child_type->data.structure.fields[slice_ptr_index].type_entry;
   6630         assert(child_ptr_type->id == ZigTypeIdPointer);
   6631         if (child_ptr_type->data.pointer.is_const || child_ptr_type->data.pointer.is_volatile ||
   6632             child_ptr_type->data.pointer.explicit_alignment != 0 || child_ptr_type->data.pointer.allow_zero)
   6633         {
   6634             ZigType *grand_child_type = child_ptr_type->data.pointer.child_type;
   6635             ZigType *bland_child_ptr_type = get_pointer_to_type_extra(g, grand_child_type, false, false,
   6636                     PtrLenUnknown, 0, 0, 0, false);
   6637             ZigType *bland_child_slice = get_slice_type(g, bland_child_ptr_type);
   6638             ZigType *peer_ptr_type = get_pointer_to_type_extra(g, bland_child_slice, false, false,
   6639                     PtrLenUnknown, 0, 0, 0, false);
   6640             ZigType *peer_slice_type = get_slice_type(g, peer_ptr_type);
   6641 
   6642             assertNoError(type_resolve(g, peer_slice_type, wanted_resolve_status));
   6643             type->llvm_type = peer_slice_type->llvm_type;
   6644             type->llvm_di_type = peer_slice_type->llvm_di_type;
   6645             type->data.structure.resolve_status = peer_slice_type->data.structure.resolve_status;
   6646             done = true;
   6647         }
   6648     }
   6649 
   6650     if (done) return;
   6651 
   6652     LLVMTypeRef usize_llvm_type = get_llvm_type(g, usize_type);
   6653     ZigLLVMDIType *usize_llvm_di_type = get_llvm_di_type(g, usize_type);
   6654     ZigLLVMDIScope *compile_unit_scope = ZigLLVMCompileUnitToScope(g->compile_unit);
   6655     ZigLLVMDIFile *di_file = nullptr;
   6656     unsigned line = 0;
   6657 
   6658     if (type->data.structure.resolve_status < ResolveStatusLLVMFwdDecl) {
   6659         type->llvm_type = LLVMStructCreateNamed(LLVMGetGlobalContext(), buf_ptr(&type->name));
   6660 
   6661         type->llvm_di_type = ZigLLVMCreateReplaceableCompositeType(g->dbuilder,
   6662             ZigLLVMTag_DW_structure_type(), buf_ptr(&type->name),
   6663             compile_unit_scope, di_file, line);
   6664 
   6665         type->data.structure.resolve_status = ResolveStatusLLVMFwdDecl;
   6666         if (ResolveStatusLLVMFwdDecl >= wanted_resolve_status) return;
   6667     }
   6668 
   6669     if (!type_has_bits(child_type)) {
   6670         LLVMTypeRef element_types[] = {
   6671             usize_llvm_type,
   6672         };
   6673         LLVMStructSetBody(type->llvm_type, element_types, 1, false);
   6674 
   6675         uint64_t len_debug_size_in_bits = usize_type->size_in_bits;
   6676         uint64_t len_debug_align_in_bits = 8*usize_type->abi_align;
   6677         uint64_t len_offset_in_bits = 8*LLVMOffsetOfElement(g->target_data_ref, type->llvm_type, 0);
   6678 
   6679         uint64_t debug_size_in_bits = type->size_in_bits;
   6680         uint64_t debug_align_in_bits = 8*type->abi_align;
   6681 
   6682         ZigLLVMDIType *di_element_types[] = {
   6683             ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(type->llvm_di_type),
   6684                     "len", di_file, line,
   6685                     len_debug_size_in_bits,
   6686                     len_debug_align_in_bits,
   6687                     len_offset_in_bits,
   6688                     ZigLLVM_DIFlags_Zero,
   6689                     usize_llvm_di_type),
   6690         };
   6691         ZigLLVMDIType *replacement_di_type = ZigLLVMCreateDebugStructType(g->dbuilder,
   6692                 compile_unit_scope,
   6693                 buf_ptr(&type->name),
   6694                 di_file, line, debug_size_in_bits, debug_align_in_bits,
   6695                 ZigLLVM_DIFlags_Zero,
   6696                 nullptr, di_element_types, 1, 0, nullptr, "");
   6697 
   6698         ZigLLVMReplaceTemporary(g->dbuilder, type->llvm_di_type, replacement_di_type);
   6699         type->llvm_di_type = replacement_di_type;
   6700         type->data.structure.resolve_status = ResolveStatusLLVMFull;
   6701         return;
   6702     }
   6703 
   6704     LLVMTypeRef element_types[2];
   6705     element_types[slice_ptr_index] = get_llvm_type(g, ptr_type);
   6706     element_types[slice_len_index] = get_llvm_type(g, g->builtin_types.entry_usize);
   6707     if (type->data.structure.resolve_status >= wanted_resolve_status) return;
   6708     LLVMStructSetBody(type->llvm_type, element_types, 2, false);
   6709 
   6710     uint64_t ptr_debug_size_in_bits = ptr_type->size_in_bits;
   6711     uint64_t ptr_debug_align_in_bits = 8*ptr_type->abi_align;
   6712     uint64_t ptr_offset_in_bits = 8*LLVMOffsetOfElement(g->target_data_ref, type->llvm_type, 0);
   6713 
   6714     uint64_t len_debug_size_in_bits = usize_type->size_in_bits;
   6715     uint64_t len_debug_align_in_bits = 8*usize_type->abi_align;
   6716     uint64_t len_offset_in_bits = 8*LLVMOffsetOfElement(g->target_data_ref, type->llvm_type, 1);
   6717 
   6718     uint64_t debug_size_in_bits = type->size_in_bits;
   6719     uint64_t debug_align_in_bits = 8*type->abi_align;
   6720 
   6721     ZigLLVMDIType *di_element_types[] = {
   6722         ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(type->llvm_di_type),
   6723                 "ptr", di_file, line,
   6724                 ptr_debug_size_in_bits,
   6725                 ptr_debug_align_in_bits,
   6726                 ptr_offset_in_bits,
   6727                 ZigLLVM_DIFlags_Zero, get_llvm_di_type(g, ptr_type)),
   6728         ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(type->llvm_di_type),
   6729                 "len", di_file, line,
   6730                 len_debug_size_in_bits,
   6731                 len_debug_align_in_bits,
   6732                 len_offset_in_bits,
   6733                 ZigLLVM_DIFlags_Zero, usize_llvm_di_type),
   6734     };
   6735     ZigLLVMDIType *replacement_di_type = ZigLLVMCreateDebugStructType(g->dbuilder,
   6736             compile_unit_scope,
   6737             buf_ptr(&type->name),
   6738             di_file, line, debug_size_in_bits, debug_align_in_bits,
   6739             ZigLLVM_DIFlags_Zero,
   6740             nullptr, di_element_types, 2, 0, nullptr, "");
   6741 
   6742     ZigLLVMReplaceTemporary(g->dbuilder, type->llvm_di_type, replacement_di_type);
   6743     type->llvm_di_type = replacement_di_type;
   6744     type->data.structure.resolve_status = ResolveStatusLLVMFull;
   6745 }
   6746 
   6747 static void resolve_llvm_types_struct(CodeGen *g, ZigType *struct_type, ResolveStatus wanted_resolve_status,
   6748         ZigType *coro_frame_type)
   6749 {
   6750     assert(struct_type->id == ZigTypeIdStruct);
   6751     assert(struct_type->data.structure.resolve_status != ResolveStatusInvalid);
   6752     assert(struct_type->data.structure.resolve_status >= ResolveStatusSizeKnown);
   6753     assert(struct_type->data.structure.fields || struct_type->data.structure.src_field_count == 0);
   6754     if (struct_type->data.structure.resolve_status >= wanted_resolve_status) return;
   6755 
   6756     AstNode *decl_node = struct_type->data.structure.decl_node;
   6757     ZigLLVMDIFile *di_file;
   6758     ZigLLVMDIScope *di_scope;
   6759     unsigned line;
   6760     if (decl_node != nullptr) {
   6761         assert(decl_node->type == NodeTypeContainerDecl);
   6762         Scope *scope = &struct_type->data.structure.decls_scope->base;
   6763         ZigType *import = get_scope_import(scope);
   6764         di_file = import->data.structure.root_struct->di_file;
   6765         di_scope = ZigLLVMFileToScope(di_file);
   6766         line = decl_node->line + 1;
   6767     } else {
   6768         di_file = nullptr;
   6769         di_scope = ZigLLVMCompileUnitToScope(g->compile_unit);
   6770         line = 0;
   6771     }
   6772 
   6773     if (struct_type->data.structure.resolve_status < ResolveStatusLLVMFwdDecl) {
   6774         struct_type->llvm_type = type_has_bits(struct_type) ?
   6775             LLVMStructCreateNamed(LLVMGetGlobalContext(), buf_ptr(&struct_type->name)) : LLVMVoidType();
   6776         unsigned dwarf_kind = ZigLLVMTag_DW_structure_type();
   6777         struct_type->llvm_di_type = ZigLLVMCreateReplaceableCompositeType(g->dbuilder,
   6778             dwarf_kind, buf_ptr(&struct_type->name),
   6779             di_scope, di_file, line);
   6780 
   6781         struct_type->data.structure.resolve_status = ResolveStatusLLVMFwdDecl;
   6782         if (ResolveStatusLLVMFwdDecl >= wanted_resolve_status) return;
   6783     }
   6784 
   6785     size_t field_count = struct_type->data.structure.src_field_count;
   6786     size_t gen_field_count = struct_type->data.structure.gen_field_count;
   6787     LLVMTypeRef *element_types = allocate<LLVMTypeRef>(gen_field_count);
   6788 
   6789     size_t gen_field_index = 0;
   6790     bool packed = (struct_type->data.structure.layout == ContainerLayoutPacked);
   6791     size_t packed_bits_offset = 0;
   6792     size_t first_packed_bits_offset_misalign = SIZE_MAX;
   6793     size_t debug_field_count = 0;
   6794 
   6795     // trigger all the recursive get_llvm_type calls
   6796     for (size_t i = 0; i < field_count; i += 1) {
   6797         TypeStructField *type_struct_field = &struct_type->data.structure.fields[i];
   6798         ZigType *field_type = type_struct_field->type_entry;
   6799         if (!type_has_bits(field_type))
   6800             continue;
   6801         (void)get_llvm_type(g, field_type);
   6802         if (struct_type->data.structure.resolve_status >= wanted_resolve_status) return;
   6803     }
   6804 
   6805     for (size_t i = 0; i < field_count; i += 1) {
   6806         TypeStructField *type_struct_field = &struct_type->data.structure.fields[i];
   6807         ZigType *field_type = type_struct_field->type_entry;
   6808 
   6809         if (!type_has_bits(field_type))
   6810             continue;
   6811 
   6812         if (packed) {
   6813             size_t field_size_in_bits = type_size_bits(g, field_type);
   6814             size_t next_packed_bits_offset = packed_bits_offset + field_size_in_bits;
   6815 
   6816             if (first_packed_bits_offset_misalign != SIZE_MAX) {
   6817                 // this field is not byte-aligned; it is part of the previous field with a bit offset
   6818 
   6819                 size_t full_bit_count = next_packed_bits_offset - first_packed_bits_offset_misalign;
   6820                 size_t full_abi_size = get_abi_size_bytes(full_bit_count, g->pointer_size_bytes);
   6821                 if (full_abi_size * 8 == full_bit_count) {
   6822                     // next field recovers ABI alignment
   6823                     element_types[gen_field_index] = LLVMIntType((unsigned)(full_bit_count));
   6824                     gen_field_index += 1;
   6825 
   6826                     first_packed_bits_offset_misalign = SIZE_MAX;
   6827                 }
   6828             } else if (get_abi_size_bytes(field_type->size_in_bits, g->pointer_size_bytes) * 8 != field_size_in_bits) {
   6829                 first_packed_bits_offset_misalign = packed_bits_offset;
   6830             } else {
   6831                 // This is a byte-aligned field (both start and end) in a packed struct.
   6832                 element_types[gen_field_index] = get_llvm_type(g, field_type);
   6833                 gen_field_index += 1;
   6834             }
   6835             packed_bits_offset = next_packed_bits_offset;
   6836         } else {
   6837             LLVMTypeRef llvm_type;
   6838             if (i == 0 && coro_frame_type != nullptr) {
   6839                 assert(coro_frame_type->id == ZigTypeIdCoroFrame);
   6840                 assert(field_type->id == ZigTypeIdFn);
   6841                 resolve_llvm_types_fn(g, coro_frame_type->data.frame.fn);
   6842                 llvm_type = LLVMPointerType(coro_frame_type->data.frame.fn->raw_type_ref, 0);
   6843             } else {
   6844                 llvm_type = get_llvm_type(g, field_type);
   6845             }
   6846             element_types[gen_field_index] = llvm_type;
   6847 
   6848             gen_field_index += 1;
   6849         }
   6850         debug_field_count += 1;
   6851     }
   6852     if (first_packed_bits_offset_misalign != SIZE_MAX) {
   6853         size_t full_bit_count = packed_bits_offset - first_packed_bits_offset_misalign;
   6854         size_t full_abi_size = get_abi_size_bytes(full_bit_count, g->pointer_size_bytes);
   6855         element_types[gen_field_index] = LLVMIntType((unsigned)full_abi_size * 8);
   6856         gen_field_index += 1;
   6857     }
   6858 
   6859     if (type_has_bits(struct_type)) {
   6860         LLVMStructSetBody(struct_type->llvm_type, element_types, (unsigned)gen_field_count, packed);
   6861     }
   6862 
   6863     ZigLLVMDIType **di_element_types = allocate<ZigLLVMDIType*>(debug_field_count);
   6864     size_t debug_field_index = 0;
   6865     for (size_t i = 0; i < field_count; i += 1) {
   6866         TypeStructField *type_struct_field = &struct_type->data.structure.fields[i];
   6867         size_t gen_field_index = type_struct_field->gen_index;
   6868         if (gen_field_index == SIZE_MAX) {
   6869             continue;
   6870         }
   6871 
   6872         ZigType *field_type = type_struct_field->type_entry;
   6873 
   6874         // if the field is a function, actually the debug info should be a pointer.
   6875         ZigLLVMDIType *field_di_type;
   6876         if (field_type->id == ZigTypeIdFn) {
   6877             ZigType *field_ptr_type = get_pointer_to_type(g, field_type, true);
   6878             uint64_t debug_size_in_bits = 8*LLVMStoreSizeOfType(g->target_data_ref, get_llvm_type(g, field_ptr_type));
   6879             uint64_t debug_align_in_bits = 8*LLVMABISizeOfType(g->target_data_ref, get_llvm_type(g, field_ptr_type));
   6880             field_di_type = ZigLLVMCreateDebugPointerType(g->dbuilder, get_llvm_di_type(g, field_type),
   6881                     debug_size_in_bits, debug_align_in_bits, buf_ptr(&field_ptr_type->name));
   6882         } else {
   6883             field_di_type = get_llvm_di_type(g, field_type);
   6884         }
   6885 
   6886         uint64_t debug_size_in_bits;
   6887         uint64_t debug_align_in_bits;
   6888         uint64_t debug_offset_in_bits;
   6889         if (packed) {
   6890             debug_size_in_bits = type_struct_field->type_entry->size_in_bits;
   6891             debug_align_in_bits = 8 * type_struct_field->type_entry->abi_align;
   6892             debug_offset_in_bits = 8 * type_struct_field->offset + type_struct_field->bit_offset_in_host;
   6893         } else {
   6894             debug_size_in_bits = 8 * get_store_size_bytes(field_type->size_in_bits);
   6895             debug_align_in_bits = 8 * field_type->abi_align;
   6896             debug_offset_in_bits = 8 * type_struct_field->offset;
   6897         }
   6898         unsigned line;
   6899         if (decl_node != nullptr) {
   6900             AstNode *field_node = decl_node->data.container_decl.fields.at(i);
   6901             line = field_node->line + 1;
   6902         } else {
   6903             line = 0;
   6904         }
   6905         di_element_types[debug_field_index] = ZigLLVMCreateDebugMemberType(g->dbuilder,
   6906                 ZigLLVMTypeToScope(struct_type->llvm_di_type), buf_ptr(type_struct_field->name),
   6907                 di_file, line,
   6908                 debug_size_in_bits,
   6909                 debug_align_in_bits,
   6910                 debug_offset_in_bits,
   6911                 ZigLLVM_DIFlags_Zero, field_di_type);
   6912         assert(di_element_types[debug_field_index]);
   6913         debug_field_index += 1;
   6914     }
   6915 
   6916     uint64_t debug_size_in_bits = 8*get_store_size_bytes(struct_type->size_in_bits);
   6917     uint64_t debug_align_in_bits = 8*struct_type->abi_align;
   6918     ZigLLVMDIType *replacement_di_type = ZigLLVMCreateDebugStructType(g->dbuilder,
   6919             di_scope,
   6920             buf_ptr(&struct_type->name),
   6921             di_file, line,
   6922             debug_size_in_bits,
   6923             debug_align_in_bits,
   6924             ZigLLVM_DIFlags_Zero,
   6925             nullptr, di_element_types, (int)debug_field_count, 0, nullptr, "");
   6926 
   6927     ZigLLVMReplaceTemporary(g->dbuilder, struct_type->llvm_di_type, replacement_di_type);
   6928     struct_type->llvm_di_type = replacement_di_type;
   6929     struct_type->data.structure.resolve_status = ResolveStatusLLVMFull;
   6930 }
   6931 
   6932 static void resolve_llvm_types_enum(CodeGen *g, ZigType *enum_type) {
   6933     assert(!enum_type->data.enumeration.is_invalid);
   6934     assert(enum_type->data.enumeration.complete);
   6935     if (enum_type->llvm_di_type != nullptr) return;
   6936 
   6937     Scope *scope = &enum_type->data.enumeration.decls_scope->base;
   6938     ZigType *import = get_scope_import(scope);
   6939     AstNode *decl_node = enum_type->data.enumeration.decl_node;
   6940 
   6941     if (!type_has_bits(enum_type)) {
   6942         enum_type->llvm_type = g->builtin_types.entry_void->llvm_type;
   6943 
   6944         uint64_t debug_size_in_bits = 0;
   6945         uint64_t debug_align_in_bits = 0;
   6946         ZigLLVMDIType **di_element_types = nullptr;
   6947         size_t debug_field_count = 0;
   6948         enum_type->llvm_di_type = ZigLLVMCreateDebugStructType(g->dbuilder,
   6949                 ZigLLVMFileToScope(import->data.structure.root_struct->di_file),
   6950                 buf_ptr(&enum_type->name),
   6951                 import->data.structure.root_struct->di_file, (unsigned)(decl_node->line + 1),
   6952                 debug_size_in_bits,
   6953                 debug_align_in_bits,
   6954                 ZigLLVM_DIFlags_Zero,
   6955                 nullptr, di_element_types, (int)debug_field_count, 0, nullptr, "");
   6956         return;
   6957     }
   6958 
   6959     uint32_t field_count = enum_type->data.enumeration.src_field_count;
   6960 
   6961     assert(enum_type->data.enumeration.fields);
   6962     ZigLLVMDIEnumerator **di_enumerators = allocate<ZigLLVMDIEnumerator*>(field_count);
   6963 
   6964     for (uint32_t i = 0; i < field_count; i += 1) {
   6965         TypeEnumField *enum_field = &enum_type->data.enumeration.fields[i];
   6966 
   6967         // TODO send patch to LLVM to support APInt in createEnumerator instead of int64_t
   6968         // http://lists.llvm.org/pipermail/llvm-dev/2017-December/119456.html
   6969         di_enumerators[i] = ZigLLVMCreateDebugEnumerator(g->dbuilder, buf_ptr(enum_field->name),
   6970                 bigint_as_signed(&enum_field->value));
   6971     }
   6972 
   6973     ZigType *tag_int_type = enum_type->data.enumeration.tag_int_type;
   6974     enum_type->llvm_type = get_llvm_type(g, tag_int_type);
   6975 
   6976     // create debug type for tag
   6977     uint64_t tag_debug_size_in_bits = tag_int_type->size_in_bits;
   6978     uint64_t tag_debug_align_in_bits = 8*tag_int_type->abi_align;
   6979     ZigLLVMDIType *tag_di_type = ZigLLVMCreateDebugEnumerationType(g->dbuilder,
   6980             ZigLLVMFileToScope(import->data.structure.root_struct->di_file), buf_ptr(&enum_type->name),
   6981             import->data.structure.root_struct->di_file, (unsigned)(decl_node->line + 1),
   6982             tag_debug_size_in_bits,
   6983             tag_debug_align_in_bits,
   6984             di_enumerators, field_count,
   6985             get_llvm_di_type(g, tag_int_type), "");
   6986 
   6987     enum_type->llvm_di_type = tag_di_type;
   6988 }
   6989 
   6990 static void resolve_llvm_types_union(CodeGen *g, ZigType *union_type, ResolveStatus wanted_resolve_status) {
   6991     if (union_type->data.unionation.resolve_status >= wanted_resolve_status) return;
   6992 
   6993     ZigType *most_aligned_union_member = union_type->data.unionation.most_aligned_union_member;
   6994     ZigType *tag_type = union_type->data.unionation.tag_type;
   6995     if (most_aligned_union_member == nullptr) {
   6996         union_type->llvm_type = get_llvm_type(g, tag_type);
   6997         union_type->llvm_di_type = get_llvm_di_type(g, tag_type);
   6998         union_type->data.unionation.resolve_status = ResolveStatusLLVMFull;
   6999         return;
   7000     }
   7001 
   7002     Scope *scope = &union_type->data.unionation.decls_scope->base;
   7003     ZigType *import = get_scope_import(scope);
   7004     AstNode *decl_node = union_type->data.unionation.decl_node;
   7005 
   7006     if (union_type->data.unionation.resolve_status < ResolveStatusLLVMFwdDecl) {
   7007         union_type->llvm_type = LLVMStructCreateNamed(LLVMGetGlobalContext(), buf_ptr(&union_type->name));
   7008         size_t line = decl_node ? decl_node->line : 0;
   7009         unsigned dwarf_kind = ZigLLVMTag_DW_structure_type();
   7010         union_type->llvm_di_type = ZigLLVMCreateReplaceableCompositeType(g->dbuilder,
   7011             dwarf_kind, buf_ptr(&union_type->name),
   7012             ZigLLVMFileToScope(import->data.structure.root_struct->di_file),
   7013             import->data.structure.root_struct->di_file, (unsigned)(line + 1));
   7014 
   7015         union_type->data.unionation.resolve_status = ResolveStatusLLVMFwdDecl;
   7016         if (ResolveStatusLLVMFwdDecl >= wanted_resolve_status) return;
   7017     }
   7018 
   7019     uint32_t gen_field_count = union_type->data.unionation.gen_field_count;
   7020     ZigLLVMDIType **union_inner_di_types = allocate<ZigLLVMDIType*>(gen_field_count);
   7021     uint32_t field_count = union_type->data.unionation.src_field_count;
   7022     for (uint32_t i = 0; i < field_count; i += 1) {
   7023         TypeUnionField *union_field = &union_type->data.unionation.fields[i];
   7024         if (!type_has_bits(union_field->type_entry))
   7025             continue;
   7026 
   7027         ZigLLVMDIType *field_di_type = get_llvm_di_type(g, union_field->type_entry);
   7028         if (union_type->data.unionation.resolve_status >= wanted_resolve_status) return;
   7029 
   7030         uint64_t store_size_in_bits = union_field->type_entry->size_in_bits;
   7031         uint64_t abi_align_in_bits = 8*union_field->type_entry->abi_align;
   7032         AstNode *field_node = decl_node->data.container_decl.fields.at(i);
   7033         union_inner_di_types[union_field->gen_index] = ZigLLVMCreateDebugMemberType(g->dbuilder,
   7034                 ZigLLVMTypeToScope(union_type->llvm_di_type), buf_ptr(union_field->enum_field->name),
   7035                 import->data.structure.root_struct->di_file, (unsigned)(field_node->line + 1),
   7036                 store_size_in_bits,
   7037                 abi_align_in_bits,
   7038                 0,
   7039                 ZigLLVM_DIFlags_Zero, field_di_type);
   7040 
   7041     }
   7042 
   7043     if (tag_type == nullptr || !type_has_bits(tag_type)) {
   7044         assert(most_aligned_union_member != nullptr);
   7045 
   7046         size_t padding_bytes = union_type->data.unionation.union_abi_size - most_aligned_union_member->abi_size;
   7047         if (padding_bytes > 0) {
   7048             ZigType *u8_type = get_int_type(g, false, 8);
   7049             ZigType *padding_array = get_array_type(g, u8_type, padding_bytes);
   7050             LLVMTypeRef union_element_types[] = {
   7051                 most_aligned_union_member->llvm_type,
   7052                 get_llvm_type(g, padding_array),
   7053             };
   7054             LLVMStructSetBody(union_type->llvm_type, union_element_types, 2, false);
   7055         } else {
   7056             LLVMStructSetBody(union_type->llvm_type, &most_aligned_union_member->llvm_type, 1, false);
   7057         }
   7058         union_type->data.unionation.union_llvm_type = union_type->llvm_type;
   7059         union_type->data.unionation.gen_tag_index = SIZE_MAX;
   7060         union_type->data.unionation.gen_union_index = SIZE_MAX;
   7061 
   7062         // create debug type for union
   7063         ZigLLVMDIType *replacement_di_type = ZigLLVMCreateDebugUnionType(g->dbuilder,
   7064             ZigLLVMFileToScope(import->data.structure.root_struct->di_file), buf_ptr(&union_type->name),
   7065             import->data.structure.root_struct->di_file, (unsigned)(decl_node->line + 1),
   7066             union_type->data.unionation.union_abi_size * 8,
   7067             most_aligned_union_member->abi_align * 8,
   7068             ZigLLVM_DIFlags_Zero, union_inner_di_types,
   7069             gen_field_count, 0, "");
   7070 
   7071         ZigLLVMReplaceTemporary(g->dbuilder, union_type->llvm_di_type, replacement_di_type);
   7072         union_type->llvm_di_type = replacement_di_type;
   7073         union_type->data.unionation.resolve_status = ResolveStatusLLVMFull;
   7074         return;
   7075     }
   7076 
   7077     LLVMTypeRef union_type_ref;
   7078     size_t padding_bytes = union_type->data.unionation.union_abi_size - most_aligned_union_member->abi_size;
   7079     if (padding_bytes == 0) {
   7080         union_type_ref = get_llvm_type(g, most_aligned_union_member);
   7081     } else {
   7082         ZigType *u8_type = get_int_type(g, false, 8);
   7083         ZigType *padding_array = get_array_type(g, u8_type, padding_bytes);
   7084         LLVMTypeRef union_element_types[] = {
   7085             get_llvm_type(g, most_aligned_union_member),
   7086             get_llvm_type(g, padding_array),
   7087         };
   7088         union_type_ref = LLVMStructType(union_element_types, 2, false);
   7089     }
   7090     union_type->data.unionation.union_llvm_type = union_type_ref;
   7091 
   7092     LLVMTypeRef root_struct_element_types[2];
   7093     root_struct_element_types[union_type->data.unionation.gen_tag_index] = get_llvm_type(g, tag_type);
   7094     root_struct_element_types[union_type->data.unionation.gen_union_index] = union_type_ref;
   7095     LLVMStructSetBody(union_type->llvm_type, root_struct_element_types, 2, false);
   7096 
   7097     // create debug type for union
   7098     ZigLLVMDIType *union_di_type = ZigLLVMCreateDebugUnionType(g->dbuilder,
   7099             ZigLLVMTypeToScope(union_type->llvm_di_type), "AnonUnion",
   7100             import->data.structure.root_struct->di_file, (unsigned)(decl_node->line + 1),
   7101             most_aligned_union_member->size_in_bits, 8*most_aligned_union_member->abi_align,
   7102             ZigLLVM_DIFlags_Zero, union_inner_di_types, gen_field_count, 0, "");
   7103 
   7104     uint64_t union_offset_in_bits = 8*LLVMOffsetOfElement(g->target_data_ref, union_type->llvm_type,
   7105             union_type->data.unionation.gen_union_index);
   7106     uint64_t tag_offset_in_bits = 8*LLVMOffsetOfElement(g->target_data_ref, union_type->llvm_type,
   7107             union_type->data.unionation.gen_tag_index);
   7108 
   7109     ZigLLVMDIType *union_member_di_type = ZigLLVMCreateDebugMemberType(g->dbuilder,
   7110             ZigLLVMTypeToScope(union_type->llvm_di_type), "payload",
   7111             import->data.structure.root_struct->di_file, (unsigned)(decl_node->line + 1),
   7112             most_aligned_union_member->size_in_bits,
   7113             8*most_aligned_union_member->abi_align,
   7114             union_offset_in_bits,
   7115             ZigLLVM_DIFlags_Zero, union_di_type);
   7116 
   7117     uint64_t tag_debug_size_in_bits = tag_type->size_in_bits;
   7118     uint64_t tag_debug_align_in_bits = 8*tag_type->abi_align;
   7119 
   7120     ZigLLVMDIType *tag_member_di_type = ZigLLVMCreateDebugMemberType(g->dbuilder,
   7121             ZigLLVMTypeToScope(union_type->llvm_di_type), "tag",
   7122             import->data.structure.root_struct->di_file, (unsigned)(decl_node->line + 1),
   7123             tag_debug_size_in_bits,
   7124             tag_debug_align_in_bits,
   7125             tag_offset_in_bits,
   7126             ZigLLVM_DIFlags_Zero, get_llvm_di_type(g, tag_type));
   7127 
   7128     ZigLLVMDIType *di_root_members[2];
   7129     di_root_members[union_type->data.unionation.gen_tag_index] = tag_member_di_type;
   7130     di_root_members[union_type->data.unionation.gen_union_index] = union_member_di_type;
   7131 
   7132     uint64_t debug_size_in_bits = union_type->size_in_bits;
   7133     uint64_t debug_align_in_bits = 8*union_type->abi_align;
   7134     ZigLLVMDIType *replacement_di_type = ZigLLVMCreateDebugStructType(g->dbuilder,
   7135             ZigLLVMFileToScope(import->data.structure.root_struct->di_file),
   7136             buf_ptr(&union_type->name),
   7137             import->data.structure.root_struct->di_file, (unsigned)(decl_node->line + 1),
   7138             debug_size_in_bits,
   7139             debug_align_in_bits,
   7140             ZigLLVM_DIFlags_Zero, nullptr, di_root_members, 2, 0, nullptr, "");
   7141 
   7142     ZigLLVMReplaceTemporary(g->dbuilder, union_type->llvm_di_type, replacement_di_type);
   7143     union_type->llvm_di_type = replacement_di_type;
   7144     union_type->data.unionation.resolve_status = ResolveStatusLLVMFull;
   7145 }
   7146 
   7147 static void resolve_llvm_types_pointer(CodeGen *g, ZigType *type) {
   7148     if (type->llvm_di_type != nullptr) return;
   7149 
   7150     if (!type_has_bits(type)) {
   7151         type->llvm_type = g->builtin_types.entry_void->llvm_type;
   7152         type->llvm_di_type = g->builtin_types.entry_void->llvm_di_type;
   7153         return;
   7154     }
   7155 
   7156     ZigType *elem_type = type->data.pointer.child_type;
   7157 
   7158     if (type->data.pointer.is_const || type->data.pointer.is_volatile ||
   7159         type->data.pointer.explicit_alignment != 0 || type->data.pointer.ptr_len != PtrLenSingle ||
   7160         type->data.pointer.bit_offset_in_host != 0 || type->data.pointer.allow_zero)
   7161     {
   7162         ZigType *peer_type = get_pointer_to_type_extra(g, elem_type, false, false,
   7163                 PtrLenSingle, 0, 0, type->data.pointer.host_int_bytes, false);
   7164         type->llvm_type = get_llvm_type(g, peer_type);
   7165         type->llvm_di_type = get_llvm_di_type(g, peer_type);
   7166         return;
   7167     }
   7168 
   7169     if (type->data.pointer.host_int_bytes == 0) {
   7170         assertNoError(type_resolve(g, elem_type, ResolveStatusLLVMFwdDecl));
   7171         type->llvm_type = LLVMPointerType(elem_type->llvm_type, 0);
   7172         uint64_t debug_size_in_bits = 8*get_store_size_bytes(type->size_in_bits);
   7173         uint64_t debug_align_in_bits = 8*type->abi_align;
   7174         type->llvm_di_type = ZigLLVMCreateDebugPointerType(g->dbuilder, elem_type->llvm_di_type,
   7175                 debug_size_in_bits, debug_align_in_bits, buf_ptr(&type->name));
   7176         assertNoError(type_resolve(g, elem_type, ResolveStatusLLVMFull));
   7177     } else {
   7178         ZigType *host_int_type = get_int_type(g, false, type->data.pointer.host_int_bytes * 8);
   7179         LLVMTypeRef host_int_llvm_type = get_llvm_type(g, host_int_type);
   7180         type->llvm_type = LLVMPointerType(host_int_llvm_type, 0);
   7181         uint64_t debug_size_in_bits = 8*LLVMStoreSizeOfType(g->target_data_ref, host_int_llvm_type);
   7182         uint64_t debug_align_in_bits = 8*LLVMABIAlignmentOfType(g->target_data_ref, host_int_llvm_type);
   7183         type->llvm_di_type = ZigLLVMCreateDebugPointerType(g->dbuilder, get_llvm_di_type(g, host_int_type),
   7184                 debug_size_in_bits, debug_align_in_bits, buf_ptr(&type->name));
   7185     }
   7186 }
   7187 
   7188 static void resolve_llvm_types_integer(CodeGen *g, ZigType *type) {
   7189     if (type->llvm_di_type != nullptr) return;
   7190 
   7191     if (!type_has_bits(type)) {
   7192         type->llvm_type = g->builtin_types.entry_void->llvm_type;
   7193         type->llvm_di_type = g->builtin_types.entry_void->llvm_di_type;
   7194         return;
   7195     }
   7196 
   7197     unsigned dwarf_tag;
   7198     if (type->data.integral.is_signed) {
   7199         if (type->size_in_bits == 8) {
   7200             dwarf_tag = ZigLLVMEncoding_DW_ATE_signed_char();
   7201         } else {
   7202             dwarf_tag = ZigLLVMEncoding_DW_ATE_signed();
   7203         }
   7204     } else {
   7205         if (type->size_in_bits == 8) {
   7206             dwarf_tag = ZigLLVMEncoding_DW_ATE_unsigned_char();
   7207         } else {
   7208             dwarf_tag = ZigLLVMEncoding_DW_ATE_unsigned();
   7209         }
   7210     }
   7211 
   7212     type->llvm_di_type = ZigLLVMCreateDebugBasicType(g->dbuilder, buf_ptr(&type->name), type->size_in_bits, dwarf_tag);
   7213     type->llvm_type = LLVMIntType(type->size_in_bits);
   7214 }
   7215 
   7216 static void resolve_llvm_types_optional(CodeGen *g, ZigType *type) {
   7217     if (type->llvm_di_type != nullptr) return;
   7218 
   7219     LLVMTypeRef bool_llvm_type = get_llvm_type(g, g->builtin_types.entry_bool);
   7220     ZigLLVMDIType *bool_llvm_di_type = get_llvm_di_type(g, g->builtin_types.entry_bool);
   7221 
   7222     ZigType *child_type = type->data.maybe.child_type;
   7223     if (!type_has_bits(child_type)) {
   7224         type->llvm_type = bool_llvm_type;
   7225         type->llvm_di_type = bool_llvm_di_type;
   7226         return;
   7227     }
   7228 
   7229     LLVMTypeRef child_llvm_type = get_llvm_type(g, child_type);
   7230     ZigLLVMDIType *child_llvm_di_type = get_llvm_di_type(g, child_type);
   7231 
   7232     if (type_is_nonnull_ptr(child_type) || child_type->id == ZigTypeIdErrorSet) {
   7233         type->llvm_type = child_llvm_type;
   7234         type->llvm_di_type = child_llvm_di_type;
   7235         return;
   7236     }
   7237 
   7238     LLVMTypeRef elem_types[] = {
   7239         get_llvm_type(g, child_type),
   7240         LLVMInt1Type(),
   7241     };
   7242     type->llvm_type = LLVMStructType(elem_types, 2, false);
   7243 
   7244     ZigLLVMDIScope *compile_unit_scope = ZigLLVMCompileUnitToScope(g->compile_unit);
   7245     ZigLLVMDIFile *di_file = nullptr;
   7246     unsigned line = 0;
   7247     type->llvm_di_type = ZigLLVMCreateReplaceableCompositeType(g->dbuilder,
   7248         ZigLLVMTag_DW_structure_type(), buf_ptr(&type->name),
   7249         compile_unit_scope, di_file, line);
   7250 
   7251     uint64_t val_debug_size_in_bits = 8*LLVMStoreSizeOfType(g->target_data_ref, child_llvm_type);
   7252     uint64_t val_debug_align_in_bits = 8*LLVMABISizeOfType(g->target_data_ref, child_llvm_type);
   7253     uint64_t val_offset_in_bits = 8*LLVMOffsetOfElement(g->target_data_ref, type->llvm_type, 0);
   7254 
   7255     uint64_t maybe_debug_size_in_bits = 8*LLVMStoreSizeOfType(g->target_data_ref, bool_llvm_type);
   7256     uint64_t maybe_debug_align_in_bits = 8*LLVMABISizeOfType(g->target_data_ref, bool_llvm_type);
   7257     uint64_t maybe_offset_in_bits = 8*LLVMOffsetOfElement(g->target_data_ref, type->llvm_type, 1);
   7258 
   7259     uint64_t debug_size_in_bits = 8*LLVMStoreSizeOfType(g->target_data_ref, type->llvm_type);
   7260     uint64_t debug_align_in_bits = 8*LLVMABISizeOfType(g->target_data_ref, type->llvm_type);
   7261 
   7262     ZigLLVMDIType *di_element_types[] = {
   7263         ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(type->llvm_di_type),
   7264                 "val", di_file, line,
   7265                 val_debug_size_in_bits,
   7266                 val_debug_align_in_bits,
   7267                 val_offset_in_bits,
   7268                 ZigLLVM_DIFlags_Zero, child_llvm_di_type),
   7269         ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(type->llvm_di_type),
   7270                 "maybe", di_file, line,
   7271                 maybe_debug_size_in_bits,
   7272                 maybe_debug_align_in_bits,
   7273                 maybe_offset_in_bits,
   7274                 ZigLLVM_DIFlags_Zero, bool_llvm_di_type),
   7275     };
   7276     ZigLLVMDIType *replacement_di_type = ZigLLVMCreateDebugStructType(g->dbuilder,
   7277             compile_unit_scope,
   7278             buf_ptr(&type->name),
   7279             di_file, line, debug_size_in_bits, debug_align_in_bits, ZigLLVM_DIFlags_Zero,
   7280             nullptr, di_element_types, 2, 0, nullptr, "");
   7281 
   7282     ZigLLVMReplaceTemporary(g->dbuilder, type->llvm_di_type, replacement_di_type);
   7283     type->llvm_di_type = replacement_di_type;
   7284 }
   7285 
   7286 static void resolve_llvm_types_error_union(CodeGen *g, ZigType *type) {
   7287     if (type->llvm_di_type != nullptr) return;
   7288 
   7289     ZigType *payload_type = type->data.error_union.payload_type;
   7290     ZigType *err_set_type = type->data.error_union.err_set_type;
   7291 
   7292     if (!type_has_bits(payload_type)) {
   7293         assert(type_has_bits(err_set_type));
   7294         type->llvm_type = get_llvm_type(g, err_set_type);
   7295         type->llvm_di_type = get_llvm_di_type(g, err_set_type);
   7296     } else if (!type_has_bits(err_set_type)) {
   7297         type->llvm_type = get_llvm_type(g, payload_type);
   7298         type->llvm_di_type = get_llvm_di_type(g, payload_type);
   7299     } else {
   7300         LLVMTypeRef err_set_llvm_type = get_llvm_type(g, err_set_type);
   7301         LLVMTypeRef payload_llvm_type = get_llvm_type(g, payload_type);
   7302         LLVMTypeRef elem_types[2];
   7303         elem_types[err_union_err_index] = err_set_llvm_type;
   7304         elem_types[err_union_payload_index] = payload_llvm_type;
   7305         type->llvm_type = LLVMStructType(elem_types, 2, false);
   7306 
   7307         ZigLLVMDIScope *compile_unit_scope = ZigLLVMCompileUnitToScope(g->compile_unit);
   7308         ZigLLVMDIFile *di_file = nullptr;
   7309         unsigned line = 0;
   7310         type->llvm_di_type = ZigLLVMCreateReplaceableCompositeType(g->dbuilder,
   7311             ZigLLVMTag_DW_structure_type(), buf_ptr(&type->name),
   7312             compile_unit_scope, di_file, line);
   7313 
   7314         uint64_t tag_debug_size_in_bits = 8*LLVMStoreSizeOfType(g->target_data_ref, err_set_llvm_type);
   7315         uint64_t tag_debug_align_in_bits = 8*LLVMABISizeOfType(g->target_data_ref, err_set_llvm_type);
   7316         uint64_t tag_offset_in_bits = 8*LLVMOffsetOfElement(g->target_data_ref, type->llvm_type, err_union_err_index);
   7317 
   7318         uint64_t value_debug_size_in_bits = 8*LLVMStoreSizeOfType(g->target_data_ref, payload_llvm_type);
   7319         uint64_t value_debug_align_in_bits = 8*LLVMABISizeOfType(g->target_data_ref, payload_llvm_type);
   7320         uint64_t value_offset_in_bits = 8*LLVMOffsetOfElement(g->target_data_ref, type->llvm_type,
   7321                 err_union_payload_index);
   7322 
   7323         uint64_t debug_size_in_bits = 8*LLVMStoreSizeOfType(g->target_data_ref, type->llvm_type);
   7324         uint64_t debug_align_in_bits = 8*LLVMABISizeOfType(g->target_data_ref, type->llvm_type);
   7325 
   7326         ZigLLVMDIType *di_element_types[] = {
   7327             ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(type->llvm_di_type),
   7328                     "tag", di_file, line,
   7329                     tag_debug_size_in_bits,
   7330                     tag_debug_align_in_bits,
   7331                     tag_offset_in_bits,
   7332                     ZigLLVM_DIFlags_Zero, get_llvm_di_type(g, err_set_type)),
   7333             ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(type->llvm_di_type),
   7334                     "value", di_file, line,
   7335                     value_debug_size_in_bits,
   7336                     value_debug_align_in_bits,
   7337                     value_offset_in_bits,
   7338                     ZigLLVM_DIFlags_Zero, get_llvm_di_type(g, payload_type)),
   7339         };
   7340 
   7341         ZigLLVMDIType *replacement_di_type = ZigLLVMCreateDebugStructType(g->dbuilder,
   7342                 compile_unit_scope,
   7343                 buf_ptr(&type->name),
   7344                 di_file, line,
   7345                 debug_size_in_bits,
   7346                 debug_align_in_bits,
   7347                 ZigLLVM_DIFlags_Zero,
   7348                 nullptr, di_element_types, 2, 0, nullptr, "");
   7349 
   7350         ZigLLVMReplaceTemporary(g->dbuilder, type->llvm_di_type, replacement_di_type);
   7351         type->llvm_di_type = replacement_di_type;
   7352     }
   7353 }
   7354 
   7355 static void resolve_llvm_types_array(CodeGen *g, ZigType *type) {
   7356     if (type->llvm_di_type != nullptr) return;
   7357 
   7358     if (!type_has_bits(type)) {
   7359         type->llvm_type = g->builtin_types.entry_void->llvm_type;
   7360         type->llvm_di_type = g->builtin_types.entry_void->llvm_di_type;
   7361         return;
   7362     }
   7363 
   7364     ZigType *elem_type = type->data.array.child_type;
   7365 
   7366     // TODO https://github.com/ziglang/zig/issues/1424
   7367     type->llvm_type = LLVMArrayType(get_llvm_type(g, elem_type), (unsigned)type->data.array.len);
   7368 
   7369     uint64_t debug_size_in_bits = 8*LLVMStoreSizeOfType(g->target_data_ref, type->llvm_type);
   7370     uint64_t debug_align_in_bits = 8*LLVMABISizeOfType(g->target_data_ref, type->llvm_type);
   7371 
   7372     type->llvm_di_type = ZigLLVMCreateDebugArrayType(g->dbuilder, debug_size_in_bits,
   7373             debug_align_in_bits, get_llvm_di_type(g, elem_type), (int)type->data.array.len);
   7374 }
   7375 
   7376 static void resolve_llvm_types_fn_type(CodeGen *g, ZigType *fn_type) {
   7377     if (fn_type->llvm_di_type != nullptr) return;
   7378 
   7379     FnTypeId *fn_type_id = &fn_type->data.fn.fn_type_id;
   7380     bool first_arg_return = want_first_arg_sret(g, fn_type_id);
   7381     bool is_async = fn_type_id->cc == CallingConventionAsync;
   7382     bool is_c_abi = fn_type_id->cc == CallingConventionC;
   7383     bool prefix_arg_error_return_trace = g->have_err_ret_tracing && fn_type_can_fail(fn_type_id);
   7384     // +1 for maybe making the first argument the return value
   7385     // +1 for maybe first argument the error return trace
   7386     // +2 for maybe arguments async allocator and error code pointer
   7387     ZigList<LLVMTypeRef> gen_param_types = {};
   7388     // +1 because 0 is the return type and
   7389     // +1 for maybe making first arg ret val and
   7390     // +1 for maybe first argument the error return trace
   7391     // +2 for maybe arguments async allocator and error code pointer
   7392     ZigList<ZigLLVMDIType *> param_di_types = {};
   7393     ZigType *gen_return_type;
   7394     if (is_async) {
   7395         gen_return_type = g->builtin_types.entry_void;
   7396         param_di_types.append(get_llvm_di_type(g, gen_return_type));
   7397     } else if (!type_has_bits(fn_type_id->return_type)) {
   7398         gen_return_type = g->builtin_types.entry_void;
   7399         param_di_types.append(get_llvm_di_type(g, gen_return_type));
   7400     } else if (first_arg_return) {
   7401         gen_return_type = g->builtin_types.entry_void;
   7402         param_di_types.append(get_llvm_di_type(g, gen_return_type));
   7403         ZigType *gen_type = get_pointer_to_type(g, fn_type_id->return_type, false);
   7404         gen_param_types.append(get_llvm_type(g, gen_type));
   7405         param_di_types.append(get_llvm_di_type(g, gen_type));
   7406     } else {
   7407         gen_return_type = fn_type_id->return_type;
   7408         param_di_types.append(get_llvm_di_type(g, gen_return_type));
   7409     }
   7410     fn_type->data.fn.gen_return_type = gen_return_type;
   7411 
   7412     if (prefix_arg_error_return_trace && !is_async) {
   7413         ZigType *gen_type = get_ptr_to_stack_trace_type(g);
   7414         gen_param_types.append(get_llvm_type(g, gen_type));
   7415         param_di_types.append(get_llvm_di_type(g, gen_type));
   7416     }
   7417     if (is_async) {
   7418         fn_type->data.fn.gen_param_info = allocate<FnGenParamInfo>(2);
   7419 
   7420         ZigType *frame_type = get_any_frame_type(g, fn_type_id->return_type);
   7421         gen_param_types.append(get_llvm_type(g, frame_type));
   7422         param_di_types.append(get_llvm_di_type(g, frame_type));
   7423 
   7424         fn_type->data.fn.gen_param_info[0].src_index = 0;
   7425         fn_type->data.fn.gen_param_info[0].gen_index = 0;
   7426         fn_type->data.fn.gen_param_info[0].type = frame_type;
   7427 
   7428         gen_param_types.append(get_llvm_type(g, g->builtin_types.entry_usize));
   7429         param_di_types.append(get_llvm_di_type(g, g->builtin_types.entry_usize));
   7430 
   7431         fn_type->data.fn.gen_param_info[1].src_index = 1;
   7432         fn_type->data.fn.gen_param_info[1].gen_index = 1;
   7433         fn_type->data.fn.gen_param_info[1].type = g->builtin_types.entry_usize;
   7434     } else {
   7435         fn_type->data.fn.gen_param_info = allocate<FnGenParamInfo>(fn_type_id->param_count);
   7436         for (size_t i = 0; i < fn_type_id->param_count; i += 1) {
   7437             FnTypeParamInfo *src_param_info = &fn_type->data.fn.fn_type_id.param_info[i];
   7438             ZigType *type_entry = src_param_info->type;
   7439             FnGenParamInfo *gen_param_info = &fn_type->data.fn.gen_param_info[i];
   7440 
   7441             gen_param_info->src_index = i;
   7442             gen_param_info->gen_index = SIZE_MAX;
   7443 
   7444             if (is_c_abi || !type_has_bits(type_entry))
   7445                 continue;
   7446 
   7447             ZigType *gen_type;
   7448             if (handle_is_ptr(type_entry)) {
   7449                 gen_type = get_pointer_to_type(g, type_entry, true);
   7450                 gen_param_info->is_byval = true;
   7451             } else {
   7452                 gen_type = type_entry;
   7453             }
   7454             gen_param_info->gen_index = gen_param_types.length;
   7455             gen_param_info->type = gen_type;
   7456             gen_param_types.append(get_llvm_type(g, gen_type));
   7457 
   7458             param_di_types.append(get_llvm_di_type(g, gen_type));
   7459         }
   7460     }
   7461 
   7462     if (is_c_abi) {
   7463         FnWalk fn_walk = {};
   7464         fn_walk.id = FnWalkIdTypes;
   7465         fn_walk.data.types.param_di_types = &param_di_types;
   7466         fn_walk.data.types.gen_param_types = &gen_param_types;
   7467         walk_function_params(g, fn_type, &fn_walk);
   7468     }
   7469 
   7470     fn_type->data.fn.gen_param_count = gen_param_types.length;
   7471 
   7472     for (size_t i = 0; i < gen_param_types.length; i += 1) {
   7473         assert(gen_param_types.items[i] != nullptr);
   7474     }
   7475 
   7476     fn_type->data.fn.raw_type_ref = LLVMFunctionType(get_llvm_type(g, gen_return_type),
   7477             gen_param_types.items, (unsigned int)gen_param_types.length, fn_type_id->is_var_args);
   7478     fn_type->llvm_type = LLVMPointerType(fn_type->data.fn.raw_type_ref, 0);
   7479     fn_type->data.fn.raw_di_type = ZigLLVMCreateSubroutineType(g->dbuilder, param_di_types.items, (int)param_di_types.length, 0);
   7480     fn_type->llvm_di_type = ZigLLVMCreateDebugPointerType(g->dbuilder, fn_type->data.fn.raw_di_type,
   7481             LLVMStoreSizeOfType(g->target_data_ref, fn_type->llvm_type),
   7482             LLVMABIAlignmentOfType(g->target_data_ref, fn_type->llvm_type), "");
   7483 }
   7484 
   7485 void resolve_llvm_types_fn(CodeGen *g, ZigFn *fn) {
   7486     if (fn->raw_di_type != nullptr) return;
   7487 
   7488     ZigType *fn_type = fn->type_entry;
   7489     if (!fn_is_async(fn)) {
   7490         resolve_llvm_types_fn_type(g, fn_type);
   7491         fn->raw_type_ref = fn_type->data.fn.raw_type_ref;
   7492         fn->raw_di_type = fn_type->data.fn.raw_di_type;
   7493         return;
   7494     }
   7495 
   7496     ZigType *gen_return_type = g->builtin_types.entry_void;
   7497     ZigList<ZigLLVMDIType *> param_di_types = {};
   7498     ZigList<LLVMTypeRef> gen_param_types = {};
   7499     // first "parameter" is return value
   7500     param_di_types.append(get_llvm_di_type(g, gen_return_type));
   7501 
   7502     ZigType *frame_type = get_coro_frame_type(g, fn);
   7503     ZigType *ptr_type = get_pointer_to_type(g, frame_type, false);
   7504     gen_param_types.append(get_llvm_type(g, ptr_type));
   7505     param_di_types.append(get_llvm_di_type(g, ptr_type));
   7506 
   7507     // this parameter is used to pass the result pointer when await completes
   7508     gen_param_types.append(get_llvm_type(g, g->builtin_types.entry_usize));
   7509     param_di_types.append(get_llvm_di_type(g, g->builtin_types.entry_usize));
   7510 
   7511     fn->raw_type_ref = LLVMFunctionType(get_llvm_type(g, gen_return_type),
   7512             gen_param_types.items, gen_param_types.length, false);
   7513     fn->raw_di_type = ZigLLVMCreateSubroutineType(g->dbuilder, param_di_types.items, (int)param_di_types.length, 0);
   7514 }
   7515 
   7516 static void resolve_llvm_types_anyerror(CodeGen *g) {
   7517     ZigType *entry = g->builtin_types.entry_global_error_set;
   7518     entry->llvm_type = get_llvm_type(g, g->err_tag_type);
   7519     ZigList<ZigLLVMDIEnumerator *> err_enumerators = {};
   7520     // reserve index 0 to indicate no error
   7521     err_enumerators.append(ZigLLVMCreateDebugEnumerator(g->dbuilder, "(none)", 0));
   7522     for (size_t i = 1; i < g->errors_by_index.length; i += 1) {
   7523         ErrorTableEntry *error_entry = g->errors_by_index.at(i);
   7524         err_enumerators.append(ZigLLVMCreateDebugEnumerator(g->dbuilder, buf_ptr(&error_entry->name), i));
   7525     }
   7526 
   7527     // create debug type for error sets
   7528     uint64_t tag_debug_size_in_bits = g->err_tag_type->size_in_bits;
   7529     uint64_t tag_debug_align_in_bits = 8*g->err_tag_type->abi_align;
   7530     ZigLLVMDIFile *err_set_di_file = nullptr;
   7531     entry->llvm_di_type = ZigLLVMCreateDebugEnumerationType(g->dbuilder,
   7532             ZigLLVMCompileUnitToScope(g->compile_unit), buf_ptr(&entry->name),
   7533             err_set_di_file, 0,
   7534             tag_debug_size_in_bits,
   7535             tag_debug_align_in_bits,
   7536             err_enumerators.items, err_enumerators.length,
   7537             get_llvm_di_type(g, g->err_tag_type), "");
   7538 }
   7539 
   7540 static void resolve_llvm_types_coro_frame(CodeGen *g, ZigType *frame_type, ResolveStatus wanted_resolve_status) {
   7541     resolve_llvm_types_struct(g, frame_type->data.frame.locals_struct, wanted_resolve_status, frame_type);
   7542     frame_type->llvm_type = frame_type->data.frame.locals_struct->llvm_type;
   7543     frame_type->llvm_di_type = frame_type->data.frame.locals_struct->llvm_di_type;
   7544 }
   7545 
   7546 static void resolve_llvm_types_any_frame(CodeGen *g, ZigType *any_frame_type, ResolveStatus wanted_resolve_status) {
   7547     if (any_frame_type->llvm_di_type != nullptr) return;
   7548 
   7549     Buf *name = buf_sprintf("(%s header)", buf_ptr(&any_frame_type->name));
   7550     LLVMTypeRef frame_header_type = LLVMStructCreateNamed(LLVMGetGlobalContext(), buf_ptr(name));
   7551     any_frame_type->llvm_type = LLVMPointerType(frame_header_type, 0);
   7552 
   7553     unsigned dwarf_kind = ZigLLVMTag_DW_structure_type();
   7554     ZigLLVMDIFile *di_file = nullptr;
   7555     ZigLLVMDIScope *di_scope = ZigLLVMCompileUnitToScope(g->compile_unit);
   7556     unsigned line = 0;
   7557     ZigLLVMDIType *frame_header_di_type = ZigLLVMCreateReplaceableCompositeType(g->dbuilder,
   7558         dwarf_kind, buf_ptr(name), di_scope, di_file, line);
   7559     any_frame_type->llvm_di_type = ZigLLVMCreateDebugPointerType(g->dbuilder, frame_header_di_type,
   7560             8*g->pointer_size_bytes, 8*g->builtin_types.entry_usize->abi_align, buf_ptr(&any_frame_type->name));
   7561 
   7562     LLVMTypeRef llvm_void = LLVMVoidType();
   7563     LLVMTypeRef arg_types[] = {any_frame_type->llvm_type, g->builtin_types.entry_usize->llvm_type};
   7564     LLVMTypeRef fn_type = LLVMFunctionType(llvm_void, arg_types, 2, false);
   7565     LLVMTypeRef usize_type_ref = get_llvm_type(g, g->builtin_types.entry_usize);
   7566     ZigLLVMDIType *usize_di_type = get_llvm_di_type(g, g->builtin_types.entry_usize);
   7567     ZigLLVMDIScope *compile_unit_scope = ZigLLVMCompileUnitToScope(g->compile_unit);
   7568 
   7569     ZigType *result_type = any_frame_type->data.any_frame.result_type;
   7570     ZigType *ptr_result_type = (result_type == nullptr) ? nullptr : get_pointer_to_type(g, result_type, false);
   7571     LLVMTypeRef ptr_fn_llvm_type = LLVMPointerType(fn_type, 0);
   7572     if (result_type == nullptr) {
   7573         g->anyframe_fn_type = ptr_fn_llvm_type;
   7574     }
   7575 
   7576     ZigList<LLVMTypeRef> field_types = {};
   7577     ZigList<ZigLLVMDIType *> di_element_types = {};
   7578 
   7579     // label (grep this): [coro_frame_struct_layout]
   7580     field_types.append(ptr_fn_llvm_type); // fn_ptr
   7581     field_types.append(usize_type_ref); // resume_index
   7582     field_types.append(usize_type_ref); // awaiter
   7583 
   7584     bool have_result_type = result_type != nullptr && type_has_bits(result_type);
   7585     if (have_result_type) {
   7586         field_types.append(get_llvm_type(g, ptr_result_type)); // result_ptr_callee
   7587         field_types.append(get_llvm_type(g, ptr_result_type)); // result_ptr_awaiter
   7588         field_types.append(get_llvm_type(g, result_type)); // result
   7589         if (codegen_fn_has_err_ret_tracing_arg(g, result_type)) {
   7590             field_types.append(get_llvm_type(g, get_ptr_to_stack_trace_type(g))); // ptr_stack_trace
   7591         }
   7592     }
   7593     LLVMStructSetBody(frame_header_type, field_types.items, field_types.length, false);
   7594 
   7595     di_element_types.append(
   7596         ZigLLVMCreateDebugMemberType(g->dbuilder,
   7597             ZigLLVMTypeToScope(any_frame_type->llvm_di_type), "fn_ptr",
   7598             di_file, line,
   7599             8*LLVMABISizeOfType(g->target_data_ref, field_types.at(di_element_types.length)),
   7600             8*LLVMABIAlignmentOfType(g->target_data_ref, field_types.at(di_element_types.length)),
   7601             8*LLVMOffsetOfElement(g->target_data_ref, frame_header_type, di_element_types.length),
   7602             ZigLLVM_DIFlags_Zero, usize_di_type));
   7603     di_element_types.append(
   7604         ZigLLVMCreateDebugMemberType(g->dbuilder,
   7605             ZigLLVMTypeToScope(any_frame_type->llvm_di_type), "resume_index",
   7606             di_file, line,
   7607             8*LLVMABISizeOfType(g->target_data_ref, field_types.at(di_element_types.length)),
   7608             8*LLVMABIAlignmentOfType(g->target_data_ref, field_types.at(di_element_types.length)),
   7609             8*LLVMOffsetOfElement(g->target_data_ref, frame_header_type, di_element_types.length),
   7610             ZigLLVM_DIFlags_Zero, usize_di_type));
   7611     di_element_types.append(
   7612         ZigLLVMCreateDebugMemberType(g->dbuilder,
   7613             ZigLLVMTypeToScope(any_frame_type->llvm_di_type), "awaiter",
   7614             di_file, line,
   7615             8*LLVMABISizeOfType(g->target_data_ref, field_types.at(di_element_types.length)),
   7616             8*LLVMABIAlignmentOfType(g->target_data_ref, field_types.at(di_element_types.length)),
   7617             8*LLVMOffsetOfElement(g->target_data_ref, frame_header_type, di_element_types.length),
   7618             ZigLLVM_DIFlags_Zero, usize_di_type));
   7619 
   7620     if (have_result_type) {
   7621         di_element_types.append(
   7622             ZigLLVMCreateDebugMemberType(g->dbuilder,
   7623                 ZigLLVMTypeToScope(any_frame_type->llvm_di_type), "result_ptr_callee",
   7624                 di_file, line,
   7625                 8*LLVMABISizeOfType(g->target_data_ref, field_types.at(di_element_types.length)),
   7626                 8*LLVMABIAlignmentOfType(g->target_data_ref, field_types.at(di_element_types.length)),
   7627                 8*LLVMOffsetOfElement(g->target_data_ref, frame_header_type, di_element_types.length),
   7628                 ZigLLVM_DIFlags_Zero, get_llvm_di_type(g, ptr_result_type)));
   7629         di_element_types.append(
   7630             ZigLLVMCreateDebugMemberType(g->dbuilder,
   7631                 ZigLLVMTypeToScope(any_frame_type->llvm_di_type), "result_ptr_awaiter",
   7632                 di_file, line,
   7633                 8*LLVMABISizeOfType(g->target_data_ref, field_types.at(di_element_types.length)),
   7634                 8*LLVMABIAlignmentOfType(g->target_data_ref, field_types.at(di_element_types.length)),
   7635                 8*LLVMOffsetOfElement(g->target_data_ref, frame_header_type, di_element_types.length),
   7636                 ZigLLVM_DIFlags_Zero, get_llvm_di_type(g, ptr_result_type)));
   7637         di_element_types.append(
   7638             ZigLLVMCreateDebugMemberType(g->dbuilder,
   7639                 ZigLLVMTypeToScope(any_frame_type->llvm_di_type), "result",
   7640                 di_file, line,
   7641                 8*LLVMABISizeOfType(g->target_data_ref, field_types.at(di_element_types.length)),
   7642                 8*LLVMABIAlignmentOfType(g->target_data_ref, field_types.at(di_element_types.length)),
   7643                 8*LLVMOffsetOfElement(g->target_data_ref, frame_header_type, di_element_types.length),
   7644                 ZigLLVM_DIFlags_Zero, get_llvm_di_type(g, result_type)));
   7645 
   7646         if (codegen_fn_has_err_ret_tracing_arg(g, result_type)) {
   7647             di_element_types.append(
   7648                 ZigLLVMCreateDebugMemberType(g->dbuilder,
   7649                     ZigLLVMTypeToScope(any_frame_type->llvm_di_type), "ptr_stack_trace",
   7650                     di_file, line,
   7651                     8*LLVMABISizeOfType(g->target_data_ref, field_types.at(di_element_types.length)),
   7652                     8*LLVMABIAlignmentOfType(g->target_data_ref, field_types.at(di_element_types.length)),
   7653                     8*LLVMOffsetOfElement(g->target_data_ref, frame_header_type, di_element_types.length),
   7654                     ZigLLVM_DIFlags_Zero, get_llvm_di_type(g, get_ptr_to_stack_trace_type(g))));
   7655         }
   7656     };
   7657 
   7658     ZigLLVMDIType *replacement_di_type = ZigLLVMCreateDebugStructType(g->dbuilder,
   7659             compile_unit_scope, buf_ptr(name),
   7660             di_file, line,
   7661             8*LLVMABISizeOfType(g->target_data_ref, frame_header_type),
   7662             8*LLVMABIAlignmentOfType(g->target_data_ref, frame_header_type),
   7663             ZigLLVM_DIFlags_Zero,
   7664             nullptr, di_element_types.items, di_element_types.length, 0, nullptr, "");
   7665 
   7666     ZigLLVMReplaceTemporary(g->dbuilder, frame_header_di_type, replacement_di_type);
   7667 }
   7668 
   7669 static void resolve_llvm_types(CodeGen *g, ZigType *type, ResolveStatus wanted_resolve_status) {
   7670     assert(type->id == ZigTypeIdOpaque || type_is_resolved(type, ResolveStatusSizeKnown));
   7671     assert(wanted_resolve_status > ResolveStatusSizeKnown);
   7672     switch (type->id) {
   7673         case ZigTypeIdInvalid:
   7674         case ZigTypeIdMetaType:
   7675         case ZigTypeIdComptimeFloat:
   7676         case ZigTypeIdComptimeInt:
   7677         case ZigTypeIdEnumLiteral:
   7678         case ZigTypeIdUndefined:
   7679         case ZigTypeIdNull:
   7680         case ZigTypeIdBoundFn:
   7681         case ZigTypeIdArgTuple:
   7682             zig_unreachable();
   7683         case ZigTypeIdFloat:
   7684         case ZigTypeIdOpaque:
   7685         case ZigTypeIdVoid:
   7686         case ZigTypeIdBool:
   7687         case ZigTypeIdUnreachable:
   7688             assert(type->llvm_di_type != nullptr);
   7689             return;
   7690         case ZigTypeIdStruct:
   7691             if (type->data.structure.is_slice)
   7692                 return resolve_llvm_types_slice(g, type, wanted_resolve_status);
   7693             else
   7694                 return resolve_llvm_types_struct(g, type, wanted_resolve_status, nullptr);
   7695         case ZigTypeIdEnum:
   7696             return resolve_llvm_types_enum(g, type);
   7697         case ZigTypeIdUnion:
   7698             return resolve_llvm_types_union(g, type, wanted_resolve_status);
   7699         case ZigTypeIdPointer:
   7700             return resolve_llvm_types_pointer(g, type);
   7701         case ZigTypeIdInt:
   7702             return resolve_llvm_types_integer(g, type);
   7703         case ZigTypeIdOptional:
   7704             return resolve_llvm_types_optional(g, type);
   7705         case ZigTypeIdErrorUnion:
   7706             return resolve_llvm_types_error_union(g, type);
   7707         case ZigTypeIdArray:
   7708             return resolve_llvm_types_array(g, type);
   7709         case ZigTypeIdFn:
   7710             return resolve_llvm_types_fn_type(g, type);
   7711         case ZigTypeIdErrorSet: {
   7712             if (type->llvm_di_type != nullptr) return;
   7713 
   7714             if (g->builtin_types.entry_global_error_set->llvm_type == nullptr) {
   7715                 resolve_llvm_types_anyerror(g);
   7716             }
   7717             type->llvm_type = g->builtin_types.entry_global_error_set->llvm_type;
   7718             type->llvm_di_type = g->builtin_types.entry_global_error_set->llvm_di_type;
   7719             return;
   7720         }
   7721         case ZigTypeIdVector: {
   7722             if (type->llvm_di_type != nullptr) return;
   7723 
   7724             type->llvm_type = LLVMVectorType(get_llvm_type(g, type->data.vector.elem_type), type->data.vector.len);
   7725             type->llvm_di_type = ZigLLVMDIBuilderCreateVectorType(g->dbuilder, type->size_in_bits,
   7726                     type->abi_align, get_llvm_di_type(g, type->data.vector.elem_type), type->data.vector.len);
   7727             return;
   7728         }
   7729         case ZigTypeIdCoroFrame:
   7730             return resolve_llvm_types_coro_frame(g, type, wanted_resolve_status);
   7731         case ZigTypeIdAnyFrame:
   7732             return resolve_llvm_types_any_frame(g, type, wanted_resolve_status);
   7733     }
   7734     zig_unreachable();
   7735 }
   7736 
   7737 LLVMTypeRef get_llvm_type(CodeGen *g, ZigType *type) {
   7738     assertNoError(type_resolve(g, type, ResolveStatusLLVMFull));
   7739     assert(type->abi_size == 0 || type->abi_size == LLVMABISizeOfType(g->target_data_ref, type->llvm_type));
   7740     assert(type->abi_align == 0 || type->abi_align == LLVMABIAlignmentOfType(g->target_data_ref, type->llvm_type));
   7741     return type->llvm_type;
   7742 }
   7743 
   7744 ZigLLVMDIType *get_llvm_di_type(CodeGen *g, ZigType *type) {
   7745     assertNoError(type_resolve(g, type, ResolveStatusLLVMFull));
   7746     return type->llvm_di_type;
   7747 }
   7748 
   7749 void src_assert(bool ok, AstNode *source_node) {
   7750     if (ok) return;
   7751     if (source_node == nullptr) {
   7752         fprintf(stderr, "when analyzing (unknown source location): ");
   7753     } else {
   7754         fprintf(stderr, "when analyzing %s:%u:%u: ",
   7755             buf_ptr(source_node->owner->data.structure.root_struct->path),
   7756             (unsigned)source_node->line + 1, (unsigned)source_node->column + 1);
   7757     }
   7758     const char *msg = "assertion failed. This is a bug in the Zig compiler.";
   7759     stage2_panic(msg, strlen(msg));
   7760 }