-
Notifications
You must be signed in to change notification settings - Fork 115
/
IRContext.cs
591 lines (527 loc) · 20.8 KB
/
IRContext.cs
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
// -----------------------------------------------------------------------------
// ILGPU
// Copyright (c) 2016-2019 Marcel Koester
// www.ilgpu.net
//
// File: IRContext.cs
//
// This file is part of ILGPU and is distributed under the University of
// Illinois Open Source License. See LICENSE.txt for details
// -----------------------------------------------------------------------------
using ILGPU.IR.Analyses;
using ILGPU.IR.Transformations;
using ILGPU.IR.Types;
using ILGPU.IR.Values;
using ILGPU.Util;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace ILGPU.IR
{
/// <summary>
/// Represents an IR context.
/// </summary>
public sealed partial class IRContext : DisposeBase, ICache
{
#region Nested Types
/// <summary>
/// Represents no transformer handler.
/// </summary>
private readonly struct NoHandler : ITransformerHandler
{
/// <summary cref="ITransformerHandler.BeforeTransformation(IRContext, Transformation)"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void BeforeTransformation(
IRContext context,
Transformation transformation)
{ }
/// <summary cref="ITransformerHandler.AfterTransformation(IRContext, Transformation)"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AfterTransformation(
IRContext context,
Transformation transformation)
{ }
}
#endregion
#region Instance
private readonly ReaderWriterLockSlim irLock = new ReaderWriterLockSlim(
LockRecursionPolicy.SupportsRecursion);
private readonly Action<Method> gcDelegate;
private readonly MethodMapping<Method> methods = new MethodMapping<Method>();
/// <summary>
/// Constructs a new IR context.
/// </summary>
/// <param name="context">The associated main context.</param>
public IRContext(Context context)
{
Context = context ?? throw new ArgumentNullException(nameof(context));
TypeContext = context.TypeContext;
gcDelegate = (Method method) => method.GC();
}
#endregion
#region Properties
/// <summary>
/// Returns the main ILGPU context.
/// </summary>
public Context Context { get; }
/// <summary>
/// Returns the associated type context.
/// </summary>
public IRTypeContext TypeContext { get; }
/// <summary>
/// Returns the associated flags.
/// </summary>
public ContextFlags Flags => Context.Flags;
/// <summary>
/// Internal (unsafe) access to all top-level functions.
/// </summary>
/// <remarks>
/// The resulting collection is not thread safe in terms
/// of parallel operations on this context.
/// </remarks>
public UnsafeMethodCollection<MethodCollections.AllMethods> UnsafeMethods =>
GetUnsafeMethodCollection(new MethodCollections.AllMethods());
/// <summary>
/// Returns all top-level functions.
/// </summary>
public MethodCollection<MethodCollections.AllMethods> Methods =>
GetMethodCollection(new MethodCollections.AllMethods());
#endregion
#region Methods
/// <summary>
/// Returns true if the current context has the given flags.
/// </summary>
/// <param name="flags">The flags to check.</param>
/// <returns>True, if the current context has the given flags.</returns>
public bool HasFlags(ContextFlags flags) => Context.HasFlags(flags);
/// <summary>
/// Returns an unsafe (not thread-safe) function view.
/// </summary>
/// <typeparam name="TPredicate">The type of the predicate to apply.</typeparam>
/// <param name="predicate">The predicate to apply.</param>
/// <returns>The resolved function view.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public UnsafeMethodCollection<TPredicate> GetUnsafeMethodCollection<TPredicate>(TPredicate predicate)
where TPredicate : IMethodCollectionPredicate =>
new UnsafeMethodCollection<TPredicate>(this, methods.AsReadOnly(), predicate);
/// <summary>
/// Returns a thread-safe function view.
/// </summary>
/// <typeparam name="TPredicate">The type of the predicate to apply.</typeparam>
/// <param name="predicate">The predicate to apply.</param>
/// <returns>The resolved function view.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public MethodCollection<TPredicate> GetMethodCollection<TPredicate>(TPredicate predicate)
where TPredicate : IMethodCollectionPredicate
{
irLock.EnterReadLock();
try
{
var builder = ImmutableArray.CreateBuilder<Method>(
methods.Count);
foreach (var function in methods)
{
if (predicate.Match(function))
builder.Add(function);
}
return new MethodCollection<TPredicate>(this, builder.ToImmutable(), predicate);
}
finally
{
irLock.ExitReadLock();
}
}
/// <summary>
/// Creates a new unique node marker.
/// </summary>
/// <returns>The new node marker.</returns>
public NodeMarker NewNodeMarker() => Context.NewNodeMarker();
/// <summary>
/// Tries to resolve the given managed method to function reference.
/// </summary>
/// <param name="method">The method to resolve.</param>
/// <param name="handle">The resolved function reference (if any).</param>
/// <returns>True, iff the requested function could be resolved.</returns>
public bool TryGetMethodHandle(MethodBase method, out MethodHandle handle)
{
if (method == null)
throw new ArgumentNullException(nameof(method));
irLock.EnterReadLock();
try
{
return methods.TryGetHandle(method, out handle);
}
finally
{
irLock.ExitReadLock();
}
}
/// <summary>
/// Tries to resolve the given handle to a top-level function.
/// </summary>
/// <param name="handle">The function handle to resolve.</param>
/// <param name="function">The resolved function (if any).</param>
/// <returns>True, iff the requested function could be resolved.</returns>
public bool TryGetMethod(MethodHandle handle, out Method function)
{
if (handle.IsEmpty)
{
function = null;
return false;
}
irLock.EnterReadLock();
try
{
return methods.TryGetData(handle, out function);
}
finally
{
irLock.ExitReadLock();
}
}
/// <summary>
/// Tries to resolve the given method to a top-level function.
/// </summary>
/// <param name="method">The method to resolve.</param>
/// <param name="function">The resolved function (if any).</param>
/// <returns>True, iff the requested function could be resolved.</returns>
public bool TryGetMethod(MethodBase method, out Method function)
{
if (method == null)
throw new ArgumentNullException(nameof(method));
function = null;
irLock.EnterReadLock();
try
{
if (!methods.TryGetHandle(method, out MethodHandle handle))
return false;
return methods.TryGetData(handle, out function);
}
finally
{
irLock.ExitReadLock();
}
}
/// <summary>
/// Resolves the given method to a top-level function.
/// </summary>
/// <param name="method">The method to resolve.</param>
/// <returns>The resolved function.</returns>
public Method GetMethod(MethodHandle method)
{
if (!TryGetMethod(method, out Method function))
throw new InvalidOperationException("Could not find the corresponding top-level function");
return function;
}
/// <summary>
/// Declares a method.
/// </summary>
/// <param name="methodBase">The method to declare.</param>
/// <param name="created">True, iff the method has been created.</param>
/// <returns>The declared method.</returns>
internal Method Declare(
MethodBase methodBase,
out bool created)
{
Debug.Assert(methodBase != null, "Invalid method base");
// Check for existing method
irLock.EnterUpgradeableReadLock();
try
{
if (methods.TryGetHandle(methodBase, out MethodHandle handle))
{
created = false;
return methods[handle];
}
handle = MethodHandle.Create(methodBase.Name);
var declaration = new MethodDeclaration(
handle,
CreateType(methodBase.GetReturnType()),
methodBase);
return Declare(declaration, out created);
}
finally
{
irLock.ExitUpgradeableReadLock();
}
}
/// <summary>
/// Declares a method.
/// </summary>
/// <param name="declaration">The method declaration.</param>
/// <param name="created">True, iff the method has been created.</param>
/// <returns>The declared method.</returns>
internal Method Declare(
in MethodDeclaration declaration,
out bool created)
{
Debug.Assert(declaration.ReturnType != null, "Invalid return type");
created = false;
irLock.EnterUpgradeableReadLock();
try
{
if (!methods.TryGetData(declaration.Handle, out Method function))
{
irLock.EnterWriteLock();
try
{
created = true;
var functionId = Context.CreateFunctionHandle();
var functionName = declaration.HasSource ? declaration.Source.Name :
declaration.Handle.Name ?? "Func";
var handle = new MethodHandle(functionId, functionName);
var specializedDeclaration = declaration.Specialize(handle);
function = new Method(this, specializedDeclaration);
methods.Register(handle, function);
// Check for external function
if (declaration.HasFlags(MethodFlags.External))
{
using (var builder = function.CreateBuilder())
{
var bbBuilder = builder.CreateEntryBlock();
var returnValue = bbBuilder.CreateNull(declaration.ReturnType);
bbBuilder.CreateReturn(returnValue);
}
}
}
finally
{
irLock.ExitWriteLock();
}
}
return function;
}
finally
{
irLock.ExitUpgradeableReadLock();
}
}
/// <summary>
/// Imports the given method (and all dependencies) into this context.
/// </summary>
/// <typeparam name="TScopeProvider">The provider to resolve methods to scopes.</typeparam>
/// <param name="source">The method to import.</param>
/// <param name="scopeProvider">Resolves methods to scopes.</param>
/// <returns>The imported method.</returns>
public Method Import<TScopeProvider>(Method source, TScopeProvider scopeProvider)
where TScopeProvider : IScopeProvider
{
irLock.EnterUpgradeableReadLock();
try
{
if (methods.TryGetData(source.Handle, out Method method))
return method;
irLock.EnterWriteLock();
try
{
return ImportInternal(source, scopeProvider);
}
finally
{
irLock.ExitWriteLock();
}
}
finally
{
irLock.ExitUpgradeableReadLock();
}
}
/// <summary>
/// Imports the given method (and all dependencies) into this context.
/// </summary>
/// <typeparam name="TScopeProvider">The provider to resolve methods to scopes.</typeparam>
/// <param name="source">The method to import.</param>
/// <param name="scopeProvider">Resolves methods to scopes.</param>
/// <returns>The imported method.</returns>
private Method ImportInternal<TScopeProvider>(Method source, TScopeProvider scopeProvider)
where TScopeProvider : IScopeProvider
{
Debug.Assert(source != null, "Invalid source");
Debug.Assert(source.Context != this, "Cannot import a function into the same context");
var allReferences = AllReferences.Create(
scopeProvider[source],
new MethodCollections.AllMethods(),
scopeProvider);
// Declare all functions and build mapping
var methodsToRebuild = new List<Method>();
var targetMapping = new Dictionary<Method, Method>();
foreach (var entry in allReferences)
{
var declared = Declare(entry.Key.Declaration, out bool created);
targetMapping.Add(entry.Key, declared);
if (created)
methodsToRebuild.Add(entry.Key);
}
// Rebuild all functions while using the created mapping
var methodMapping = new Method.MethodMapping(targetMapping);
foreach (var sourceMethod in methodsToRebuild)
{
var targetMethod = methodMapping[sourceMethod];
// Store original sequence point
targetMethod.SequencePoint = sourceMethod.SequencePoint;
using (var builder = targetMethod.CreateBuilder())
{
// Build new parameters to match the old ones
var parameterArguments = ImmutableArray.CreateBuilder<ValueReference>(
sourceMethod.NumParameters);
foreach (var param in sourceMethod.Parameters)
{
var newParam = builder.AddParameter(param.Type, param.Name);
parameterArguments.Add(newParam);
}
var parameterMapping = sourceMethod.CreateParameterMapping(
parameterArguments.MoveToImmutable());
// Rebuild the source function into this context
var references = allReferences[sourceMethod];
var rebuilder = builder.CreateRebuilder(
parameterMapping,
references.Scope,
methodMapping);
// Create appropriate return instructions
var exitBlocks = rebuilder.Rebuild();
foreach (var (blockBuilder, returnValue) in exitBlocks)
blockBuilder.CreateReturn(returnValue);
// Wire entry block
builder.EntryBlock = rebuilder.EntryBlock.BasicBlock;
}
}
return targetMapping[source];
}
/// <summary>
/// Creates an instantiated node by assigning a unique node id.
/// </summary>
/// <param name="value">The node to create.</param>
/// <returns>The created node.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void Create(Value value)
{
value.Id = Context.CreateNodeId();
}
/// <summary>
/// Applies all default optimization transformations.
/// </summary>
public void Optimize()
{
Transform(Context.ContextTransformer);
}
/// <summary>
/// Applies the given transfomer to the current context.
/// </summary>
/// <param name="transformer">The target transformer.</param>
public void Transform(in Transformer transformer) =>
Transform(transformer, new NoHandler());
/// <summary>
/// Applies the given transfomer to the current context.
/// </summary>
/// <typeparam name="THandler">The handler type.</typeparam>
/// <param name="transformer">The target transformer.</param>
/// <param name="handler">The target handler.</param>
public void Transform<THandler>(in Transformer transformer, THandler handler)
where THandler : ITransformerHandler
{
irLock.EnterWriteLock();
try
{
transformer.Transform(this, handler);
}
finally
{
irLock.ExitWriteLock();
}
}
/// <summary>
/// Dumps the IR context to the given file.
/// </summary>
public void DumpToFile(string fileName)
{
using (var stream = new StreamWriter(fileName, false))
Dump(stream);
}
/// <summary>
/// Dumps the IR context to the console output.
/// </summary>
public void DumpToConsole()
{
Dump(Console.Out);
}
/// <summary>
/// Dumps the IR context to the given text writer.
/// </summary>
/// <param name="textWriter">The text writer.</param>
public void Dump(TextWriter textWriter)
{
foreach (var method in UnsafeMethods)
{
method.Dump(textWriter, false);
textWriter.WriteLine();
textWriter.WriteLine("------------------------------");
}
}
#endregion
#region GC
/// <summary>
/// Rebuilds all nodes and clears up the IR.
/// </summary>
/// <remarks>
/// This method must not be invoked in the context of other
/// parallel operations using this context.
/// </remarks>
[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods",
Justification = "Users might want to force a global GC to free memory after an internal ILGPU GC run")]
public void GC()
{
irLock.EnterWriteLock();
try
{
Parallel.ForEach(UnsafeMethods, gcDelegate);
}
catch (Exception)
{
throw;
}
finally
{
irLock.ExitWriteLock();
}
// Check whether to call a forced system GC
if (HasFlags(ContextFlags.ForceSystemGC))
System.GC.Collect();
}
/// <summary>
/// Clears cached IR nodes.
/// </summary>
[Obsolete("Use ClearCache(ClearCacheMode.Everything) instead")]
public void Clear() => ClearCache(ClearCacheMode.Everything);
/// <summary>
/// Clears cached IR nodes.
/// </summary>
/// <param name="mode">The clear mode.</param>
public void ClearCache(ClearCacheMode mode)
{
irLock.EnterWriteLock();
try
{
methods.Clear();
}
finally
{
irLock.ExitWriteLock();
}
}
#endregion
#region IDisposable
/// <summary cref="DisposeBase.Dispose(bool)"/>
protected override void Dispose(bool disposing)
{
irLock.Dispose();
}
#endregion
}
}