|
15 | 15 | namespace Ubiquity.NET.Llvm
|
16 | 16 | {
|
17 | 17 | /// <summary>Maintains a global cache of <see cref="LLVMContextRef"/> to <see cref="Context"/> mappings</summary>
|
| 18 | + /// <remarks> |
| 19 | + /// The public constructor <see cref="Context.Context()"/> will add itself to the cache, since it is a new instance |
| 20 | + /// that is a safe operation. In all other cases a lookup in the cache based on the underlying LLVM handle is |
| 21 | + /// performed in a thread safe manner. |
| 22 | + /// </remarks> |
18 | 23 | internal static class ContextCache
|
19 | 24 | {
|
20 |
| - internal static bool TryGetValue( LLVMContextRef h, out Context value ) |
21 |
| - { |
22 |
| - return Instance.Value.TryGetValue( h, out value ); |
23 |
| - } |
24 |
| - |
25 |
| - internal static bool Remove( LLVMContextRef h ) |
| 25 | + internal static bool TryRemove( LLVMContextRef h ) |
26 | 26 | {
|
27 | 27 | return Instance.Value.TryRemove( h, out Context _ );
|
28 | 28 | }
|
29 | 29 |
|
30 |
| - internal static Context Add( Context context ) |
| 30 | + internal static void Add( Context context ) |
31 | 31 | {
|
32 |
| - return Instance.Value.GetOrAdd( context.ContextHandle, context ); |
| 32 | + if( !Instance.Value.TryAdd( context.ContextHandle, context ) ) |
| 33 | + { |
| 34 | + throw new InternalCodeGeneratorException( "Internal Error: Can't add context to Cache as it already exists!" ); |
| 35 | + } |
33 | 36 | }
|
34 | 37 |
|
35 | 38 | internal static Context GetContextFor( LLVMContextRef contextRef )
|
36 | 39 | {
|
37 |
| - contextRef.ValidateNotNull( nameof( contextRef ) ); |
38 |
| - |
39 |
| - if( TryGetValue( contextRef, out Context retVal ) ) |
40 |
| - { |
41 |
| - return retVal; |
42 |
| - } |
43 |
| - |
44 |
| - // Context constructor will add itself to this cache |
45 |
| - // and remove itself on Dispose/finalize |
46 |
| - // TODO: resolve thread safety bug (https://github.com/UbiquityDotNET/Llvm.NET/issues/179) |
47 |
| - return new Context( contextRef ); |
| 40 | + contextRef.ThrowIfInvalid( ); |
| 41 | + return Instance.Value.GetOrAdd( contextRef, h => new Context( h ) ); |
48 | 42 | }
|
49 | 43 |
|
50 | 44 | private static ConcurrentDictionary<LLVMContextRef, Context> CreateInstance( )
|
|
0 commit comments