authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-07-16 20:52:50-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-07-16 20:52:50-04:00
log97bfeac13f89e1b5a22fcd7d4705341b4c3e1950
tree4a3e23a8b3908450b23f2dbba72e5f6c091d7114
parent0fa24b6b7568557c29c9b3ee213ce2b06fcd6367

self-hosted: create tmp dir for .o files and emit .o file for fn


20 files changed, 808 insertions(+), 175 deletions(-)

CMakeLists.txt+1
......@@ -479,6 +479,7 @@ set(ZIG_STD_FILES
479479 "index.zig"
480480 "io.zig"
481481 "json.zig"
482 "lazy_init.zig"
482483 "linked_list.zig"
483484 "macho.zig"
484485 "math/acos.zig"
src-self-hosted/codegen.zig+78-8
......@@ -1,19 +1,22 @@
11const std = @import("std");
2const builtin = @import("builtin");
23const Compilation = @import("compilation.zig").Compilation;
3// we go through llvm instead of c for 2 reasons:
4// 1. to avoid accidentally calling the non-thread-safe functions
5// 2. patch up some of the types to remove nullability
64const llvm = @import("llvm.zig");
5const c = @import("c.zig");
76const ir = @import("ir.zig");
87const Value = @import("value.zig").Value;
98const Type = @import("type.zig").Type;
109const event = std.event;
1110const assert = std.debug.assert;
11const DW = std.dwarf;
1212
1313pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code) !void {
1414 fn_val.base.ref();
1515 defer fn_val.base.deref(comp);
16 defer code.destroy(comp.a());
16 defer code.destroy(comp.gpa());
17
18 var output_path = try await (async comp.createRandomOutputPath(comp.target.oFileExt()) catch unreachable);
19 errdefer output_path.deinit();
1720
1821 const llvm_handle = try comp.event_loop_local.getAnyLlvmContext();
1922 defer llvm_handle.release(comp.event_loop_local);
......@@ -23,13 +26,56 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code)
2326 const module = llvm.ModuleCreateWithNameInContext(comp.name.ptr(), context) orelse return error.OutOfMemory;
2427 defer llvm.DisposeModule(module);
2528
29 llvm.SetTarget(module, comp.llvm_triple.ptr());
30 llvm.SetDataLayout(module, comp.target_layout_str);
31
32 if (comp.target.getObjectFormat() == builtin.ObjectFormat.coff) {
33 llvm.AddModuleCodeViewFlag(module);
34 } else {
35 llvm.AddModuleDebugInfoFlag(module);
36 }
37
2638 const builder = llvm.CreateBuilderInContext(context) orelse return error.OutOfMemory;
2739 defer llvm.DisposeBuilder(builder);
2840
41 const dibuilder = llvm.CreateDIBuilder(module, true) orelse return error.OutOfMemory;
42 defer llvm.DisposeDIBuilder(dibuilder);
43
44 // Don't use ZIG_VERSION_STRING here. LLVM misparses it when it includes
45 // the git revision.
46 const producer = try std.Buffer.allocPrint(
47 &code.arena.allocator,
48 "zig {}.{}.{}",
49 u32(c.ZIG_VERSION_MAJOR),
50 u32(c.ZIG_VERSION_MINOR),
51 u32(c.ZIG_VERSION_PATCH),
52 );
53 const flags = c"";
54 const runtime_version = 0;
55 const compile_unit_file = llvm.CreateFile(
56 dibuilder,
57 comp.name.ptr(),
58 comp.root_package.root_src_dir.ptr(),
59 ) orelse return error.OutOfMemory;
60 const is_optimized = comp.build_mode != builtin.Mode.Debug;
61 const compile_unit = llvm.CreateCompileUnit(
62 dibuilder,
63 DW.LANG_C99,
64 compile_unit_file,
65 producer.ptr(),
66 is_optimized,
67 flags,
68 runtime_version,
69 c"",
70 0,
71 !comp.strip,
72 ) orelse return error.OutOfMemory;
73
2974 var ofile = ObjectFile{
3075 .comp = comp,
3176 .module = module,
3277 .builder = builder,
78 .dibuilder = dibuilder,
3379 .context = context,
3480 .lock = event.Lock.init(comp.loop),
3581 };
......@@ -41,8 +87,7 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code)
4187 // LLVMSetModuleInlineAsm(g->module, buf_ptr(&g->global_asm));
4288 //}
4389
44 // TODO
45 //ZigLLVMDIBuilderFinalize(g->dbuilder);
90 llvm.DIBuilderFinalize(dibuilder);
4691
4792 if (comp.verbose_llvm_ir) {
4893 llvm.DumpModule(ofile.module);
......@@ -53,17 +98,42 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code)
5398 var error_ptr: ?[*]u8 = null;
5499 _ = llvm.VerifyModule(ofile.module, llvm.AbortProcessAction, &error_ptr);
55100 }
101
102 assert(comp.emit_file_type == Compilation.Emit.Binary); // TODO support other types
103
104 const is_small = comp.build_mode == builtin.Mode.ReleaseSmall;
105 const is_debug = comp.build_mode == builtin.Mode.Debug;
106
107 var err_msg: [*]u8 = undefined;
108 // TODO integrate this with evented I/O
109 if (llvm.TargetMachineEmitToFile(
110 comp.target_machine,
111 module,
112 output_path.ptr(),
113 llvm.EmitBinary,
114 &err_msg,
115 is_debug,
116 is_small,
117 )) {
118 if (std.debug.runtime_safety) {
119 std.debug.panic("unable to write object file {}: {s}\n", output_path.toSliceConst(), err_msg);
120 }
121 return error.WritingObjectFileFailed;
122 }
123 //validate_inline_fns(g); TODO
124 fn_val.containing_object = output_path;
56125}
57126
58127pub const ObjectFile = struct {
59128 comp: *Compilation,
60129 module: llvm.ModuleRef,
61130 builder: llvm.BuilderRef,
131 dibuilder: *llvm.DIBuilder,
62132 context: llvm.ContextRef,
63133 lock: event.Lock,
64134
65 fn a(self: *ObjectFile) *std.mem.Allocator {
66 return self.comp.a();
135 fn gpa(self: *ObjectFile) *std.mem.Allocator {
136 return self.comp.gpa();
67137 }
68138};
69139
src-self-hosted/compilation.zig+270-65
......@@ -26,16 +26,31 @@ const Value = @import("value.zig").Value;
2626const Type = Value.Type;
2727const Span = errmsg.Span;
2828const codegen = @import("codegen.zig");
29const Package = @import("package.zig").Package;
2930
3031/// Data that is local to the event loop.
3132pub const EventLoopLocal = struct {
3233 loop: *event.Loop,
3334 llvm_handle_pool: std.atomic.Stack(llvm.ContextRef),
3435
35 fn init(loop: *event.Loop) EventLoopLocal {
36 /// TODO pool these so that it doesn't have to lock
37 prng: event.Locked(std.rand.DefaultPrng),
38
39 var lazy_init_targets = std.lazyInit(void);
40
41 fn init(loop: *event.Loop) !EventLoopLocal {
42 lazy_init_targets.get() orelse {
43 Target.initializeAll();
44 lazy_init_targets.resolve();
45 };
46
47 var seed_bytes: [@sizeOf(u64)]u8 = undefined;
48 try std.os.getRandomBytes(seed_bytes[0..]);
49 const seed = std.mem.readInt(seed_bytes, u64, builtin.Endian.Big);
3650 return EventLoopLocal{
3751 .loop = loop,
3852 .llvm_handle_pool = std.atomic.Stack(llvm.ContextRef).init(),
53 .prng = event.Locked(std.rand.DefaultPrng).init(loop, std.rand.DefaultPrng.init(seed)),
3954 };
4055 }
4156
......@@ -76,10 +91,16 @@ pub const Compilation = struct {
7691 event_loop_local: *EventLoopLocal,
7792 loop: *event.Loop,
7893 name: Buffer,
94 llvm_triple: Buffer,
7995 root_src_path: ?[]const u8,
8096 target: Target,
97 llvm_target: llvm.TargetRef,
8198 build_mode: builtin.Mode,
8299 zig_lib_dir: []const u8,
100 zig_std_dir: []const u8,
101
102 /// lazily created when we need it
103 tmp_dir: event.Future(BuildError![]u8),
83104
84105 version_major: u32,
85106 version_minor: u32,
......@@ -106,8 +127,16 @@ pub const Compilation = struct {
106127 lib_dirs: []const []const u8,
107128 rpath_list: []const []const u8,
108129 assembly_files: []const []const u8,
130
131 /// paths that are explicitly provided by the user to link against
109132 link_objects: []const []const u8,
110133
134 /// functions that have their own objects that we need to link
135 /// it uses an optional pointer so that tombstone removals are possible
136 fn_link_set: event.Locked(FnLinkSet),
137
138 pub const FnLinkSet = std.LinkedList(?*Value.Fn);
139
111140 windows_subsystem_windows: bool,
112141 windows_subsystem_console: bool,
113142
......@@ -141,7 +170,7 @@ pub const Compilation = struct {
141170
142171 /// Before code generation starts, must wait on this group to make sure
143172 /// the build is complete.
144 build_group: event.Group(BuildError!void),
173 prelink_group: event.Group(BuildError!void),
145174
146175 compile_errors: event.Locked(CompileErrList),
147176
......@@ -155,6 +184,16 @@ pub const Compilation = struct {
155184 false_value: *Value.Bool,
156185 noreturn_value: *Value.NoReturn,
157186
187 target_machine: llvm.TargetMachineRef,
188 target_data_ref: llvm.TargetDataRef,
189 target_layout_str: [*]u8,
190
191 /// for allocating things which have the same lifetime as this Compilation
192 arena_allocator: std.heap.ArenaAllocator,
193
194 root_package: *Package,
195 std_package: *Package,
196
158197 const CompileErrList = std.ArrayList(*errmsg.Msg);
159198
160199 // TODO handle some of these earlier and report them in a way other than error codes
......@@ -195,6 +234,9 @@ pub const Compilation = struct {
195234 BufferTooSmall,
196235 Unimplemented, // TODO remove this one
197236 SemanticAnalysisFailed, // TODO remove this one
237 ReadOnlyFileSystem,
238 LinkQuotaExceeded,
239 EnvironmentVariableNotFound,
198240 };
199241
200242 pub const Event = union(enum) {
......@@ -234,31 +276,31 @@ pub const Compilation = struct {
234276 event_loop_local: *EventLoopLocal,
235277 name: []const u8,
236278 root_src_path: ?[]const u8,
237 target: *const Target,
279 target: Target,
238280 kind: Kind,
239281 build_mode: builtin.Mode,
282 is_static: bool,
240283 zig_lib_dir: []const u8,
241284 cache_dir: []const u8,
242285 ) !*Compilation {
243286 const loop = event_loop_local.loop;
244
245 var name_buffer = try Buffer.init(loop.allocator, name);
246 errdefer name_buffer.deinit();
247
248 const events = try event.Channel(Event).create(loop, 0);
249 errdefer events.destroy();
250
251 const comp = try loop.allocator.create(Compilation{
287 const comp = try event_loop_local.loop.allocator.create(Compilation{
252288 .loop = loop,
289 .arena_allocator = std.heap.ArenaAllocator.init(loop.allocator),
253290 .event_loop_local = event_loop_local,
254 .events = events,
255 .name = name_buffer,
291 .events = undefined,
256292 .root_src_path = root_src_path,
257 .target = target.*,
293 .target = target,
294 .llvm_target = undefined,
258295 .kind = kind,
259296 .build_mode = build_mode,
260297 .zig_lib_dir = zig_lib_dir,
298 .zig_std_dir = undefined,
261299 .cache_dir = cache_dir,
300 .tmp_dir = event.Future(BuildError![]u8).init(loop),
301
302 .name = undefined,
303 .llvm_triple = undefined,
262304
263305 .version_major = 0,
264306 .version_minor = 0,
......@@ -283,7 +325,7 @@ pub const Compilation = struct {
283325 .is_test = false,
284326 .each_lib_rpath = false,
285327 .strip = false,
286 .is_static = false,
328 .is_static = is_static,
287329 .linker_rdynamic = false,
288330 .clang_argv = [][]const u8{},
289331 .llvm_argv = [][]const u8{},
......@@ -291,9 +333,10 @@ pub const Compilation = struct {
291333 .rpath_list = [][]const u8{},
292334 .assembly_files = [][]const u8{},
293335 .link_objects = [][]const u8{},
336 .fn_link_set = event.Locked(FnLinkSet).init(loop, FnLinkSet.init()),
294337 .windows_subsystem_windows = false,
295338 .windows_subsystem_console = false,
296 .link_libs_list = ArrayList(*LinkLib).init(loop.allocator),
339 .link_libs_list = undefined,
297340 .libc_link_lib = null,
298341 .err_color = errmsg.Color.Auto,
299342 .darwin_frameworks = [][]const u8{},
......@@ -303,7 +346,7 @@ pub const Compilation = struct {
303346 .emit_file_type = Emit.Binary,
304347 .link_out_file = null,
305348 .exported_symbol_names = event.Locked(Decl.Table).init(loop, Decl.Table.init(loop.allocator)),
306 .build_group = event.Group(BuildError!void).init(loop),
349 .prelink_group = event.Group(BuildError!void).init(loop),
307350 .compile_errors = event.Locked(CompileErrList).init(loop, CompileErrList.init(loop.allocator)),
308351
309352 .meta_type = undefined,
......@@ -314,13 +357,82 @@ pub const Compilation = struct {
314357 .false_value = undefined,
315358 .noreturn_type = undefined,
316359 .noreturn_value = undefined,
360
361 .target_machine = undefined,
362 .target_data_ref = undefined,
363 .target_layout_str = undefined,
364
365 .root_package = undefined,
366 .std_package = undefined,
317367 });
368 errdefer {
369 comp.arena_allocator.deinit();
370 comp.loop.allocator.destroy(comp);
371 }
372
373 comp.name = try Buffer.init(comp.arena(), name);
374 comp.llvm_triple = try target.getTriple(comp.arena());
375 comp.llvm_target = try Target.llvmTargetFromTriple(comp.llvm_triple);
376 comp.link_libs_list = ArrayList(*LinkLib).init(comp.arena());
377 comp.zig_std_dir = try std.os.path.join(comp.arena(), zig_lib_dir, "std");
378
379 const opt_level = switch (build_mode) {
380 builtin.Mode.Debug => llvm.CodeGenLevelNone,
381 else => llvm.CodeGenLevelAggressive,
382 };
383
384 const reloc_mode = if (is_static) llvm.RelocStatic else llvm.RelocPIC;
385
386 // LLVM creates invalid binaries on Windows sometimes.
387 // See https://github.com/ziglang/zig/issues/508
388 // As a workaround we do not use target native features on Windows.
389 var target_specific_cpu_args: ?[*]u8 = null;
390 var target_specific_cpu_features: ?[*]u8 = null;
391 errdefer llvm.DisposeMessage(target_specific_cpu_args);
392 errdefer llvm.DisposeMessage(target_specific_cpu_features);
393 if (target == Target.Native and !target.isWindows()) {
394 target_specific_cpu_args = llvm.GetHostCPUName() orelse return error.OutOfMemory;
395 target_specific_cpu_features = llvm.GetNativeFeatures() orelse return error.OutOfMemory;
396 }
397
398 comp.target_machine = llvm.CreateTargetMachine(
399 comp.llvm_target,
400 comp.llvm_triple.ptr(),
401 target_specific_cpu_args orelse c"",
402 target_specific_cpu_features orelse c"",
403 opt_level,
404 reloc_mode,
405 llvm.CodeModelDefault,
406 ) orelse return error.OutOfMemory;
407 errdefer llvm.DisposeTargetMachine(comp.target_machine);
408
409 comp.target_data_ref = llvm.CreateTargetDataLayout(comp.target_machine) orelse return error.OutOfMemory;
410 errdefer llvm.DisposeTargetData(comp.target_data_ref);
411
412 comp.target_layout_str = llvm.CopyStringRepOfTargetData(comp.target_data_ref) orelse return error.OutOfMemory;
413 errdefer llvm.DisposeMessage(comp.target_layout_str);
414
415 comp.events = try event.Channel(Event).create(comp.loop, 0);
416 errdefer comp.events.destroy();
417
418 if (root_src_path) |root_src| {
419 const dirname = std.os.path.dirname(root_src) orelse ".";
420 const basename = std.os.path.basename(root_src);
421
422 comp.root_package = try Package.create(comp.arena(), dirname, basename);
423 comp.std_package = try Package.create(comp.arena(), comp.zig_std_dir, "index.zig");
424 try comp.root_package.add("std", comp.std_package);
425 } else {
426 comp.root_package = try Package.create(comp.arena(), ".", "");
427 }
428
318429 try comp.initTypes();
430
319431 return comp;
320432 }
321433
322434 fn initTypes(comp: *Compilation) !void {
323 comp.meta_type = try comp.a().create(Type.MetaType{
435 comp.meta_type = try comp.gpa().create(Type.MetaType{
324436 .base = Type{
325437 .base = Value{
326438 .id = Value.Id.Type,
......@@ -333,9 +445,9 @@ pub const Compilation = struct {
333445 });
334446 comp.meta_type.value = &comp.meta_type.base;
335447 comp.meta_type.base.base.typeof = &comp.meta_type.base;
336 errdefer comp.a().destroy(comp.meta_type);
448 errdefer comp.gpa().destroy(comp.meta_type);
337449
338 comp.void_type = try comp.a().create(Type.Void{
450 comp.void_type = try comp.gpa().create(Type.Void{
339451 .base = Type{
340452 .base = Value{
341453 .id = Value.Id.Type,
......@@ -345,9 +457,9 @@ pub const Compilation = struct {
345457 .id = builtin.TypeId.Void,
346458 },
347459 });
348 errdefer comp.a().destroy(comp.void_type);
460 errdefer comp.gpa().destroy(comp.void_type);
349461
350 comp.noreturn_type = try comp.a().create(Type.NoReturn{
462 comp.noreturn_type = try comp.gpa().create(Type.NoReturn{
351463 .base = Type{
352464 .base = Value{
353465 .id = Value.Id.Type,
......@@ -357,9 +469,9 @@ pub const Compilation = struct {
357469 .id = builtin.TypeId.NoReturn,
358470 },
359471 });
360 errdefer comp.a().destroy(comp.noreturn_type);
472 errdefer comp.gpa().destroy(comp.noreturn_type);
361473
362 comp.bool_type = try comp.a().create(Type.Bool{
474 comp.bool_type = try comp.gpa().create(Type.Bool{
363475 .base = Type{
364476 .base = Value{
365477 .id = Value.Id.Type,
......@@ -369,18 +481,18 @@ pub const Compilation = struct {
369481 .id = builtin.TypeId.Bool,
370482 },
371483 });
372 errdefer comp.a().destroy(comp.bool_type);
484 errdefer comp.gpa().destroy(comp.bool_type);
373485
374 comp.void_value = try comp.a().create(Value.Void{
486 comp.void_value = try comp.gpa().create(Value.Void{
375487 .base = Value{
376488 .id = Value.Id.Void,
377489 .typeof = &Type.Void.get(comp).base,
378490 .ref_count = std.atomic.Int(usize).init(1),
379491 },
380492 });
381 errdefer comp.a().destroy(comp.void_value);
493 errdefer comp.gpa().destroy(comp.void_value);
382494
383 comp.true_value = try comp.a().create(Value.Bool{
495 comp.true_value = try comp.gpa().create(Value.Bool{
384496 .base = Value{
385497 .id = Value.Id.Bool,
386498 .typeof = &Type.Bool.get(comp).base,
......@@ -388,9 +500,9 @@ pub const Compilation = struct {
388500 },
389501 .x = true,
390502 });
391 errdefer comp.a().destroy(comp.true_value);
503 errdefer comp.gpa().destroy(comp.true_value);
392504
393 comp.false_value = try comp.a().create(Value.Bool{
505 comp.false_value = try comp.gpa().create(Value.Bool{
394506 .base = Value{
395507 .id = Value.Id.Bool,
396508 .typeof = &Type.Bool.get(comp).base,
......@@ -398,19 +510,23 @@ pub const Compilation = struct {
398510 },
399511 .x = false,
400512 });
401 errdefer comp.a().destroy(comp.false_value);
513 errdefer comp.gpa().destroy(comp.false_value);
402514
403 comp.noreturn_value = try comp.a().create(Value.NoReturn{
515 comp.noreturn_value = try comp.gpa().create(Value.NoReturn{
404516 .base = Value{
405517 .id = Value.Id.NoReturn,
406518 .typeof = &Type.NoReturn.get(comp).base,
407519 .ref_count = std.atomic.Int(usize).init(1),
408520 },
409521 });
410 errdefer comp.a().destroy(comp.noreturn_value);
522 errdefer comp.gpa().destroy(comp.noreturn_value);
411523 }
412524
413525 pub fn destroy(self: *Compilation) void {
526 if (self.tmp_dir.getOrNull()) |tmp_dir_result| if (tmp_dir_result.*) |tmp_dir| {
527 os.deleteTree(self.arena(), tmp_dir) catch {};
528 } else |_| {};
529
414530 self.noreturn_value.base.deref(self);
415531 self.void_value.base.deref(self);
416532 self.false_value.base.deref(self);
......@@ -420,14 +536,18 @@ pub const Compilation = struct {
420536 self.meta_type.base.base.deref(self);
421537
422538 self.events.destroy();
423 self.name.deinit();
424539
425 self.a().destroy(self);
540 llvm.DisposeMessage(self.target_layout_str);
541 llvm.DisposeTargetData(self.target_data_ref);
542 llvm.DisposeTargetMachine(self.target_machine);
543
544 self.arena_allocator.deinit();
545 self.gpa().destroy(self);
426546 }
427547
428548 pub fn build(self: *Compilation) !void {
429549 if (self.llvm_argv.len != 0) {
430 var c_compatible_args = try std.cstr.NullTerminated2DArray.fromSlices(self.a(), [][]const []const u8{
550 var c_compatible_args = try std.cstr.NullTerminated2DArray.fromSlices(self.arena(), [][]const []const u8{
431551 [][]const u8{"zig (LLVM option parsing)"},
432552 self.llvm_argv,
433553 });
......@@ -436,7 +556,7 @@ pub const Compilation = struct {
436556 c.ZigLLVMParseCommandLineOptions(self.llvm_argv.len + 1, c_compatible_args.ptr);
437557 }
438558
439 _ = try async<self.a()> self.buildAsync();
559 _ = try async<self.gpa()> self.buildAsync();
440560 }
441561
442562 async fn buildAsync(self: *Compilation) void {
......@@ -464,7 +584,7 @@ pub const Compilation = struct {
464584 }
465585 } else |err| {
466586 // if there's an error then the compile errors have dangling references
467 self.a().free(compile_errors);
587 self.gpa().free(compile_errors);
468588
469589 await (async self.events.put(Event{ .Error = err }) catch unreachable);
470590 }
......@@ -477,26 +597,26 @@ pub const Compilation = struct {
477597 async fn addRootSrc(self: *Compilation) !void {
478598 const root_src_path = self.root_src_path orelse @panic("TODO handle null root src path");
479599 // TODO async/await os.path.real
480 const root_src_real_path = os.path.real(self.a(), root_src_path) catch |err| {
600 const root_src_real_path = os.path.real(self.gpa(), root_src_path) catch |err| {
481601 try printError("unable to get real path '{}': {}", root_src_path, err);
482602 return err;
483603 };
484 errdefer self.a().free(root_src_real_path);
604 errdefer self.gpa().free(root_src_real_path);
485605
486606 // TODO async/await readFileAlloc()
487 const source_code = io.readFileAlloc(self.a(), root_src_real_path) catch |err| {
607 const source_code = io.readFileAlloc(self.gpa(), root_src_real_path) catch |err| {
488608 try printError("unable to open '{}': {}", root_src_real_path, err);
489609 return err;
490610 };
491 errdefer self.a().free(source_code);
611 errdefer self.gpa().free(source_code);
492612
493 const parsed_file = try self.a().create(ParsedFile{
613 const parsed_file = try self.gpa().create(ParsedFile{
494614 .tree = undefined,
495615 .realpath = root_src_real_path,
496616 });
497 errdefer self.a().destroy(parsed_file);
617 errdefer self.gpa().destroy(parsed_file);
498618
499 parsed_file.tree = try std.zig.parse(self.a(), source_code);
619 parsed_file.tree = try std.zig.parse(self.gpa(), source_code);
500620 errdefer parsed_file.tree.deinit();
501621
502622 const tree = &parsed_file.tree;
......@@ -525,7 +645,7 @@ pub const Compilation = struct {
525645 continue;
526646 };
527647
528 const fn_decl = try self.a().create(Decl.Fn{
648 const fn_decl = try self.gpa().create(Decl.Fn{
529649 .base = Decl{
530650 .id = Decl.Id.Fn,
531651 .name = name,
......@@ -538,7 +658,7 @@ pub const Compilation = struct {
538658 .value = Decl.Fn.Val{ .Unresolved = {} },
539659 .fn_proto = fn_proto,
540660 });
541 errdefer self.a().destroy(fn_decl);
661 errdefer self.gpa().destroy(fn_decl);
542662
543663 try decl_group.call(addTopLevelDecl, self, &fn_decl.base);
544664 },
......@@ -547,15 +667,15 @@ pub const Compilation = struct {
547667 }
548668 }
549669 try await (async decl_group.wait() catch unreachable);
550 try await (async self.build_group.wait() catch unreachable);
670 try await (async self.prelink_group.wait() catch unreachable);
551671 }
552672
553673 async fn addTopLevelDecl(self: *Compilation, decl: *Decl) !void {
554674 const is_export = decl.isExported(&decl.parsed_file.tree);
555675
556676 if (is_export) {
557 try self.build_group.call(verifyUniqueSymbol, self, decl);
558 try self.build_group.call(resolveDecl, self, decl);
677 try self.prelink_group.call(verifyUniqueSymbol, self, decl);
678 try self.prelink_group.call(resolveDecl, self, decl);
559679 }
560680 }
561681
......@@ -563,7 +683,7 @@ pub const Compilation = struct {
563683 const text = try std.fmt.allocPrint(self.loop.allocator, fmt, args);
564684 errdefer self.loop.allocator.free(text);
565685
566 try self.build_group.call(addCompileErrorAsync, self, parsed_file, span, text);
686 try self.prelink_group.call(addCompileErrorAsync, self, parsed_file, span, text);
567687 }
568688
569689 async fn addCompileErrorAsync(
......@@ -625,11 +745,11 @@ pub const Compilation = struct {
625745 }
626746 }
627747
628 const link_lib = try self.a().create(LinkLib{
748 const link_lib = try self.gpa().create(LinkLib{
629749 .name = name,
630750 .path = null,
631751 .provided_explicitly = provided_explicitly,
632 .symbols = ArrayList([]u8).init(self.a()),
752 .symbols = ArrayList([]u8).init(self.gpa()),
633753 });
634754 try self.link_libs_list.append(link_lib);
635755 if (is_libc) {
......@@ -638,9 +758,71 @@ pub const Compilation = struct {
638758 return link_lib;
639759 }
640760
641 fn a(self: Compilation) *mem.Allocator {
761 /// General Purpose Allocator. Must free when done.
762 fn gpa(self: Compilation) *mem.Allocator {
642763 return self.loop.allocator;
643764 }
765
766 /// Arena Allocator. Automatically freed when the Compilation is destroyed.
767 fn arena(self: *Compilation) *mem.Allocator {
768 return &self.arena_allocator.allocator;
769 }
770
771 /// If the temporary directory for this compilation has not been created, it creates it.
772 /// Then it creates a random file name in that dir and returns it.
773 pub async fn createRandomOutputPath(self: *Compilation, suffix: []const u8) !Buffer {
774 const tmp_dir = try await (async self.getTmpDir() catch unreachable);
775 const file_prefix = await (async self.getRandomFileName() catch unreachable);
776
777 const file_name = try std.fmt.allocPrint(self.gpa(), "{}{}", file_prefix[0..], suffix);
778 defer self.gpa().free(file_name);
779
780 const full_path = try os.path.join(self.gpa(), tmp_dir, file_name[0..]);
781 errdefer self.gpa().free(full_path);
782
783 return Buffer.fromOwnedSlice(self.gpa(), full_path);
784 }
785
786 /// If the temporary directory for this Compilation has not been created, creates it.
787 /// Then returns it. The directory is unique to this Compilation and cleaned up when
788 /// the Compilation deinitializes.
789 async fn getTmpDir(self: *Compilation) ![]const u8 {
790 if (await (async self.tmp_dir.start() catch unreachable)) |ptr| return ptr.*;
791 self.tmp_dir.data = await (async self.getTmpDirImpl() catch unreachable);
792 self.tmp_dir.resolve();
793 return self.tmp_dir.data;
794 }
795
796 async fn getTmpDirImpl(self: *Compilation) ![]u8 {
797 const comp_dir_name = await (async self.getRandomFileName() catch unreachable);
798 const zig_dir_path = try getZigDir(self.gpa());
799 defer self.gpa().free(zig_dir_path);
800
801 const tmp_dir = try os.path.join(self.arena(), zig_dir_path, comp_dir_name[0..]);
802 try os.makePath(self.gpa(), tmp_dir);
803 return tmp_dir;
804 }
805
806 async fn getRandomFileName(self: *Compilation) [12]u8 {
807 // here we replace the standard +/ with -_ so that it can be used in a file name
808 const b64_fs_encoder = std.base64.Base64Encoder.init(
809 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",
810 std.base64.standard_pad_char,
811 );
812
813 var rand_bytes: [9]u8 = undefined;
814
815 {
816 const held = await (async self.event_loop_local.prng.acquire() catch unreachable);
817 defer held.release();
818
819 held.value.random.bytes(rand_bytes[0..]);
820 }
821
822 var result: [12]u8 = undefined;
823 b64_fs_encoder.encode(result[0..], rand_bytes);
824 return result;
825 }
644826};
645827
646828fn printError(comptime format: []const u8, args: ...) !void {
......@@ -662,13 +844,11 @@ fn parseVisibToken(tree: *ast.Tree, optional_token_index: ?ast.TokenIndex) Visib
662844
663845/// This declaration has been blessed as going into the final code generation.
664846pub async fn resolveDecl(comp: *Compilation, decl: *Decl) !void {
665 if (@atomicRmw(u8, &decl.resolution_in_progress, AtomicRmwOp.Xchg, 1, AtomicOrder.SeqCst) == 0) {
666 decl.resolution.data = await (async generateDecl(comp, decl) catch unreachable);
667 decl.resolution.resolve();
668 return decl.resolution.data;
669 } else {
670 return (await (async decl.resolution.get() catch unreachable)).*;
671 }
847 if (await (async decl.resolution.start() catch unreachable)) |ptr| return ptr.*;
848
849 decl.resolution.data = await (async generateDecl(comp, decl) catch unreachable);
850 decl.resolution.resolve();
851 return decl.resolution.data;
672852}
673853
674854/// The function that actually does the generation.
......@@ -698,7 +878,7 @@ async fn generateDeclFn(comp: *Compilation, fn_decl: *Decl.Fn) !void {
698878 const fn_type = try Type.Fn.create(comp, return_type, params, is_var_args);
699879 defer fn_type.base.base.deref(comp);
700880
701 var symbol_name = try std.Buffer.init(comp.a(), fn_decl.base.name);
881 var symbol_name = try std.Buffer.init(comp.gpa(), fn_decl.base.name);
702882 errdefer symbol_name.deinit();
703883
704884 const fn_val = try Value.Fn.create(comp, fn_type, fndef_scope, symbol_name);
......@@ -719,7 +899,7 @@ async fn generateDeclFn(comp: *Compilation, fn_decl: *Decl.Fn) !void {
719899 error.SemanticAnalysisFailed => return {},
720900 else => return err,
721901 };
722 defer unanalyzed_code.destroy(comp.a());
902 defer unanalyzed_code.destroy(comp.gpa());
723903
724904 if (comp.verbose_ir) {
725905 std.debug.warn("unanalyzed:\n");
......@@ -738,7 +918,7 @@ async fn generateDeclFn(comp: *Compilation, fn_decl: *Decl.Fn) !void {
738918 error.SemanticAnalysisFailed => return {},
739919 else => return err,
740920 };
741 errdefer analyzed_code.destroy(comp.a());
921 errdefer analyzed_code.destroy(comp.gpa());
742922
743923 if (comp.verbose_ir) {
744924 std.debug.warn("analyzed:\n");
......@@ -747,5 +927,30 @@ async fn generateDeclFn(comp: *Compilation, fn_decl: *Decl.Fn) !void {
747927
748928 // Kick off rendering to LLVM module, but it doesn't block the fn decl
749929 // analysis from being complete.
750 try comp.build_group.call(codegen.renderToLlvm, comp, fn_val, analyzed_code);
930 try comp.prelink_group.call(codegen.renderToLlvm, comp, fn_val, analyzed_code);
931 try comp.prelink_group.call(addFnToLinkSet, comp, fn_val);
932}
933
934async fn addFnToLinkSet(comp: *Compilation, fn_val: *Value.Fn) void {
935 fn_val.base.ref();
936 defer fn_val.base.deref(comp);
937
938 fn_val.link_set_node.data = fn_val;
939
940 const held = await (async comp.fn_link_set.acquire() catch unreachable);
941 defer held.release();
942
943 held.value.append(fn_val.link_set_node);
944}
945
946fn getZigDir(allocator: *mem.Allocator) ![]u8 {
947 const home_dir = try getHomeDir(allocator);
948 defer allocator.free(home_dir);
949
950 return os.path.join(allocator, home_dir, ".zig");
951}
952
953/// TODO move to zig std lib, and make it work for other OSes
954fn getHomeDir(allocator: *mem.Allocator) ![]u8 {
955 return os.getEnvVarOwned(allocator, "HOME");
751956}
src-self-hosted/ir.zig+5-5
......@@ -453,7 +453,7 @@ pub const Code = struct {
453453 arena: std.heap.ArenaAllocator,
454454 return_type: ?*Type,
455455
456 /// allocator is comp.a()
456 /// allocator is comp.gpa()
457457 pub fn destroy(self: *Code, allocator: *Allocator) void {
458458 self.arena.deinit();
459459 allocator.destroy(self);
......@@ -483,13 +483,13 @@ pub const Builder = struct {
483483 pub const Error = Analyze.Error;
484484
485485 pub fn init(comp: *Compilation, parsed_file: *ParsedFile) !Builder {
486 const code = try comp.a().create(Code{
486 const code = try comp.gpa().create(Code{
487487 .basic_block_list = undefined,
488 .arena = std.heap.ArenaAllocator.init(comp.a()),
488 .arena = std.heap.ArenaAllocator.init(comp.gpa()),
489489 .return_type = null,
490490 });
491491 code.basic_block_list = std.ArrayList(*BasicBlock).init(&code.arena.allocator);
492 errdefer code.destroy(comp.a());
492 errdefer code.destroy(comp.gpa());
493493
494494 return Builder{
495495 .comp = comp,
......@@ -502,7 +502,7 @@ pub const Builder = struct {
502502 }
503503
504504 pub fn abort(self: *Builder) void {
505 self.code.destroy(self.comp.a());
505 self.code.destroy(self.comp.gpa());
506506 }
507507
508508 /// Call code.destroy() when done
src-self-hosted/llvm.zig+73-2
......@@ -2,6 +2,12 @@ const builtin = @import("builtin");
22const c = @import("c.zig");
33const assert = @import("std").debug.assert;
44
5// we wrap the c module for 3 reasons:
6// 1. to avoid accidentally calling the non-thread-safe functions
7// 2. patch up some of the types to remove nullability
8// 3. some functions have been augmented by zig_llvm.cpp to be more powerful,
9// such as ZigLLVMTargetMachineEmitToFile
10
511pub const AttributeIndex = c_uint;
612pub const Bool = c_int;
713
......@@ -12,25 +18,51 @@ pub const ValueRef = removeNullability(c.LLVMValueRef);
1218pub const TypeRef = removeNullability(c.LLVMTypeRef);
1319pub const BasicBlockRef = removeNullability(c.LLVMBasicBlockRef);
1420pub const AttributeRef = removeNullability(c.LLVMAttributeRef);
21pub const TargetRef = removeNullability(c.LLVMTargetRef);
22pub const TargetMachineRef = removeNullability(c.LLVMTargetMachineRef);
23pub const TargetDataRef = removeNullability(c.LLVMTargetDataRef);
24pub const DIBuilder = c.ZigLLVMDIBuilder;
1525
1626pub const AddAttributeAtIndex = c.LLVMAddAttributeAtIndex;
1727pub const AddFunction = c.LLVMAddFunction;
28pub const AddModuleCodeViewFlag = c.ZigLLVMAddModuleCodeViewFlag;
29pub const AddModuleDebugInfoFlag = c.ZigLLVMAddModuleDebugInfoFlag;
1830pub const ClearCurrentDebugLocation = c.ZigLLVMClearCurrentDebugLocation;
31pub const ConstAllOnes = c.LLVMConstAllOnes;
1932pub const ConstInt = c.LLVMConstInt;
33pub const ConstNull = c.LLVMConstNull;
2034pub const ConstStringInContext = c.LLVMConstStringInContext;
2135pub const ConstStructInContext = c.LLVMConstStructInContext;
36pub const CopyStringRepOfTargetData = c.LLVMCopyStringRepOfTargetData;
2237pub const CreateBuilderInContext = c.LLVMCreateBuilderInContext;
38pub const CreateCompileUnit = c.ZigLLVMCreateCompileUnit;
39pub const CreateDIBuilder = c.ZigLLVMCreateDIBuilder;
2340pub const CreateEnumAttribute = c.LLVMCreateEnumAttribute;
41pub const CreateFile = c.ZigLLVMCreateFile;
2442pub const CreateStringAttribute = c.LLVMCreateStringAttribute;
43pub const CreateTargetDataLayout = c.LLVMCreateTargetDataLayout;
44pub const CreateTargetMachine = c.LLVMCreateTargetMachine;
45pub const DIBuilderFinalize = c.ZigLLVMDIBuilderFinalize;
2546pub const DisposeBuilder = c.LLVMDisposeBuilder;
47pub const DisposeDIBuilder = c.ZigLLVMDisposeDIBuilder;
48pub const DisposeMessage = c.LLVMDisposeMessage;
2649pub const DisposeModule = c.LLVMDisposeModule;
50pub const DisposeTargetData = c.LLVMDisposeTargetData;
51pub const DisposeTargetMachine = c.LLVMDisposeTargetMachine;
2752pub const DoubleTypeInContext = c.LLVMDoubleTypeInContext;
2853pub const DumpModule = c.LLVMDumpModule;
2954pub const FP128TypeInContext = c.LLVMFP128TypeInContext;
3055pub const FloatTypeInContext = c.LLVMFloatTypeInContext;
3156pub const GetEnumAttributeKindForName = c.LLVMGetEnumAttributeKindForName;
57pub const GetHostCPUName = c.ZigLLVMGetHostCPUName;
3258pub const GetMDKindIDInContext = c.LLVMGetMDKindIDInContext;
59pub const GetNativeFeatures = c.ZigLLVMGetNativeFeatures;
3360pub const HalfTypeInContext = c.LLVMHalfTypeInContext;
61pub const InitializeAllAsmParsers = c.LLVMInitializeAllAsmParsers;
62pub const InitializeAllAsmPrinters = c.LLVMInitializeAllAsmPrinters;
63pub const InitializeAllTargetInfos = c.LLVMInitializeAllTargetInfos;
64pub const InitializeAllTargetMCs = c.LLVMInitializeAllTargetMCs;
65pub const InitializeAllTargets = c.LLVMInitializeAllTargets;
3466pub const InsertBasicBlockInContext = c.LLVMInsertBasicBlockInContext;
3567pub const Int128TypeInContext = c.LLVMInt128TypeInContext;
3668pub const Int16TypeInContext = c.LLVMInt16TypeInContext;
......@@ -47,13 +79,16 @@ pub const MDStringInContext = c.LLVMMDStringInContext;
4779pub const MetadataTypeInContext = c.LLVMMetadataTypeInContext;
4880pub const ModuleCreateWithNameInContext = c.LLVMModuleCreateWithNameInContext;
4981pub const PPCFP128TypeInContext = c.LLVMPPCFP128TypeInContext;
82pub const SetDataLayout = c.LLVMSetDataLayout;
83pub const SetTarget = c.LLVMSetTarget;
5084pub const StructTypeInContext = c.LLVMStructTypeInContext;
5185pub const TokenTypeInContext = c.LLVMTokenTypeInContext;
5286pub const VoidTypeInContext = c.LLVMVoidTypeInContext;
5387pub const X86FP80TypeInContext = c.LLVMX86FP80TypeInContext;
5488pub const X86MMXTypeInContext = c.LLVMX86MMXTypeInContext;
55pub const ConstAllOnes = c.LLVMConstAllOnes;
56pub const ConstNull = c.LLVMConstNull;
89
90pub const GetTargetFromTriple = LLVMGetTargetFromTriple;
91extern fn LLVMGetTargetFromTriple(Triple: [*]const u8, T: *TargetRef, ErrorMessage: ?*[*]u8) Bool;
5792
5893pub const VerifyModule = LLVMVerifyModule;
5994extern fn LLVMVerifyModule(M: ModuleRef, Action: VerifierFailureAction, OutMessage: *?[*]u8) Bool;
......@@ -83,6 +118,31 @@ pub const PrintMessageAction = VerifierFailureAction.LLVMPrintMessageAction;
83118pub const ReturnStatusAction = VerifierFailureAction.LLVMReturnStatusAction;
84119pub const VerifierFailureAction = c.LLVMVerifierFailureAction;
85120
121pub const CodeGenLevelNone = c.LLVMCodeGenOptLevel.LLVMCodeGenLevelNone;
122pub const CodeGenLevelLess = c.LLVMCodeGenOptLevel.LLVMCodeGenLevelLess;
123pub const CodeGenLevelDefault = c.LLVMCodeGenOptLevel.LLVMCodeGenLevelDefault;
124pub const CodeGenLevelAggressive = c.LLVMCodeGenOptLevel.LLVMCodeGenLevelAggressive;
125pub const CodeGenOptLevel = c.LLVMCodeGenOptLevel;
126
127pub const RelocDefault = c.LLVMRelocMode.LLVMRelocDefault;
128pub const RelocStatic = c.LLVMRelocMode.LLVMRelocStatic;
129pub const RelocPIC = c.LLVMRelocMode.LLVMRelocPIC;
130pub const RelocDynamicNoPic = c.LLVMRelocMode.LLVMRelocDynamicNoPic;
131pub const RelocMode = c.LLVMRelocMode;
132
133pub const CodeModelDefault = c.LLVMCodeModel.LLVMCodeModelDefault;
134pub const CodeModelJITDefault = c.LLVMCodeModel.LLVMCodeModelJITDefault;
135pub const CodeModelSmall = c.LLVMCodeModel.LLVMCodeModelSmall;
136pub const CodeModelKernel = c.LLVMCodeModel.LLVMCodeModelKernel;
137pub const CodeModelMedium = c.LLVMCodeModel.LLVMCodeModelMedium;
138pub const CodeModelLarge = c.LLVMCodeModel.LLVMCodeModelLarge;
139pub const CodeModel = c.LLVMCodeModel;
140
141pub const EmitAssembly = EmitOutputType.ZigLLVM_EmitAssembly;
142pub const EmitBinary = EmitOutputType.ZigLLVM_EmitBinary;
143pub const EmitLLVMIr = EmitOutputType.ZigLLVM_EmitLLVMIr;
144pub const EmitOutputType = c.ZigLLVM_EmitOutputType;
145
86146fn removeNullability(comptime T: type) type {
87147 comptime assert(@typeId(T) == builtin.TypeId.Optional);
88148 return T.Child;
......@@ -90,3 +150,14 @@ fn removeNullability(comptime T: type) type {
90150
91151pub const BuildRet = LLVMBuildRet;
92152extern fn LLVMBuildRet(arg0: BuilderRef, V: ?ValueRef) ValueRef;
153
154pub const TargetMachineEmitToFile = ZigLLVMTargetMachineEmitToFile;
155extern fn ZigLLVMTargetMachineEmitToFile(
156 targ_machine_ref: TargetMachineRef,
157 module_ref: ModuleRef,
158 filename: [*]const u8,
159 output_type: EmitOutputType,
160 error_message: *[*]u8,
161 is_debug: bool,
162 is_small: bool,
163) bool;
src-self-hosted/main.zig+5-3
......@@ -363,6 +363,8 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Co
363363 }
364364 };
365365
366 const is_static = flags.present("static");
367
366368 const assembly_files = flags.many("assembly");
367369 const link_objects = flags.many("object");
368370 if (root_source_file == null and link_objects.len == 0 and assembly_files.len == 0) {
......@@ -389,7 +391,7 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Co
389391 try loop.initMultiThreaded(allocator);
390392 defer loop.deinit();
391393
392 var event_loop_local = EventLoopLocal.init(&loop);
394 var event_loop_local = try EventLoopLocal.init(&loop);
393395 defer event_loop_local.deinit();
394396
395397 var comp = try Compilation.create(
......@@ -399,6 +401,7 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Co
399401 Target.Native,
400402 out_type,
401403 build_mode,
404 is_static,
402405 zig_lib_dir,
403406 full_cache_dir,
404407 );
......@@ -426,7 +429,6 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Co
426429 comp.clang_argv = clang_argv_buf.toSliceConst();
427430
428431 comp.strip = flags.present("strip");
429 comp.is_static = flags.present("static");
430432
431433 if (flags.single("libc-lib-dir")) |libc_lib_dir| {
432434 comp.libc_lib_dir = libc_lib_dir;
......@@ -481,9 +483,9 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Co
481483 }
482484
483485 comp.emit_file_type = emit_type;
484 comp.link_objects = link_objects;
485486 comp.assembly_files = assembly_files;
486487 comp.link_out_file = flags.single("out-file");
488 comp.link_objects = link_objects;
487489
488490 try comp.build();
489491 const process_build_events_handle = try async<loop.allocator> processBuildEvents(comp, color);
src-self-hosted/package.zig created+29
......@@ -0,0 +1,29 @@
1const std = @import("std");
2const mem = std.mem;
3const assert = std.debug.assert;
4const Buffer = std.Buffer;
5
6pub const Package = struct {
7 root_src_dir: Buffer,
8 root_src_path: Buffer,
9
10 /// relative to root_src_dir
11 table: Table,
12
13 pub const Table = std.HashMap([]const u8, *Package, mem.hash_slice_u8, mem.eql_slice_u8);
14
15 /// makes internal copies of root_src_dir and root_src_path
16 /// allocator should be an arena allocator because Package never frees anything
17 pub fn create(allocator: *mem.Allocator, root_src_dir: []const u8, root_src_path: []const u8) !*Package {
18 return allocator.create(Package{
19 .root_src_dir = try Buffer.init(allocator, root_src_dir),
20 .root_src_path = try Buffer.init(allocator, root_src_path),
21 .table = Table.init(allocator),
22 });
23 }
24
25 pub fn add(self: *Package, name: []const u8, package: *Package) !void {
26 const entry = try self.table.put(try mem.dupe(self.table.allocator, u8, name), package);
27 assert(entry == null);
28 }
29};
src-self-hosted/scope.zig+16-16
......@@ -64,7 +64,7 @@ pub const Scope = struct {
6464
6565 /// Creates a Decls scope with 1 reference
6666 pub fn create(comp: *Compilation, parent: ?*Scope) !*Decls {
67 const self = try comp.a().create(Decls{
67 const self = try comp.gpa().create(Decls{
6868 .base = Scope{
6969 .id = Id.Decls,
7070 .parent = parent,
......@@ -72,9 +72,9 @@ pub const Scope = struct {
7272 },
7373 .table = undefined,
7474 });
75 errdefer comp.a().destroy(self);
75 errdefer comp.gpa().destroy(self);
7676
77 self.table = Decl.Table.init(comp.a());
77 self.table = Decl.Table.init(comp.gpa());
7878 errdefer self.table.deinit();
7979
8080 if (parent) |p| p.ref();
......@@ -126,7 +126,7 @@ pub const Scope = struct {
126126
127127 /// Creates a Block scope with 1 reference
128128 pub fn create(comp: *Compilation, parent: ?*Scope) !*Block {
129 const self = try comp.a().create(Block{
129 const self = try comp.gpa().create(Block{
130130 .base = Scope{
131131 .id = Id.Block,
132132 .parent = parent,
......@@ -138,14 +138,14 @@ pub const Scope = struct {
138138 .is_comptime = undefined,
139139 .safety = Safety.Auto,
140140 });
141 errdefer comp.a().destroy(self);
141 errdefer comp.gpa().destroy(self);
142142
143143 if (parent) |p| p.ref();
144144 return self;
145145 }
146146
147147 pub fn destroy(self: *Block, comp: *Compilation) void {
148 comp.a().destroy(self);
148 comp.gpa().destroy(self);
149149 }
150150 };
151151
......@@ -158,7 +158,7 @@ pub const Scope = struct {
158158 /// Creates a FnDef scope with 1 reference
159159 /// Must set the fn_val later
160160 pub fn create(comp: *Compilation, parent: ?*Scope) !*FnDef {
161 const self = try comp.a().create(FnDef{
161 const self = try comp.gpa().create(FnDef{
162162 .base = Scope{
163163 .id = Id.FnDef,
164164 .parent = parent,
......@@ -173,7 +173,7 @@ pub const Scope = struct {
173173 }
174174
175175 pub fn destroy(self: *FnDef, comp: *Compilation) void {
176 comp.a().destroy(self);
176 comp.gpa().destroy(self);
177177 }
178178 };
179179
......@@ -182,7 +182,7 @@ pub const Scope = struct {
182182
183183 /// Creates a CompTime scope with 1 reference
184184 pub fn create(comp: *Compilation, parent: ?*Scope) !*CompTime {
185 const self = try comp.a().create(CompTime{
185 const self = try comp.gpa().create(CompTime{
186186 .base = Scope{
187187 .id = Id.CompTime,
188188 .parent = parent,
......@@ -195,7 +195,7 @@ pub const Scope = struct {
195195 }
196196
197197 pub fn destroy(self: *CompTime, comp: *Compilation) void {
198 comp.a().destroy(self);
198 comp.gpa().destroy(self);
199199 }
200200 };
201201
......@@ -216,7 +216,7 @@ pub const Scope = struct {
216216 kind: Kind,
217217 defer_expr_scope: *DeferExpr,
218218 ) !*Defer {
219 const self = try comp.a().create(Defer{
219 const self = try comp.gpa().create(Defer{
220220 .base = Scope{
221221 .id = Id.Defer,
222222 .parent = parent,
......@@ -225,7 +225,7 @@ pub const Scope = struct {
225225 .defer_expr_scope = defer_expr_scope,
226226 .kind = kind,
227227 });
228 errdefer comp.a().destroy(self);
228 errdefer comp.gpa().destroy(self);
229229
230230 defer_expr_scope.base.ref();
231231
......@@ -235,7 +235,7 @@ pub const Scope = struct {
235235
236236 pub fn destroy(self: *Defer, comp: *Compilation) void {
237237 self.defer_expr_scope.base.deref(comp);
238 comp.a().destroy(self);
238 comp.gpa().destroy(self);
239239 }
240240 };
241241
......@@ -245,7 +245,7 @@ pub const Scope = struct {
245245
246246 /// Creates a DeferExpr scope with 1 reference
247247 pub fn create(comp: *Compilation, parent: ?*Scope, expr_node: *ast.Node) !*DeferExpr {
248 const self = try comp.a().create(DeferExpr{
248 const self = try comp.gpa().create(DeferExpr{
249249 .base = Scope{
250250 .id = Id.DeferExpr,
251251 .parent = parent,
......@@ -253,14 +253,14 @@ pub const Scope = struct {
253253 },
254254 .expr_node = expr_node,
255255 });
256 errdefer comp.a().destroy(self);
256 errdefer comp.gpa().destroy(self);
257257
258258 if (parent) |p| p.ref();
259259 return self;
260260 }
261261
262262 pub fn destroy(self: *DeferExpr, comp: *Compilation) void {
263 comp.a().destroy(self);
263 comp.gpa().destroy(self);
264264 }
265265 };
266266};
src-self-hosted/target.zig+87-29
......@@ -1,60 +1,118 @@
1const std = @import("std");
12const builtin = @import("builtin");
2const c = @import("c.zig");
3
4pub const CrossTarget = struct {
5 arch: builtin.Arch,
6 os: builtin.Os,
7 environ: builtin.Environ,
8};
3const llvm = @import("llvm.zig");
94
105pub const Target = union(enum) {
116 Native,
12 Cross: CrossTarget,
7 Cross: Cross,
138
14 pub fn oFileExt(self: *const Target) []const u8 {
15 const environ = switch (self.*) {
16 Target.Native => builtin.environ,
17 Target.Cross => |t| t.environ,
18 };
19 return switch (environ) {
20 builtin.Environ.msvc => ".obj",
9 pub const Cross = struct {
10 arch: builtin.Arch,
11 os: builtin.Os,
12 environ: builtin.Environ,
13 object_format: builtin.ObjectFormat,
14 };
15
16 pub fn oFileExt(self: Target) []const u8 {
17 return switch (self.getObjectFormat()) {
18 builtin.ObjectFormat.coff => ".obj",
2119 else => ".o",
2220 };
2321 }
2422
25 pub fn exeFileExt(self: *const Target) []const u8 {
23 pub fn exeFileExt(self: Target) []const u8 {
2624 return switch (self.getOs()) {
2725 builtin.Os.windows => ".exe",
2826 else => "",
2927 };
3028 }
3129
32 pub fn getOs(self: *const Target) builtin.Os {
33 return switch (self.*) {
30 pub fn getOs(self: Target) builtin.Os {
31 return switch (self) {
3432 Target.Native => builtin.os,
35 Target.Cross => |t| t.os,
33 @TagType(Target).Cross => |t| t.os,
34 };
35 }
36
37 pub fn getArch(self: Target) builtin.Arch {
38 return switch (self) {
39 Target.Native => builtin.arch,
40 @TagType(Target).Cross => |t| t.arch,
41 };
42 }
43
44 pub fn getEnviron(self: Target) builtin.Environ {
45 return switch (self) {
46 Target.Native => builtin.environ,
47 @TagType(Target).Cross => |t| t.environ,
48 };
49 }
50
51 pub fn getObjectFormat(self: Target) builtin.ObjectFormat {
52 return switch (self) {
53 Target.Native => builtin.object_format,
54 @TagType(Target).Cross => |t| t.object_format,
3655 };
3756 }
3857
39 pub fn isDarwin(self: *const Target) bool {
58 pub fn isWasm(self: Target) bool {
59 return switch (self.getArch()) {
60 builtin.Arch.wasm32, builtin.Arch.wasm64 => true,
61 else => false,
62 };
63 }
64
65 pub fn isDarwin(self: Target) bool {
4066 return switch (self.getOs()) {
4167 builtin.Os.ios, builtin.Os.macosx => true,
4268 else => false,
4369 };
4470 }
4571
46 pub fn isWindows(self: *const Target) bool {
72 pub fn isWindows(self: Target) bool {
4773 return switch (self.getOs()) {
4874 builtin.Os.windows => true,
4975 else => false,
5076 };
5177 }
52};
5378
54pub fn initializeAll() void {
55 c.LLVMInitializeAllTargets();
56 c.LLVMInitializeAllTargetInfos();
57 c.LLVMInitializeAllTargetMCs();
58 c.LLVMInitializeAllAsmPrinters();
59 c.LLVMInitializeAllAsmParsers();
60}
79 pub fn initializeAll() void {
80 llvm.InitializeAllTargets();
81 llvm.InitializeAllTargetInfos();
82 llvm.InitializeAllTargetMCs();
83 llvm.InitializeAllAsmPrinters();
84 llvm.InitializeAllAsmParsers();
85 }
86
87 pub fn getTriple(self: Target, allocator: *std.mem.Allocator) !std.Buffer {
88 var result = try std.Buffer.initSize(allocator, 0);
89 errdefer result.deinit();
90
91 // LLVM WebAssembly output support requires the target to be activated at
92 // build type with -DCMAKE_LLVM_EXPIERMENTAL_TARGETS_TO_BUILD=WebAssembly.
93 //
94 // LLVM determines the output format based on the environment suffix,
95 // defaulting to an object based on the architecture. The default format in
96 // LLVM 6 sets the wasm arch output incorrectly to ELF. We need to
97 // explicitly set this ourself in order for it to work.
98 //
99 // This is fixed in LLVM 7 and you will be able to get wasm output by
100 // using the target triple `wasm32-unknown-unknown-unknown`.
101 const env_name = if (self.isWasm()) "wasm" else @tagName(self.getEnviron());
102
103 var out = &std.io.BufferOutStream.init(&result).stream;
104 try out.print("{}-unknown-{}-{}", @tagName(self.getArch()), @tagName(self.getOs()), env_name);
105
106 return result;
107 }
108
109 pub fn llvmTargetFromTriple(triple: std.Buffer) !llvm.TargetRef {
110 var result: llvm.TargetRef = undefined;
111 var err_msg: [*]u8 = undefined;
112 if (llvm.GetTargetFromTriple(triple.ptr(), &result, &err_msg) != 0) {
113 std.debug.warn("triple: {s} error: {s}\n", triple.ptr(), err_msg);
114 return error.UnsupportedTarget;
115 }
116 return result;
117 }
118};
src-self-hosted/test.zig+2-1
......@@ -46,7 +46,7 @@ pub const TestContext = struct {
4646 try self.loop.initMultiThreaded(allocator);
4747 errdefer self.loop.deinit();
4848
49 self.event_loop_local = EventLoopLocal.init(&self.loop);
49 self.event_loop_local = try EventLoopLocal.init(&self.loop);
5050 errdefer self.event_loop_local.deinit();
5151
5252 self.group = std.event.Group(error!void).init(&self.loop);
......@@ -107,6 +107,7 @@ pub const TestContext = struct {
107107 Target.Native,
108108 Compilation.Kind.Obj,
109109 builtin.Mode.Debug,
110 true, // is_static
110111 self.zig_lib_dir,
111112 self.zig_cache_dir,
112113 );
src-self-hosted/type.zig+29-29
......@@ -160,7 +160,7 @@ pub const Type = struct {
160160 decls: *Scope.Decls,
161161
162162 pub fn destroy(self: *Struct, comp: *Compilation) void {
163 comp.a().destroy(self);
163 comp.gpa().destroy(self);
164164 }
165165
166166 pub fn getLlvmType(self: *Struct, ofile: *ObjectFile) llvm.TypeRef {
......@@ -180,7 +180,7 @@ pub const Type = struct {
180180 };
181181
182182 pub fn create(comp: *Compilation, return_type: *Type, params: []Param, is_var_args: bool) !*Fn {
183 const result = try comp.a().create(Fn{
183 const result = try comp.gpa().create(Fn{
184184 .base = Type{
185185 .base = Value{
186186 .id = Value.Id.Type,
......@@ -193,7 +193,7 @@ pub const Type = struct {
193193 .params = params,
194194 .is_var_args = is_var_args,
195195 });
196 errdefer comp.a().destroy(result);
196 errdefer comp.gpa().destroy(result);
197197
198198 result.return_type.base.ref();
199199 for (result.params) |param| {
......@@ -207,7 +207,7 @@ pub const Type = struct {
207207 for (self.params) |param| {
208208 param.typeof.base.deref(comp);
209209 }
210 comp.a().destroy(self);
210 comp.gpa().destroy(self);
211211 }
212212
213213 pub fn getLlvmType(self: *Fn, ofile: *ObjectFile) !llvm.TypeRef {
......@@ -215,8 +215,8 @@ pub const Type = struct {
215215 Type.Id.Void => llvm.VoidTypeInContext(ofile.context) orelse return error.OutOfMemory,
216216 else => try self.return_type.getLlvmType(ofile),
217217 };
218 const llvm_param_types = try ofile.a().alloc(llvm.TypeRef, self.params.len);
219 defer ofile.a().free(llvm_param_types);
218 const llvm_param_types = try ofile.gpa().alloc(llvm.TypeRef, self.params.len);
219 defer ofile.gpa().free(llvm_param_types);
220220 for (llvm_param_types) |*llvm_param_type, i| {
221221 llvm_param_type.* = try self.params[i].typeof.getLlvmType(ofile);
222222 }
......@@ -241,7 +241,7 @@ pub const Type = struct {
241241 }
242242
243243 pub fn destroy(self: *MetaType, comp: *Compilation) void {
244 comp.a().destroy(self);
244 comp.gpa().destroy(self);
245245 }
246246 };
247247
......@@ -255,7 +255,7 @@ pub const Type = struct {
255255 }
256256
257257 pub fn destroy(self: *Void, comp: *Compilation) void {
258 comp.a().destroy(self);
258 comp.gpa().destroy(self);
259259 }
260260 };
261261
......@@ -269,7 +269,7 @@ pub const Type = struct {
269269 }
270270
271271 pub fn destroy(self: *Bool, comp: *Compilation) void {
272 comp.a().destroy(self);
272 comp.gpa().destroy(self);
273273 }
274274
275275 pub fn getLlvmType(self: *Bool, ofile: *ObjectFile) llvm.TypeRef {
......@@ -287,7 +287,7 @@ pub const Type = struct {
287287 }
288288
289289 pub fn destroy(self: *NoReturn, comp: *Compilation) void {
290 comp.a().destroy(self);
290 comp.gpa().destroy(self);
291291 }
292292 };
293293
......@@ -295,7 +295,7 @@ pub const Type = struct {
295295 base: Type,
296296
297297 pub fn destroy(self: *Int, comp: *Compilation) void {
298 comp.a().destroy(self);
298 comp.gpa().destroy(self);
299299 }
300300
301301 pub fn getLlvmType(self: *Int, ofile: *ObjectFile) llvm.TypeRef {
......@@ -307,7 +307,7 @@ pub const Type = struct {
307307 base: Type,
308308
309309 pub fn destroy(self: *Float, comp: *Compilation) void {
310 comp.a().destroy(self);
310 comp.gpa().destroy(self);
311311 }
312312
313313 pub fn getLlvmType(self: *Float, ofile: *ObjectFile) llvm.TypeRef {
......@@ -332,7 +332,7 @@ pub const Type = struct {
332332 pub const Size = builtin.TypeInfo.Pointer.Size;
333333
334334 pub fn destroy(self: *Pointer, comp: *Compilation) void {
335 comp.a().destroy(self);
335 comp.gpa().destroy(self);
336336 }
337337
338338 pub fn get(
......@@ -355,7 +355,7 @@ pub const Type = struct {
355355 base: Type,
356356
357357 pub fn destroy(self: *Array, comp: *Compilation) void {
358 comp.a().destroy(self);
358 comp.gpa().destroy(self);
359359 }
360360
361361 pub fn getLlvmType(self: *Array, ofile: *ObjectFile) llvm.TypeRef {
......@@ -367,7 +367,7 @@ pub const Type = struct {
367367 base: Type,
368368
369369 pub fn destroy(self: *ComptimeFloat, comp: *Compilation) void {
370 comp.a().destroy(self);
370 comp.gpa().destroy(self);
371371 }
372372 };
373373
......@@ -375,7 +375,7 @@ pub const Type = struct {
375375 base: Type,
376376
377377 pub fn destroy(self: *ComptimeInt, comp: *Compilation) void {
378 comp.a().destroy(self);
378 comp.gpa().destroy(self);
379379 }
380380 };
381381
......@@ -383,7 +383,7 @@ pub const Type = struct {
383383 base: Type,
384384
385385 pub fn destroy(self: *Undefined, comp: *Compilation) void {
386 comp.a().destroy(self);
386 comp.gpa().destroy(self);
387387 }
388388 };
389389
......@@ -391,7 +391,7 @@ pub const Type = struct {
391391 base: Type,
392392
393393 pub fn destroy(self: *Null, comp: *Compilation) void {
394 comp.a().destroy(self);
394 comp.gpa().destroy(self);
395395 }
396396 };
397397
......@@ -399,7 +399,7 @@ pub const Type = struct {
399399 base: Type,
400400
401401 pub fn destroy(self: *Optional, comp: *Compilation) void {
402 comp.a().destroy(self);
402 comp.gpa().destroy(self);
403403 }
404404
405405 pub fn getLlvmType(self: *Optional, ofile: *ObjectFile) llvm.TypeRef {
......@@ -411,7 +411,7 @@ pub const Type = struct {
411411 base: Type,
412412
413413 pub fn destroy(self: *ErrorUnion, comp: *Compilation) void {
414 comp.a().destroy(self);
414 comp.gpa().destroy(self);
415415 }
416416
417417 pub fn getLlvmType(self: *ErrorUnion, ofile: *ObjectFile) llvm.TypeRef {
......@@ -423,7 +423,7 @@ pub const Type = struct {
423423 base: Type,
424424
425425 pub fn destroy(self: *ErrorSet, comp: *Compilation) void {
426 comp.a().destroy(self);
426 comp.gpa().destroy(self);
427427 }
428428
429429 pub fn getLlvmType(self: *ErrorSet, ofile: *ObjectFile) llvm.TypeRef {
......@@ -435,7 +435,7 @@ pub const Type = struct {
435435 base: Type,
436436
437437 pub fn destroy(self: *Enum, comp: *Compilation) void {
438 comp.a().destroy(self);
438 comp.gpa().destroy(self);
439439 }
440440
441441 pub fn getLlvmType(self: *Enum, ofile: *ObjectFile) llvm.TypeRef {
......@@ -447,7 +447,7 @@ pub const Type = struct {
447447 base: Type,
448448
449449 pub fn destroy(self: *Union, comp: *Compilation) void {
450 comp.a().destroy(self);
450 comp.gpa().destroy(self);
451451 }
452452
453453 pub fn getLlvmType(self: *Union, ofile: *ObjectFile) llvm.TypeRef {
......@@ -459,7 +459,7 @@ pub const Type = struct {
459459 base: Type,
460460
461461 pub fn destroy(self: *Namespace, comp: *Compilation) void {
462 comp.a().destroy(self);
462 comp.gpa().destroy(self);
463463 }
464464 };
465465
......@@ -467,7 +467,7 @@ pub const Type = struct {
467467 base: Type,
468468
469469 pub fn destroy(self: *Block, comp: *Compilation) void {
470 comp.a().destroy(self);
470 comp.gpa().destroy(self);
471471 }
472472 };
473473
......@@ -475,7 +475,7 @@ pub const Type = struct {
475475 base: Type,
476476
477477 pub fn destroy(self: *BoundFn, comp: *Compilation) void {
478 comp.a().destroy(self);
478 comp.gpa().destroy(self);
479479 }
480480
481481 pub fn getLlvmType(self: *BoundFn, ofile: *ObjectFile) llvm.TypeRef {
......@@ -487,7 +487,7 @@ pub const Type = struct {
487487 base: Type,
488488
489489 pub fn destroy(self: *ArgTuple, comp: *Compilation) void {
490 comp.a().destroy(self);
490 comp.gpa().destroy(self);
491491 }
492492 };
493493
......@@ -495,7 +495,7 @@ pub const Type = struct {
495495 base: Type,
496496
497497 pub fn destroy(self: *Opaque, comp: *Compilation) void {
498 comp.a().destroy(self);
498 comp.gpa().destroy(self);
499499 }
500500
501501 pub fn getLlvmType(self: *Opaque, ofile: *ObjectFile) llvm.TypeRef {
......@@ -507,7 +507,7 @@ pub const Type = struct {
507507 base: Type,
508508
509509 pub fn destroy(self: *Promise, comp: *Compilation) void {
510 comp.a().destroy(self);
510 comp.gpa().destroy(self);
511511 }
512512
513513 pub fn getLlvmType(self: *Promise, ofile: *ObjectFile) llvm.TypeRef {
src-self-hosted/value.zig+33-8
......@@ -4,6 +4,7 @@ const Scope = @import("scope.zig").Scope;
44const Compilation = @import("compilation.zig").Compilation;
55const ObjectFile = @import("codegen.zig").ObjectFile;
66const llvm = @import("llvm.zig");
7const Buffer = std.Buffer;
78
89/// Values are ref-counted, heap-allocated, and copy-on-write
910/// If there is only 1 ref then write need not copy
......@@ -68,7 +69,7 @@ pub const Value = struct {
6869
6970 /// The main external name that is used in the .o file.
7071 /// TODO https://github.com/ziglang/zig/issues/265
71 symbol_name: std.Buffer,
72 symbol_name: Buffer,
7273
7374 /// parent should be the top level decls or container decls
7475 fndef_scope: *Scope.FnDef,
......@@ -79,10 +80,22 @@ pub const Value = struct {
7980 /// parent is child_scope
8081 block_scope: *Scope.Block,
8182
83 /// Path to the object file that contains this function
84 containing_object: Buffer,
85
86 link_set_node: *std.LinkedList(?*Value.Fn).Node,
87
8288 /// Creates a Fn value with 1 ref
8389 /// Takes ownership of symbol_name
84 pub fn create(comp: *Compilation, fn_type: *Type.Fn, fndef_scope: *Scope.FnDef, symbol_name: std.Buffer) !*Fn {
85 const self = try comp.a().create(Fn{
90 pub fn create(comp: *Compilation, fn_type: *Type.Fn, fndef_scope: *Scope.FnDef, symbol_name: Buffer) !*Fn {
91 const link_set_node = try comp.gpa().create(Compilation.FnLinkSet.Node{
92 .data = null,
93 .next = undefined,
94 .prev = undefined,
95 });
96 errdefer comp.gpa().destroy(link_set_node);
97
98 const self = try comp.gpa().create(Fn{
8699 .base = Value{
87100 .id = Value.Id.Fn,
88101 .typeof = &fn_type.base,
......@@ -92,6 +105,8 @@ pub const Value = struct {
92105 .child_scope = &fndef_scope.base,
93106 .block_scope = undefined,
94107 .symbol_name = symbol_name,
108 .containing_object = Buffer.initNull(comp.gpa()),
109 .link_set_node = link_set_node,
95110 });
96111 fn_type.base.base.ref();
97112 fndef_scope.fn_val = self;
......@@ -100,9 +115,19 @@ pub const Value = struct {
100115 }
101116
102117 pub fn destroy(self: *Fn, comp: *Compilation) void {
118 // remove with a tombstone so that we do not have to grab a lock
119 if (self.link_set_node.data != null) {
120 // it's now the job of the link step to find this tombstone and
121 // deallocate it.
122 self.link_set_node.data = null;
123 } else {
124 comp.gpa().destroy(self.link_set_node);
125 }
126
127 self.containing_object.deinit();
103128 self.fndef_scope.base.deref(comp);
104129 self.symbol_name.deinit();
105 comp.a().destroy(self);
130 comp.gpa().destroy(self);
106131 }
107132 };
108133
......@@ -115,7 +140,7 @@ pub const Value = struct {
115140 }
116141
117142 pub fn destroy(self: *Void, comp: *Compilation) void {
118 comp.a().destroy(self);
143 comp.gpa().destroy(self);
119144 }
120145 };
121146
......@@ -134,7 +159,7 @@ pub const Value = struct {
134159 }
135160
136161 pub fn destroy(self: *Bool, comp: *Compilation) void {
137 comp.a().destroy(self);
162 comp.gpa().destroy(self);
138163 }
139164
140165 pub fn getLlvmConst(self: *Bool, ofile: *ObjectFile) ?llvm.ValueRef {
......@@ -156,7 +181,7 @@ pub const Value = struct {
156181 }
157182
158183 pub fn destroy(self: *NoReturn, comp: *Compilation) void {
159 comp.a().destroy(self);
184 comp.gpa().destroy(self);
160185 }
161186 };
162187
......@@ -170,7 +195,7 @@ pub const Value = struct {
170195 };
171196
172197 pub fn destroy(self: *Ptr, comp: *Compilation) void {
173 comp.a().destroy(self);
198 comp.gpa().destroy(self);
174199 }
175200 };
176201};
src/zig_llvm.cpp+5
......@@ -440,6 +440,11 @@ ZigLLVMDIBuilder *ZigLLVMCreateDIBuilder(LLVMModuleRef module, bool allow_unreso
440440 return reinterpret_cast<ZigLLVMDIBuilder *>(di_builder);
441441}
442442
443void ZigLLVMDisposeDIBuilder(ZigLLVMDIBuilder *dbuilder) {
444 DIBuilder *di_builder = reinterpret_cast<DIBuilder *>(dbuilder);
445 delete di_builder;
446}
447
443448void ZigLLVMSetCurrentDebugLocation(LLVMBuilderRef builder, int line, int column, ZigLLVMDIScope *scope) {
444449 unwrap(builder)->SetCurrentDebugLocation(DebugLoc::get(
445450 line, column, reinterpret_cast<DIScope*>(scope)));
src/zig_llvm.h+2-1
......@@ -39,7 +39,7 @@ struct ZigLLVMInsertionPoint;
3939ZIG_EXTERN_C void ZigLLVMInitializeLoopStrengthReducePass(LLVMPassRegistryRef R);
4040ZIG_EXTERN_C void ZigLLVMInitializeLowerIntrinsicsPass(LLVMPassRegistryRef R);
4141
42/// Caller must free memory.
42/// Caller must free memory with LLVMDisposeMessage
4343ZIG_EXTERN_C char *ZigLLVMGetHostCPUName(void);
4444ZIG_EXTERN_C char *ZigLLVMGetNativeFeatures(void);
4545
......@@ -139,6 +139,7 @@ ZIG_EXTERN_C unsigned ZigLLVMTag_DW_enumeration_type(void);
139139ZIG_EXTERN_C unsigned ZigLLVMTag_DW_union_type(void);
140140
141141ZIG_EXTERN_C struct ZigLLVMDIBuilder *ZigLLVMCreateDIBuilder(LLVMModuleRef module, bool allow_unresolved);
142ZIG_EXTERN_C void ZigLLVMDisposeDIBuilder(struct ZigLLVMDIBuilder *dbuilder);
142143ZIG_EXTERN_C void ZigLLVMAddModuleDebugInfoFlag(LLVMModuleRef module);
143144ZIG_EXTERN_C void ZigLLVMAddModuleCodeViewFlag(LLVMModuleRef module);
144145
std/atomic/int.zig+4
......@@ -25,5 +25,9 @@ pub fn Int(comptime T: type) type {
2525 pub fn get(self: *Self) T {
2626 return @atomicLoad(T, &self.unprotected_value, AtomicOrder.SeqCst);
2727 }
28
29 pub fn xchg(self: *Self, new_value: T) T {
30 return @atomicRmw(T, &self.unprotected_value, builtin.AtomicRmwOp.Xchg, new_value, AtomicOrder.SeqCst);
31 }
2832 };
2933}
std/buffer.zig+13
......@@ -54,6 +54,19 @@ pub const Buffer = struct {
5454 return result;
5555 }
5656
57 pub fn allocPrint(allocator: *Allocator, comptime format: []const u8, args: ...) !Buffer {
58 const countSize = struct {
59 fn countSize(size: *usize, bytes: []const u8) (error{}!void) {
60 size.* += bytes.len;
61 }
62 }.countSize;
63 var size: usize = 0;
64 std.fmt.format(&size, error{}, countSize, format, args) catch |err| switch (err) {};
65 var self = try Buffer.initSize(allocator, size);
66 assert((std.fmt.bufPrint(self.list.items, format, args) catch unreachable).len == size);
67 return self;
68 }
69
5770 pub fn deinit(self: *Buffer) void {
5871 self.list.deinit();
5972 }
std/dwarf.zig+37
......@@ -639,3 +639,40 @@ pub const LNE_define_file = 0x03;
639639pub const LNE_set_discriminator = 0x04;
640640pub const LNE_lo_user = 0x80;
641641pub const LNE_hi_user = 0xff;
642
643pub const LANG_C89 = 0x0001;
644pub const LANG_C = 0x0002;
645pub const LANG_Ada83 = 0x0003;
646pub const LANG_C_plus_plus = 0x0004;
647pub const LANG_Cobol74 = 0x0005;
648pub const LANG_Cobol85 = 0x0006;
649pub const LANG_Fortran77 = 0x0007;
650pub const LANG_Fortran90 = 0x0008;
651pub const LANG_Pascal83 = 0x0009;
652pub const LANG_Modula2 = 0x000a;
653pub const LANG_Java = 0x000b;
654pub const LANG_C99 = 0x000c;
655pub const LANG_Ada95 = 0x000d;
656pub const LANG_Fortran95 = 0x000e;
657pub const LANG_PLI = 0x000f;
658pub const LANG_ObjC = 0x0010;
659pub const LANG_ObjC_plus_plus = 0x0011;
660pub const LANG_UPC = 0x0012;
661pub const LANG_D = 0x0013;
662pub const LANG_Python = 0x0014;
663pub const LANG_Go = 0x0016;
664pub const LANG_C_plus_plus_11 = 0x001a;
665pub const LANG_Rust = 0x001c;
666pub const LANG_C11 = 0x001d;
667pub const LANG_C_plus_plus_14 = 0x0021;
668pub const LANG_Fortran03 = 0x0022;
669pub const LANG_Fortran08 = 0x0023;
670pub const LANG_lo_user = 0x8000;
671pub const LANG_hi_user = 0xffff;
672pub const LANG_Mips_Assembler = 0x8001;
673pub const LANG_Upc = 0x8765;
674pub const LANG_HP_Bliss = 0x8003;
675pub const LANG_HP_Basic91 = 0x8004;
676pub const LANG_HP_Pascal91 = 0x8005;
677pub const LANG_HP_IMacro = 0x8006;
678pub const LANG_HP_Assembler = 0x8007;
std/event/future.zig+31-8
......@@ -6,15 +6,20 @@ const AtomicOrder = builtin.AtomicOrder;
66const Lock = std.event.Lock;
77const Loop = std.event.Loop;
88
9/// This is a value that starts out unavailable, until a value is put().
9/// This is a value that starts out unavailable, until resolve() is called
1010/// While it is unavailable, coroutines suspend when they try to get() it,
11/// and then are resumed when the value is put().
12/// At this point the value remains forever available, and another put() is not allowed.
11/// and then are resumed when resolve() is called.
12/// At this point the value remains forever available, and another resolve() is not allowed.
1313pub fn Future(comptime T: type) type {
1414 return struct {
1515 lock: Lock,
1616 data: T,
17 available: u8, // TODO make this a bool
17
18 /// TODO make this an enum
19 /// 0 - not started
20 /// 1 - started
21 /// 2 - finished
22 available: u8,
1823
1924 const Self = this;
2025 const Queue = std.atomic.Queue(promise);
......@@ -31,7 +36,7 @@ pub fn Future(comptime T: type) type {
3136 /// available.
3237 /// Thread-safe.
3338 pub async fn get(self: *Self) *T {
34 if (@atomicLoad(u8, &self.available, AtomicOrder.SeqCst) == 1) {
39 if (@atomicLoad(u8, &self.available, AtomicOrder.SeqCst) == 2) {
3540 return &self.data;
3641 }
3742 const held = await (async self.lock.acquire() catch unreachable);
......@@ -43,18 +48,36 @@ pub fn Future(comptime T: type) type {
4348 /// Gets the data without waiting for it. If it's available, a pointer is
4449 /// returned. Otherwise, null is returned.
4550 pub fn getOrNull(self: *Self) ?*T {
46 if (@atomicLoad(u8, &self.available, AtomicOrder.SeqCst) == 1) {
51 if (@atomicLoad(u8, &self.available, AtomicOrder.SeqCst) == 2) {
4752 return &self.data;
4853 } else {
4954 return null;
5055 }
5156 }
5257
58 /// If someone else has started working on the data, wait for them to complete
59 /// and return a pointer to the data. Otherwise, return null, and the caller
60 /// should start working on the data.
61 /// It's not required to call start() before resolve() but it can be useful since
62 /// this method is thread-safe.
63 pub async fn start(self: *Self) ?*T {
64 const state = @cmpxchgStrong(u8, &self.available, 0, 1, AtomicOrder.SeqCst, AtomicOrder.SeqCst) orelse return null;
65 switch (state) {
66 1 => {
67 const held = await (async self.lock.acquire() catch unreachable);
68 held.release();
69 return &self.data;
70 },
71 2 => return &self.data,
72 else => unreachable,
73 }
74 }
75
5376 /// Make the data become available. May be called only once.
5477 /// Before calling this, modify the `data` property.
5578 pub fn resolve(self: *Self) void {
56 const prev = @atomicRmw(u8, &self.available, AtomicRmwOp.Xchg, 1, AtomicOrder.SeqCst);
57 assert(prev == 0); // put() called twice
79 const prev = @atomicRmw(u8, &self.available, AtomicRmwOp.Xchg, 2, AtomicOrder.SeqCst);
80 assert(prev == 0 or prev == 1); // resolve() called twice
5881 Lock.Held.release(Lock.Held{ .lock = &self.lock });
5982 }
6083 };
std/index.zig+3
......@@ -36,6 +36,8 @@ pub const sort = @import("sort.zig");
3636pub const unicode = @import("unicode.zig");
3737pub const zig = @import("zig/index.zig");
3838
39pub const lazyInit = @import("lazy_init.zig").lazyInit;
40
3941test "std" {
4042 // run tests from these
4143 _ = @import("atomic/index.zig");
......@@ -71,4 +73,5 @@ test "std" {
7173 _ = @import("sort.zig");
7274 _ = @import("unicode.zig");
7375 _ = @import("zig/index.zig");
76 _ = @import("lazy_init.zig");
7477}
std/lazy_init.zig created+85
......@@ -0,0 +1,85 @@
1const std = @import("index.zig");
2const builtin = @import("builtin");
3const assert = std.debug.assert;
4const AtomicRmwOp = builtin.AtomicRmwOp;
5const AtomicOrder = builtin.AtomicOrder;
6
7/// Thread-safe initialization of global data.
8/// TODO use a mutex instead of a spinlock
9pub fn lazyInit(comptime T: type) LazyInit(T) {
10 return LazyInit(T){
11 .data = undefined,
12 .state = 0,
13 };
14}
15
16fn LazyInit(comptime T: type) type {
17 return struct {
18 state: u8, // TODO make this an enum
19 data: Data,
20
21 const Self = this;
22
23 // TODO this isn't working for void, investigate and then remove this special case
24 const Data = if (@sizeOf(T) == 0) u8 else T;
25 const Ptr = if (T == void) void else *T;
26
27 /// Returns a usable pointer to the initialized data,
28 /// or returns null, indicating that the caller should
29 /// perform the initialization and then call resolve().
30 pub fn get(self: *Self) ?Ptr {
31 while (true) {
32 var state = @cmpxchgWeak(u8, &self.state, 0, 1, AtomicOrder.SeqCst, AtomicOrder.SeqCst) orelse return null;
33 switch (state) {
34 0 => continue,
35 1 => {
36 // TODO mutex instead of a spinlock
37 continue;
38 },
39 2 => {
40 if (@sizeOf(T) == 0) {
41 return T(undefined);
42 } else {
43 return &self.data;
44 }
45 },
46 else => unreachable,
47 }
48 }
49 }
50
51 pub fn resolve(self: *Self) void {
52 const prev = @atomicRmw(u8, &self.state, AtomicRmwOp.Xchg, 2, AtomicOrder.SeqCst);
53 assert(prev == 1); // resolve() called twice
54 }
55 };
56}
57
58var global_number = lazyInit(i32);
59
60test "std.lazyInit" {
61 if (global_number.get()) |_| @panic("bad") else {
62 global_number.data = 1234;
63 global_number.resolve();
64 }
65 if (global_number.get()) |x| {
66 assert(x.* == 1234);
67 } else {
68 @panic("bad");
69 }
70 if (global_number.get()) |x| {
71 assert(x.* == 1234);
72 } else {
73 @panic("bad");
74 }
75}
76
77var global_void = lazyInit(void);
78
79test "std.lazyInit(void)" {
80 if (global_void.get()) |_| @panic("bad") else {
81 global_void.resolve();
82 }
83 assert(global_void.get() != null);
84 assert(global_void.get() != null);
85}