-
-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy pathInternPool.zig
12737 lines (11699 loc) · 489 KB
/
InternPool.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! All interned objects have both a value and a type.
//! This data structure is self-contained.
/// One item per thread, indexed by `tid`, which is dense and unique per thread.
locals: []Local,
/// Length must be a power of two and represents the number of simultaneous
/// writers that can mutate any single sharded data structure.
shards: []Shard,
/// Key is the error name, index is the error tag value. Index 0 has a length-0 string.
global_error_set: GlobalErrorSet,
/// Cached number of active bits in a `tid`.
tid_width: if (single_threaded) u0 else std.math.Log2Int(u32),
/// Cached shift amount to put a `tid` in the top bits of a 30-bit value.
tid_shift_30: if (single_threaded) u0 else std.math.Log2Int(u32),
/// Cached shift amount to put a `tid` in the top bits of a 31-bit value.
tid_shift_31: if (single_threaded) u0 else std.math.Log2Int(u32),
/// Cached shift amount to put a `tid` in the top bits of a 32-bit value.
tid_shift_32: if (single_threaded) u0 else std.math.Log2Int(u32),
/// Dependencies on the source code hash associated with a ZIR instruction.
/// * For a `declaration`, this is the entire declaration body.
/// * For a `struct_decl`, `union_decl`, etc, this is the source of the fields (but not declarations).
/// * For a `func`, this is the source of the full function signature.
/// These are also invalidated if tracking fails for this instruction.
/// Value is index into `dep_entries` of the first dependency on this hash.
src_hash_deps: std.AutoArrayHashMapUnmanaged(TrackedInst.Index, DepEntry.Index),
/// Dependencies on the value of a Nav.
/// Value is index into `dep_entries` of the first dependency on this Nav value.
nav_val_deps: std.AutoArrayHashMapUnmanaged(Nav.Index, DepEntry.Index),
/// Dependencies on the type of a Nav.
/// Value is index into `dep_entries` of the first dependency on this Nav value.
nav_ty_deps: std.AutoArrayHashMapUnmanaged(Nav.Index, DepEntry.Index),
/// Dependencies on an interned value, either:
/// * a runtime function (invalidated when its IES changes)
/// * a container type requiring resolution (invalidated when the type must be recreated at a new index)
/// Value is index into `dep_entries` of the first dependency on this interned value.
interned_deps: std.AutoArrayHashMapUnmanaged(Index, DepEntry.Index),
/// Dependencies on a ZON file. Triggered by `@import` of ZON.
/// Value is index into `dep_entries` of the first dependency on this ZON file.
zon_file_deps: std.AutoArrayHashMapUnmanaged(FileIndex, DepEntry.Index),
/// Dependencies on an embedded file.
/// Introduced by `@embedFile`; invalidated when the file changes.
/// Value is index into `dep_entries` of the first dependency on this `Zcu.EmbedFile`.
embed_file_deps: std.AutoArrayHashMapUnmanaged(Zcu.EmbedFile.Index, DepEntry.Index),
/// Dependencies on the full set of names in a ZIR namespace.
/// Key refers to a `struct_decl`, `union_decl`, etc.
/// Value is index into `dep_entries` of the first dependency on this namespace.
namespace_deps: std.AutoArrayHashMapUnmanaged(TrackedInst.Index, DepEntry.Index),
/// Dependencies on the (non-)existence of some name in a namespace.
/// Value is index into `dep_entries` of the first dependency on this name.
namespace_name_deps: std.AutoArrayHashMapUnmanaged(NamespaceNameKey, DepEntry.Index),
// Dependencies on the value of fields memoized on `Zcu` (`panic_messages` etc).
// If set, these are indices into `dep_entries` of the first dependency on this state.
memoized_state_main_deps: DepEntry.Index.Optional,
memoized_state_panic_deps: DepEntry.Index.Optional,
memoized_state_va_list_deps: DepEntry.Index.Optional,
/// Given a `Depender`, points to an entry in `dep_entries` whose `depender`
/// matches. The `next_dependee` field can be used to iterate all such entries
/// and remove them from the corresponding lists.
first_dependency: std.AutoArrayHashMapUnmanaged(AnalUnit, DepEntry.Index),
/// Stores dependency information. The hashmaps declared above are used to look
/// up entries in this list as required. This is not stored in `extra` so that
/// we can use `free_dep_entries` to track free indices, since dependencies are
/// removed frequently.
dep_entries: std.ArrayListUnmanaged(DepEntry),
/// Stores unused indices in `dep_entries` which can be reused without a full
/// garbage collection pass.
free_dep_entries: std.ArrayListUnmanaged(DepEntry.Index),
/// Whether a multi-threaded intern pool is useful.
/// Currently `false` until the intern pool is actually accessed
/// from multiple threads to reduce the cost of this data structure.
const want_multi_threaded = true;
/// Whether a single-threaded intern pool impl is in use.
pub const single_threaded = builtin.single_threaded or !want_multi_threaded;
pub const empty: InternPool = .{
.locals = &.{},
.shards = &.{},
.global_error_set = .empty,
.tid_width = 0,
.tid_shift_30 = if (single_threaded) 0 else 31,
.tid_shift_31 = if (single_threaded) 0 else 31,
.tid_shift_32 = if (single_threaded) 0 else 31,
.src_hash_deps = .empty,
.nav_val_deps = .empty,
.nav_ty_deps = .empty,
.interned_deps = .empty,
.zon_file_deps = .empty,
.embed_file_deps = .empty,
.namespace_deps = .empty,
.namespace_name_deps = .empty,
.memoized_state_main_deps = .none,
.memoized_state_panic_deps = .none,
.memoized_state_va_list_deps = .none,
.first_dependency = .empty,
.dep_entries = .empty,
.free_dep_entries = .empty,
};
/// A `TrackedInst.Index` provides a single, unchanging reference to a ZIR instruction across a whole
/// compilation. From this index, you can acquire a `TrackedInst`, which containss a reference to both
/// the file which the instruction lives in, and the instruction index itself, which is updated on
/// incremental updates by `Zcu.updateZirRefs`.
pub const TrackedInst = extern struct {
file: FileIndex,
inst: Zir.Inst.Index,
/// It is possible on an incremental update that we "lose" a ZIR instruction: some tracked `%x` in
/// the old ZIR failed to map to any `%y` in the new ZIR. For this reason, we actually store values
/// of type `MaybeLost`, which uses `ZirIndex.lost` to represent this case. `Index.resolve` etc
/// return `null` when the `TrackedInst` being resolved has been lost.
pub const MaybeLost = extern struct {
file: FileIndex,
inst: ZirIndex,
pub const ZirIndex = enum(u32) {
/// Tracking failed for this ZIR instruction. Uses of it should fail.
lost = std.math.maxInt(u32),
_,
pub fn unwrap(inst: ZirIndex) ?Zir.Inst.Index {
return switch (inst) {
.lost => null,
_ => @enumFromInt(@intFromEnum(inst)),
};
}
pub fn wrap(inst: Zir.Inst.Index) ZirIndex {
return @enumFromInt(@intFromEnum(inst));
}
};
comptime {
// The fields should be tightly packed. See also serialiation logic in `Compilation.saveState`.
assert(@sizeOf(@This()) == @sizeOf(FileIndex) + @sizeOf(ZirIndex));
}
};
pub const Index = enum(u32) {
_,
pub fn resolveFull(tracked_inst_index: TrackedInst.Index, ip: *const InternPool) ?TrackedInst {
const tracked_inst_unwrapped = tracked_inst_index.unwrap(ip);
const tracked_insts = ip.getLocalShared(tracked_inst_unwrapped.tid).tracked_insts.acquire();
const maybe_lost = tracked_insts.view().items(.@"0")[tracked_inst_unwrapped.index];
return .{
.file = maybe_lost.file,
.inst = maybe_lost.inst.unwrap() orelse return null,
};
}
pub fn resolveFile(tracked_inst_index: TrackedInst.Index, ip: *const InternPool) FileIndex {
const tracked_inst_unwrapped = tracked_inst_index.unwrap(ip);
const tracked_insts = ip.getLocalShared(tracked_inst_unwrapped.tid).tracked_insts.acquire();
const maybe_lost = tracked_insts.view().items(.@"0")[tracked_inst_unwrapped.index];
return maybe_lost.file;
}
pub fn resolve(i: TrackedInst.Index, ip: *const InternPool) ?Zir.Inst.Index {
return (i.resolveFull(ip) orelse return null).inst;
}
pub fn toOptional(i: TrackedInst.Index) Optional {
return @enumFromInt(@intFromEnum(i));
}
pub const Optional = enum(u32) {
none = std.math.maxInt(u32),
_,
pub fn unwrap(opt: Optional) ?TrackedInst.Index {
return switch (opt) {
.none => null,
_ => @enumFromInt(@intFromEnum(opt)),
};
}
const debug_state = InternPool.debug_state;
};
pub const Unwrapped = struct {
tid: Zcu.PerThread.Id,
index: u32,
pub fn wrap(unwrapped: Unwrapped, ip: *const InternPool) TrackedInst.Index {
assert(@intFromEnum(unwrapped.tid) <= ip.getTidMask());
assert(unwrapped.index <= ip.getIndexMask(u32));
return @enumFromInt(@as(u32, @intFromEnum(unwrapped.tid)) << ip.tid_shift_32 |
unwrapped.index);
}
};
pub fn unwrap(tracked_inst_index: TrackedInst.Index, ip: *const InternPool) Unwrapped {
return .{
.tid = @enumFromInt(@intFromEnum(tracked_inst_index) >> ip.tid_shift_32 & ip.getTidMask()),
.index = @intFromEnum(tracked_inst_index) & ip.getIndexMask(u32),
};
}
const debug_state = InternPool.debug_state;
};
};
pub fn trackZir(
ip: *InternPool,
gpa: Allocator,
tid: Zcu.PerThread.Id,
key: TrackedInst,
) Allocator.Error!TrackedInst.Index {
const maybe_lost_key: TrackedInst.MaybeLost = .{
.file = key.file,
.inst = TrackedInst.MaybeLost.ZirIndex.wrap(key.inst),
};
const full_hash = Hash.hash(0, std.mem.asBytes(&maybe_lost_key));
const hash: u32 = @truncate(full_hash >> 32);
const shard = &ip.shards[@intCast(full_hash & (ip.shards.len - 1))];
var map = shard.shared.tracked_inst_map.acquire();
const Map = @TypeOf(map);
var map_mask = map.header().mask();
var map_index = hash;
while (true) : (map_index += 1) {
map_index &= map_mask;
const entry = &map.entries[map_index];
const index = entry.acquire().unwrap() orelse break;
if (entry.hash != hash) continue;
if (std.meta.eql(index.resolveFull(ip) orelse continue, key)) return index;
}
shard.mutate.tracked_inst_map.mutex.lock();
defer shard.mutate.tracked_inst_map.mutex.unlock();
if (map.entries != shard.shared.tracked_inst_map.entries) {
map = shard.shared.tracked_inst_map;
map_mask = map.header().mask();
map_index = hash;
}
while (true) : (map_index += 1) {
map_index &= map_mask;
const entry = &map.entries[map_index];
const index = entry.acquire().unwrap() orelse break;
if (entry.hash != hash) continue;
if (std.meta.eql(index.resolveFull(ip) orelse continue, key)) return index;
}
defer shard.mutate.tracked_inst_map.len += 1;
const local = ip.getLocal(tid);
const list = local.getMutableTrackedInsts(gpa);
try list.ensureUnusedCapacity(1);
const map_header = map.header().*;
if (shard.mutate.tracked_inst_map.len < map_header.capacity * 3 / 5) {
const entry = &map.entries[map_index];
entry.hash = hash;
const index = (TrackedInst.Index.Unwrapped{
.tid = tid,
.index = list.mutate.len,
}).wrap(ip);
list.appendAssumeCapacity(.{maybe_lost_key});
entry.release(index.toOptional());
return index;
}
const arena_state = &local.mutate.arena;
var arena = arena_state.promote(gpa);
defer arena_state.* = arena.state;
const new_map_capacity = map_header.capacity * 2;
const new_map_buf = try arena.allocator().alignedAlloc(
u8,
Map.alignment,
Map.entries_offset + new_map_capacity * @sizeOf(Map.Entry),
);
const new_map: Map = .{ .entries = @ptrCast(new_map_buf[Map.entries_offset..].ptr) };
new_map.header().* = .{ .capacity = new_map_capacity };
@memset(new_map.entries[0..new_map_capacity], .{ .value = .none, .hash = undefined });
const new_map_mask = new_map.header().mask();
map_index = 0;
while (map_index < map_header.capacity) : (map_index += 1) {
const entry = &map.entries[map_index];
const index = entry.value.unwrap() orelse continue;
const item_hash = entry.hash;
var new_map_index = item_hash;
while (true) : (new_map_index += 1) {
new_map_index &= new_map_mask;
const new_entry = &new_map.entries[new_map_index];
if (new_entry.value != .none) continue;
new_entry.* = .{
.value = index.toOptional(),
.hash = item_hash,
};
break;
}
}
map = new_map;
map_index = hash;
while (true) : (map_index += 1) {
map_index &= new_map_mask;
if (map.entries[map_index].value == .none) break;
}
const index = (TrackedInst.Index.Unwrapped{
.tid = tid,
.index = list.mutate.len,
}).wrap(ip);
list.appendAssumeCapacity(.{maybe_lost_key});
map.entries[map_index] = .{ .value = index.toOptional(), .hash = hash };
shard.shared.tracked_inst_map.release(new_map);
return index;
}
/// At the start of an incremental update, we update every entry in `tracked_insts` to include
/// the new ZIR index. Once this is done, we must update the hashmap metadata so that lookups
/// return correct entries where they already exist.
pub fn rehashTrackedInsts(
ip: *InternPool,
gpa: Allocator,
tid: Zcu.PerThread.Id,
) Allocator.Error!void {
assert(tid == .main); // we shouldn't have any other threads active right now
// TODO: this function doesn't handle OOM well. What should it do?
// We don't lock anything, as this function assumes that no other thread is
// accessing `tracked_insts`. This is necessary because we're going to be
// iterating the `TrackedInst`s in each `Local`, so we have to know that
// none will be added as we work.
// Figure out how big each shard need to be and store it in its mutate `len`.
for (ip.shards) |*shard| shard.mutate.tracked_inst_map.len = 0;
for (ip.locals) |*local| {
// `getMutableTrackedInsts` is okay only because no other thread is currently active.
// We need the `mutate` for the len.
for (local.getMutableTrackedInsts(gpa).viewAllowEmpty().items(.@"0")) |tracked_inst| {
if (tracked_inst.inst == .lost) continue; // we can ignore this one!
const full_hash = Hash.hash(0, std.mem.asBytes(&tracked_inst));
const shard = &ip.shards[@intCast(full_hash & (ip.shards.len - 1))];
shard.mutate.tracked_inst_map.len += 1;
}
}
const Map = Shard.Map(TrackedInst.Index.Optional);
const arena_state = &ip.getLocal(tid).mutate.arena;
// We know how big each shard must be, so ensure we have the capacity we need.
for (ip.shards) |*shard| {
const want_capacity = if (shard.mutate.tracked_inst_map.len == 0) 0 else cap: {
// We need to return a capacity of at least 2 to make sure we don't have the `Map(...).empty` value.
// For this reason, note the `+ 1` in the below expression. This matches the behavior of `trackZir`.
break :cap std.math.ceilPowerOfTwo(u32, shard.mutate.tracked_inst_map.len * 5 / 3 + 1) catch unreachable;
};
const have_capacity = shard.shared.tracked_inst_map.header().capacity; // no acquire because we hold the mutex
if (have_capacity >= want_capacity) {
if (have_capacity == 1) {
// The map is `.empty` -- we can't memset the entries, or we'll segfault, because
// the buffer is secretly constant.
} else {
@memset(shard.shared.tracked_inst_map.entries[0..have_capacity], .{ .value = .none, .hash = undefined });
}
continue;
}
var arena = arena_state.promote(gpa);
defer arena_state.* = arena.state;
const new_map_buf = try arena.allocator().alignedAlloc(
u8,
Map.alignment,
Map.entries_offset + want_capacity * @sizeOf(Map.Entry),
);
const new_map: Map = .{ .entries = @ptrCast(new_map_buf[Map.entries_offset..].ptr) };
new_map.header().* = .{ .capacity = want_capacity };
@memset(new_map.entries[0..want_capacity], .{ .value = .none, .hash = undefined });
shard.shared.tracked_inst_map.release(new_map);
}
// Now, actually insert the items.
for (ip.locals, 0..) |*local, local_tid| {
// `getMutableTrackedInsts` is okay only because no other thread is currently active.
// We need the `mutate` for the len.
for (local.getMutableTrackedInsts(gpa).viewAllowEmpty().items(.@"0"), 0..) |tracked_inst, local_inst_index| {
if (tracked_inst.inst == .lost) continue; // we can ignore this one!
const full_hash = Hash.hash(0, std.mem.asBytes(&tracked_inst));
const hash: u32 = @truncate(full_hash >> 32);
const shard = &ip.shards[@intCast(full_hash & (ip.shards.len - 1))];
const map = shard.shared.tracked_inst_map; // no acquire because we hold the mutex
const map_mask = map.header().mask();
var map_index = hash;
const entry = while (true) : (map_index += 1) {
map_index &= map_mask;
const entry = &map.entries[map_index];
if (entry.acquire() == .none) break entry;
};
const index = TrackedInst.Index.Unwrapped.wrap(.{
.tid = @enumFromInt(local_tid),
.index = @intCast(local_inst_index),
}, ip);
entry.hash = hash;
entry.release(index.toOptional());
}
}
}
/// Analysis Unit. Represents a single entity which undergoes semantic analysis.
/// This is the "source" of an incremental dependency edge.
pub const AnalUnit = packed struct(u64) {
kind: Kind,
id: u32,
pub const Kind = enum(u32) {
@"comptime",
nav_val,
nav_ty,
type,
func,
memoized_state,
};
pub const Unwrapped = union(Kind) {
/// This `AnalUnit` analyzes the body of the given `comptime` declaration.
@"comptime": ComptimeUnit.Id,
/// This `AnalUnit` resolves the value of the given `Nav`.
nav_val: Nav.Index,
/// This `AnalUnit` resolves the type of the given `Nav`.
nav_ty: Nav.Index,
/// This `AnalUnit` resolves the given `struct`/`union`/`enum` type.
/// Generated tag enums are never used here (they do not undergo type resolution).
type: InternPool.Index,
/// This `AnalUnit` analyzes the body of the given runtime function.
func: InternPool.Index,
/// This `AnalUnit` resolves all state which is memoized in fields on `Zcu`.
memoized_state: MemoizedStateStage,
};
pub fn unwrap(au: AnalUnit) Unwrapped {
return switch (au.kind) {
inline else => |tag| @unionInit(
Unwrapped,
@tagName(tag),
@enumFromInt(au.id),
),
};
}
pub fn wrap(raw: Unwrapped) AnalUnit {
return switch (raw) {
inline else => |id, tag| .{
.kind = tag,
.id = @intFromEnum(id),
},
};
}
pub fn toOptional(as: AnalUnit) Optional {
return @enumFromInt(@as(u64, @bitCast(as)));
}
pub const Optional = enum(u64) {
none = std.math.maxInt(u64),
_,
pub fn unwrap(opt: Optional) ?AnalUnit {
return switch (opt) {
.none => null,
_ => @bitCast(@intFromEnum(opt)),
};
}
};
};
pub const MemoizedStateStage = enum(u32) {
/// Everything other than panics and `VaList`.
main,
/// Everything within `std.builtin.Panic`.
/// Since the panic handler is user-provided, this must be able to reference the other memoized state.
panic,
/// Specifically `std.builtin.VaList`. See `Zcu.BuiltinDecl.stage`.
va_list,
};
pub const ComptimeUnit = extern struct {
zir_index: TrackedInst.Index,
namespace: NamespaceIndex,
comptime {
assert(std.meta.hasUniqueRepresentation(ComptimeUnit));
}
pub const Id = enum(u32) {
_,
const Unwrapped = struct {
tid: Zcu.PerThread.Id,
index: u32,
fn wrap(unwrapped: Unwrapped, ip: *const InternPool) ComptimeUnit.Id {
assert(@intFromEnum(unwrapped.tid) <= ip.getTidMask());
assert(unwrapped.index <= ip.getIndexMask(u32));
return @enumFromInt(@as(u32, @intFromEnum(unwrapped.tid)) << ip.tid_shift_32 |
unwrapped.index);
}
};
fn unwrap(id: Id, ip: *const InternPool) Unwrapped {
return .{
.tid = @enumFromInt(@intFromEnum(id) >> ip.tid_shift_32 & ip.getTidMask()),
.index = @intFromEnum(id) & ip.getIndexMask(u31),
};
}
const debug_state = InternPool.debug_state;
};
};
/// Named Addressable Value. Represents a global value with a name and address. This name may be
/// generated, and the type (and hence address) may be comptime-only. A `Nav` whose type has runtime
/// bits is sent to the linker to be emitted to the binary.
///
/// * Every ZIR `declaration` which is not a `comptime` declaration has a `Nav` (post-instantiation)
/// which stores the declaration's resolved value.
/// * Generic instances have a `Nav` corresponding to the instantiated function.
/// * `@extern` calls create a `Nav` whose value is a `.@"extern"`.
///
/// This data structure is optimized for the `analysis_info != null` case, because this is much more
/// common in practice; the other case is used only for externs and for generic instances. At the time
/// of writing, in the compiler itself, around 74% of all `Nav`s have `analysis_info != null`.
/// (Specifically, 104225 / 140923)
///
/// `Nav.Repr` is the in-memory representation.
pub const Nav = struct {
/// The unqualified name of this `Nav`. Namespace lookups use this name, and error messages may use it.
/// Additionally, extern `Nav`s (i.e. those whose value is an `extern`) use this name.
name: NullTerminatedString,
/// The fully-qualified name of this `Nav`.
fqn: NullTerminatedString,
/// This field is populated iff this `Nav` is resolved by semantic analysis.
/// If this is `null`, then `status == .fully_resolved` always.
analysis: ?struct {
namespace: NamespaceIndex,
zir_index: TrackedInst.Index,
},
/// TODO: this is a hack! If #20663 isn't accepted, let's figure out something a bit better.
is_usingnamespace: bool,
status: union(enum) {
/// This `Nav` is pending semantic analysis.
unresolved,
/// The type of this `Nav` is resolved; the value is queued for resolution.
type_resolved: struct {
type: InternPool.Index,
alignment: Alignment,
@"linksection": OptionalNullTerminatedString,
@"addrspace": std.builtin.AddressSpace,
is_const: bool,
is_threadlocal: bool,
/// This field is whether this `Nav` is a literal `extern` definition.
/// It does *not* tell you whether this might alias an extern fn (see #21027).
is_extern_decl: bool,
},
/// The value of this `Nav` is resolved.
fully_resolved: struct {
val: InternPool.Index,
alignment: Alignment,
@"linksection": OptionalNullTerminatedString,
@"addrspace": std.builtin.AddressSpace,
},
},
/// Asserts that `status != .unresolved`.
pub fn typeOf(nav: Nav, ip: *const InternPool) InternPool.Index {
return switch (nav.status) {
.unresolved => unreachable,
.type_resolved => |r| r.type,
.fully_resolved => |r| ip.typeOf(r.val),
};
}
/// This function is intended to be used by code generation, since semantic
/// analysis will ensure that any `Nav` which is potentially `extern` is
/// fully resolved.
/// Asserts that `status == .fully_resolved`.
pub fn getResolvedExtern(nav: Nav, ip: *const InternPool) ?Key.Extern {
assert(nav.status == .fully_resolved);
return nav.getExtern(ip);
}
/// Always returns `null` for `status == .type_resolved`. This function is inteded
/// to be used by code generation, since semantic analysis will ensure that any `Nav`
/// which is potentially `extern` is fully resolved.
/// Asserts that `status != .unresolved`.
pub fn getExtern(nav: Nav, ip: *const InternPool) ?Key.Extern {
return switch (nav.status) {
.unresolved => unreachable,
.type_resolved => null,
.fully_resolved => |r| switch (ip.indexToKey(r.val)) {
.@"extern" => |e| e,
else => null,
},
};
}
/// Asserts that `status != .unresolved`.
pub fn getAddrspace(nav: Nav) std.builtin.AddressSpace {
return switch (nav.status) {
.unresolved => unreachable,
.type_resolved => |r| r.@"addrspace",
.fully_resolved => |r| r.@"addrspace",
};
}
/// Asserts that `status != .unresolved`.
pub fn getAlignment(nav: Nav) Alignment {
return switch (nav.status) {
.unresolved => unreachable,
.type_resolved => |r| r.alignment,
.fully_resolved => |r| r.alignment,
};
}
/// Asserts that `status != .unresolved`.
pub fn getLinkSection(nav: Nav) OptionalNullTerminatedString {
return switch (nav.status) {
.unresolved => unreachable,
.type_resolved => |r| r.@"linksection",
.fully_resolved => |r| r.@"linksection",
};
}
/// Asserts that `status != .unresolved`.
pub fn isThreadlocal(nav: Nav, ip: *const InternPool) bool {
return switch (nav.status) {
.unresolved => unreachable,
.type_resolved => |r| r.is_threadlocal,
.fully_resolved => |r| switch (ip.indexToKey(r.val)) {
.@"extern" => |e| e.is_threadlocal,
.variable => |v| v.is_threadlocal,
else => false,
},
};
}
pub fn isFn(nav: Nav, ip: *const InternPool) bool {
return switch (nav.status) {
.unresolved => unreachable,
.type_resolved => |r| {
const tag = ip.zigTypeTag(r.type);
return tag == .@"fn";
},
.fully_resolved => |r| {
const tag = ip.zigTypeTag(ip.typeOf(r.val));
return tag == .@"fn";
},
};
}
/// If this returns `true`, then a pointer to this `Nav` might actually be encoded as a pointer
/// to some other `Nav` due to an extern definition or extern alias (see #21027).
/// This query is valid on `Nav`s for whom only the type is resolved.
/// Asserts that `status != .unresolved`.
pub fn isExternOrFn(nav: Nav, ip: *const InternPool) bool {
return switch (nav.status) {
.unresolved => unreachable,
.type_resolved => |r| {
if (r.is_extern_decl) return true;
const tag = ip.zigTypeTag(r.type);
if (tag == .@"fn") return true;
return false;
},
.fully_resolved => |r| {
if (ip.indexToKey(r.val) == .@"extern") return true;
const tag = ip.zigTypeTag(ip.typeOf(r.val));
if (tag == .@"fn") return true;
return false;
},
};
}
/// Get the ZIR instruction corresponding to this `Nav`, used to resolve source locations.
/// This is a `declaration`.
pub fn srcInst(nav: Nav, ip: *const InternPool) TrackedInst.Index {
if (nav.analysis) |a| {
return a.zir_index;
}
// A `Nav` which does not undergo analysis always has a resolved value.
return switch (ip.indexToKey(nav.status.fully_resolved.val)) {
.func => |func| {
// Since `analysis` was not populated, this must be an instantiation.
// Go up to the generic owner and consult *its* `analysis` field.
const go_nav = ip.getNav(ip.indexToKey(func.generic_owner).func.owner_nav);
return go_nav.analysis.?.zir_index;
},
.@"extern" => |@"extern"| @"extern".zir_index, // extern / @extern
else => unreachable,
};
}
pub const Index = enum(u32) {
_,
pub const Optional = enum(u32) {
none = std.math.maxInt(u32),
_,
pub fn unwrap(opt: Optional) ?Nav.Index {
return switch (opt) {
.none => null,
_ => @enumFromInt(@intFromEnum(opt)),
};
}
const debug_state = InternPool.debug_state;
};
pub fn toOptional(i: Nav.Index) Optional {
return @enumFromInt(@intFromEnum(i));
}
const Unwrapped = struct {
tid: Zcu.PerThread.Id,
index: u32,
fn wrap(unwrapped: Unwrapped, ip: *const InternPool) Nav.Index {
assert(@intFromEnum(unwrapped.tid) <= ip.getTidMask());
assert(unwrapped.index <= ip.getIndexMask(u32));
return @enumFromInt(@as(u32, @intFromEnum(unwrapped.tid)) << ip.tid_shift_32 |
unwrapped.index);
}
};
fn unwrap(nav_index: Nav.Index, ip: *const InternPool) Unwrapped {
return .{
.tid = @enumFromInt(@intFromEnum(nav_index) >> ip.tid_shift_32 & ip.getTidMask()),
.index = @intFromEnum(nav_index) & ip.getIndexMask(u32),
};
}
const debug_state = InternPool.debug_state;
};
/// The compact in-memory representation of a `Nav`.
/// 26 bytes.
const Repr = struct {
name: NullTerminatedString,
fqn: NullTerminatedString,
// The following 1 fields are either both populated, or both `.none`.
analysis_namespace: OptionalNamespaceIndex,
analysis_zir_index: TrackedInst.Index.Optional,
/// Populated only if `bits.status != .unresolved`.
type_or_val: InternPool.Index,
/// Populated only if `bits.status != .unresolved`.
@"linksection": OptionalNullTerminatedString,
bits: Bits,
const Bits = packed struct(u16) {
status: enum(u2) { unresolved, type_resolved, fully_resolved, type_resolved_extern_decl },
/// Populated only if `bits.status != .unresolved`.
alignment: Alignment,
/// Populated only if `bits.status != .unresolved`.
@"addrspace": std.builtin.AddressSpace,
/// Populated only if `bits.status == .type_resolved`.
is_const: bool,
/// Populated only if `bits.status == .type_resolved`.
is_threadlocal: bool,
is_usingnamespace: bool,
};
fn unpack(repr: Repr) Nav {
return .{
.name = repr.name,
.fqn = repr.fqn,
.analysis = if (repr.analysis_namespace.unwrap()) |namespace| .{
.namespace = namespace,
.zir_index = repr.analysis_zir_index.unwrap().?,
} else a: {
assert(repr.analysis_zir_index == .none);
break :a null;
},
.is_usingnamespace = repr.bits.is_usingnamespace,
.status = switch (repr.bits.status) {
.unresolved => .unresolved,
.type_resolved, .type_resolved_extern_decl => .{ .type_resolved = .{
.type = repr.type_or_val,
.alignment = repr.bits.alignment,
.@"linksection" = repr.@"linksection",
.@"addrspace" = repr.bits.@"addrspace",
.is_const = repr.bits.is_const,
.is_threadlocal = repr.bits.is_threadlocal,
.is_extern_decl = repr.bits.status == .type_resolved_extern_decl,
} },
.fully_resolved => .{ .fully_resolved = .{
.val = repr.type_or_val,
.alignment = repr.bits.alignment,
.@"linksection" = repr.@"linksection",
.@"addrspace" = repr.bits.@"addrspace",
} },
},
};
}
};
fn pack(nav: Nav) Repr {
// Note that in the `unresolved` case, we do not mark fields as `undefined`, even though they should not be used.
// This is to avoid writing undefined bytes to disk when serializing buffers.
return .{
.name = nav.name,
.fqn = nav.fqn,
.analysis_namespace = if (nav.analysis) |a| a.namespace.toOptional() else .none,
.analysis_zir_index = if (nav.analysis) |a| a.zir_index.toOptional() else .none,
.type_or_val = switch (nav.status) {
.unresolved => .none,
.type_resolved => |r| r.type,
.fully_resolved => |r| r.val,
},
.@"linksection" = switch (nav.status) {
.unresolved => .none,
.type_resolved => |r| r.@"linksection",
.fully_resolved => |r| r.@"linksection",
},
.bits = switch (nav.status) {
.unresolved => .{
.status = .unresolved,
.alignment = .none,
.@"addrspace" = .generic,
.is_usingnamespace = nav.is_usingnamespace,
.is_const = false,
.is_threadlocal = false,
},
.type_resolved => |r| .{
.status = if (r.is_extern_decl) .type_resolved_extern_decl else .type_resolved,
.alignment = r.alignment,
.@"addrspace" = r.@"addrspace",
.is_usingnamespace = nav.is_usingnamespace,
.is_const = r.is_const,
.is_threadlocal = r.is_threadlocal,
},
.fully_resolved => |r| .{
.status = .fully_resolved,
.alignment = r.alignment,
.@"addrspace" = r.@"addrspace",
.is_usingnamespace = nav.is_usingnamespace,
.is_const = false,
.is_threadlocal = false,
},
},
};
}
};
pub const Dependee = union(enum) {
src_hash: TrackedInst.Index,
nav_val: Nav.Index,
nav_ty: Nav.Index,
interned: Index,
zon_file: FileIndex,
embed_file: Zcu.EmbedFile.Index,
namespace: TrackedInst.Index,
namespace_name: NamespaceNameKey,
memoized_state: MemoizedStateStage,
};
pub fn removeDependenciesForDepender(ip: *InternPool, gpa: Allocator, depender: AnalUnit) void {
var opt_idx = (ip.first_dependency.fetchSwapRemove(depender) orelse return).value.toOptional();
while (opt_idx.unwrap()) |idx| {
const dep = ip.dep_entries.items[@intFromEnum(idx)];
opt_idx = dep.next_dependee;
const prev_idx = dep.prev.unwrap() orelse {
// This entry is the start of a list in some `*_deps`.
// We cannot easily remove this mapping, so this must remain as a dummy entry.
ip.dep_entries.items[@intFromEnum(idx)].depender = .none;
continue;
};
ip.dep_entries.items[@intFromEnum(prev_idx)].next = dep.next;
if (dep.next.unwrap()) |next_idx| {
ip.dep_entries.items[@intFromEnum(next_idx)].prev = dep.prev;
}
ip.free_dep_entries.append(gpa, idx) catch {
// This memory will be reclaimed on the next garbage collection.
// Thus, we do not need to propagate this error.
};
}
}
pub const DependencyIterator = struct {
ip: *const InternPool,
next_entry: DepEntry.Index.Optional,
pub fn next(it: *DependencyIterator) ?AnalUnit {
while (true) {
const idx = it.next_entry.unwrap() orelse return null;
const entry = it.ip.dep_entries.items[@intFromEnum(idx)];
it.next_entry = entry.next;
if (entry.depender.unwrap()) |depender| return depender;
}
}
};
pub fn dependencyIterator(ip: *const InternPool, dependee: Dependee) DependencyIterator {
const first_entry = switch (dependee) {
.src_hash => |x| ip.src_hash_deps.get(x),
.nav_val => |x| ip.nav_val_deps.get(x),
.nav_ty => |x| ip.nav_ty_deps.get(x),
.interned => |x| ip.interned_deps.get(x),
.zon_file => |x| ip.zon_file_deps.get(x),
.embed_file => |x| ip.embed_file_deps.get(x),
.namespace => |x| ip.namespace_deps.get(x),
.namespace_name => |x| ip.namespace_name_deps.get(x),
.memoized_state => |stage| switch (stage) {
.main => ip.memoized_state_main_deps.unwrap(),
.panic => ip.memoized_state_panic_deps.unwrap(),
.va_list => ip.memoized_state_va_list_deps.unwrap(),
},
} orelse return .{
.ip = ip,
.next_entry = .none,
};
return .{
.ip = ip,
.next_entry = first_entry.toOptional(),
};
}
pub fn addDependency(ip: *InternPool, gpa: Allocator, depender: AnalUnit, dependee: Dependee) Allocator.Error!void {
const first_depender_dep: DepEntry.Index.Optional = if (ip.first_dependency.get(depender)) |idx| dep: {
// The entry already exists, so there is capacity to overwrite it later.
break :dep idx.toOptional();
} else none: {
// Ensure there is capacity available to add this dependency later.
try ip.first_dependency.ensureUnusedCapacity(gpa, 1);
break :none .none;
};
// We're very likely to need space for a new entry - reserve it now to avoid
// the need for error cleanup logic.
if (ip.free_dep_entries.items.len == 0) {
try ip.dep_entries.ensureUnusedCapacity(gpa, 1);
}
// This block should allocate an entry and prepend it to the relevant `*_deps` list.
// The `next` field should be correctly initialized; all other fields may be undefined.
const new_index: DepEntry.Index = switch (dependee) {
.memoized_state => |stage| new_index: {
const deps = switch (stage) {
.main => &ip.memoized_state_main_deps,
.panic => &ip.memoized_state_panic_deps,
.va_list => &ip.memoized_state_va_list_deps,
};
if (deps.unwrap()) |first| {
if (ip.dep_entries.items[@intFromEnum(first)].depender == .none) {
// Dummy entry, so we can reuse it rather than allocating a new one!
break :new_index first;
}
}
// Prepend a new dependency.
const new_index: DepEntry.Index, const ptr = if (ip.free_dep_entries.pop()) |new_index| new: {
break :new .{ new_index, &ip.dep_entries.items[@intFromEnum(new_index)] };
} else .{ @enumFromInt(ip.dep_entries.items.len), ip.dep_entries.addOneAssumeCapacity() };
if (deps.unwrap()) |old_first| {
ptr.next = old_first.toOptional();
ip.dep_entries.items[@intFromEnum(old_first)].prev = new_index.toOptional();
} else {
ptr.next = .none;
}
deps.* = new_index.toOptional();
break :new_index new_index;
},
inline else => |dependee_payload, tag| new_index: {
const gop = try switch (tag) {
.src_hash => ip.src_hash_deps,
.nav_val => ip.nav_val_deps,
.nav_ty => ip.nav_ty_deps,
.interned => ip.interned_deps,
.zon_file => ip.zon_file_deps,
.embed_file => ip.embed_file_deps,
.namespace => ip.namespace_deps,
.namespace_name => ip.namespace_name_deps,
.memoized_state => comptime unreachable,
}.getOrPut(gpa, dependee_payload);
if (gop.found_existing and ip.dep_entries.items[@intFromEnum(gop.value_ptr.*)].depender == .none) {
// Dummy entry, so we can reuse it rather than allocating a new one!
break :new_index gop.value_ptr.*;
}
// Prepend a new dependency.
const new_index: DepEntry.Index, const ptr = if (ip.free_dep_entries.pop()) |new_index| new: {
break :new .{ new_index, &ip.dep_entries.items[@intFromEnum(new_index)] };
} else .{ @enumFromInt(ip.dep_entries.items.len), ip.dep_entries.addOneAssumeCapacity() };
if (gop.found_existing) {
ptr.next = gop.value_ptr.*.toOptional();
ip.dep_entries.items[@intFromEnum(gop.value_ptr.*)].prev = new_index.toOptional();
} else {
ptr.next = .none;
}
gop.value_ptr.* = new_index;
break :new_index new_index;
},
};
ip.dep_entries.items[@intFromEnum(new_index)].depender = depender.toOptional();
ip.dep_entries.items[@intFromEnum(new_index)].prev = .none;
ip.dep_entries.items[@intFromEnum(new_index)].next_dependee = first_depender_dep;
ip.first_dependency.putAssumeCapacity(depender, new_index);
}
/// String is the name whose existence the dependency is on.
/// DepEntry.Index refers to the first such dependency.
pub const NamespaceNameKey = struct {
/// The instruction (`struct_decl` etc) which owns the namespace in question.
namespace: TrackedInst.Index,
/// The name whose existence the dependency is on.
name: NullTerminatedString,
};
pub const DepEntry = extern struct {
/// If null, this is a dummy entry. `next_dependee` is undefined. This is the first
/// entry in one of `*_deps`, and does not appear in any list by `first_dependency`,
/// but is not in `free_dep_entries` since `*_deps` stores a reference to it.
depender: AnalUnit.Optional,
/// Index into `dep_entries` forming a doubly linked list of all dependencies on this dependee.
/// Used to iterate all dependers for a given dependee during an update.
/// null if this is the end of the list.
next: DepEntry.Index.Optional,