forked from UbiquityDotNET/Llvm.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodeGenerator.cs
More file actions
663 lines (552 loc) · 30.5 KB
/
Copy pathCodeGenerator.cs
File metadata and controls
663 lines (552 loc) · 30.5 KB
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
// Copyright (c) Ubiquity.NET Contributors. All rights reserved.
// Licensed under the Apache-2.0 WITH LLVM-exception license. See the LICENSE.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Kaleidoscope.Grammar;
using Kaleidoscope.Grammar.AST;
using Ubiquity.NET.InteropHelpers;
using Ubiquity.NET.Llvm;
using Ubiquity.NET.Llvm.DebugInfo;
using Ubiquity.NET.Llvm.Instructions;
using Ubiquity.NET.Llvm.Values;
using Ubiquity.NET.Runtime.Utils;
using ConstantExpression = Kaleidoscope.Grammar.AST.ConstantExpression;
namespace Kaleidoscope.Chapter9
{
/// <summary>Performs LLVM IR Code generation from the Kaleidoscope AST</summary>
public sealed class CodeGenerator
: KaleidoscopeAstVisitorBase<Value>
, IDisposable
, ICodeGenerator<Module>
{
#region Initialization
public CodeGenerator( DynamicRuntimeState globalState, TargetMachine machine, string sourcePath )
: base( null )
{
ArgumentNullException.ThrowIfNull( globalState );
ArgumentNullException.ThrowIfNull( machine );
if(globalState.LanguageLevel > LanguageLevel.MutableVariables)
{
throw new ArgumentException( "Language features not supported by this generator", nameof( globalState ) );
}
RuntimeState = globalState;
Context = new Context();
TargetMachine = machine;
InstructionBuilder = new InstructionBuilder( Context );
Module = Context.CreateBitcodeModule( Path.GetFileName( sourcePath ) );
Module.TargetTriple = machine.Triple;
using var layout = TargetMachine.CreateTargetData();
Module.Layout = layout;
SourcePath = sourcePath;
}
#endregion
#region Dispose
public void Dispose( )
{
Module.Dispose();
InstructionBuilder.Dispose();
Context.Dispose();
}
#endregion
#region Generate
public Module? Generate( IAstNode ast )
{
ArgumentNullException.ThrowIfNull( ast );
using var diBuilder = new DIBuilder(Module);
CurrentDIBuilder = diBuilder.AsAlias(); // This gets the underlying unowned resource...
var cu = diBuilder.CreateCompileUnit(SourceLanguage.C, SourcePath, "Kaleidoscope Compiler");
Debug.Assert( cu != null, "Expected non null compile unit" );
Debug.Assert( cu.File != null, "Expected non-null file for compile unit" );
DoubleType = new DebugBasicType( Context.DoubleType, diBuilder, "double", DiTypeKind.Float );
// use this instance and the DIBuilder to visit the AST
ast.Accept( this );
if(AnonymousFunctions.Count > 0)
{
var mainFunction = Module.CreateFunction( "main", Context.GetFunctionType( Context.VoidType ) );
var block = mainFunction.AppendBasicBlock( "entry" );
using var irBuilder = new InstructionBuilder( block );
var printdFunc = Module.CreateFunction( "printd", Context.GetFunctionType( Context.DoubleType, Context.DoubleType ) );
foreach(var anonFunc in AnonymousFunctions)
{
var value = irBuilder.Call( anonFunc );
irBuilder.Call( printdFunc, value );
}
irBuilder.Return();
}
return Module;
}
#endregion
#region ConstantExpression
public override Value? Visit( ConstantExpression constant )
{
ArgumentNullException.ThrowIfNull( constant );
return Context.CreateConstant( constant.Value );
}
#endregion
#region BinaryOperatorExpression
public override Value? Visit( BinaryOperatorExpression binaryOperator )
{
ArgumentNullException.ThrowIfNull( binaryOperator );
EmitLocation( binaryOperator );
switch(binaryOperator.Op)
{
case BuiltInOperatorKind.Less:
{
var tmp = InstructionBuilder.Compare( RealPredicate.UnorderedOrLessThan
, binaryOperator.Left.Accept( this ) ?? throw new CodeGeneratorException( ExpectValidExpr )
, binaryOperator.Right.Accept( this ) ?? throw new CodeGeneratorException( ExpectValidExpr )
).RegisterName( "cmptmp" );
return InstructionBuilder.UIToFPCast( tmp, InstructionBuilder.Context.DoubleType )
.RegisterName( "booltmp" );
}
case BuiltInOperatorKind.Pow:
{
var pow = GetOrDeclareFunction( new Prototype( "llvm.pow.f64", "value", "power" ) );
return InstructionBuilder.Call( pow
, binaryOperator.Left.Accept( this ) ?? throw new CodeGeneratorException( ExpectValidExpr )
, binaryOperator.Right.Accept( this ) ?? throw new CodeGeneratorException( ExpectValidExpr )
).RegisterName( "powtmp" );
}
case BuiltInOperatorKind.Add:
return InstructionBuilder.FAdd( binaryOperator.Left.Accept( this ) ?? throw new CodeGeneratorException( ExpectValidExpr )
, binaryOperator.Right.Accept( this ) ?? throw new CodeGeneratorException( ExpectValidExpr )
).RegisterName( "addtmp" );
case BuiltInOperatorKind.Subtract:
return InstructionBuilder.FSub( binaryOperator.Left.Accept( this ) ?? throw new CodeGeneratorException( ExpectValidExpr )
, binaryOperator.Right.Accept( this ) ?? throw new CodeGeneratorException( ExpectValidExpr )
).RegisterName( "subtmp" );
case BuiltInOperatorKind.Multiply:
return InstructionBuilder.FMul( binaryOperator.Left.Accept( this ) ?? throw new CodeGeneratorException( ExpectValidExpr )
, binaryOperator.Right.Accept( this ) ?? throw new CodeGeneratorException( ExpectValidExpr )
).RegisterName( "multmp" );
case BuiltInOperatorKind.Divide:
return InstructionBuilder.FDiv( binaryOperator.Left.Accept( this ) ?? throw new CodeGeneratorException( ExpectValidExpr )
, binaryOperator.Right.Accept( this ) ?? throw new CodeGeneratorException( ExpectValidExpr )
).RegisterName( "divtmp" );
case BuiltInOperatorKind.Assign:
{
Alloca target = LookupVariable( ( ( VariableReferenceExpression )binaryOperator.Left ).Name );
Value value = binaryOperator.Right.Accept( this ) ?? throw new CodeGeneratorException( ExpectValidExpr );
InstructionBuilder.Store( value, target );
return value;
}
default:
throw new CodeGeneratorException( $"ICE: Invalid binary operator {binaryOperator.Op}" );
}
}
#endregion
#region FunctionCallExpression
public override Value? Visit( FunctionCallExpression functionCall )
{
ArgumentNullException.ThrowIfNull( functionCall );
Debug.Assert( InstructionBuilder is not null, "Internal error Instruction builder should be set in Generate already" );
if(Module is null)
{
throw new InvalidOperationException( "Can't visit a function call without an active module" );
}
string targetName = functionCall.FunctionPrototype.Name;
Function? function;
if(RuntimeState.FunctionDeclarations.TryGetValue( targetName, out Prototype? target ))
{
function = GetOrDeclareFunction( target );
}
else if(!Module.TryGetFunction( targetName, out function ))
{
throw new CodeGeneratorException( $"Definition for function {targetName} not found" );
}
var args = new Value[functionCall.Arguments.Count];
for(int i = 0; i < args.Length; ++i)
{
args[ i ] = functionCall.Arguments[ i ].Accept( this ) ?? throw new CodeGeneratorException( ExpectValidExpr );
}
EmitLocation( functionCall );
return InstructionBuilder.Call( function, args ).RegisterName( "calltmp" );
}
#endregion
#region FunctionDefinition
public override Value? Visit( FunctionDefinition definition )
{
ArgumentNullException.ThrowIfNull( definition );
Debug.Assert( InstructionBuilder is not null, "Internal error Instruction builder should be set in Generate already" );
Debug.Assert( CurrentDIBuilder is not null, "Internal error CurrentDIBuilder should be set in Generate already" );
var function = GetOrDeclareFunction( definition.Signature );
if(!function.IsDeclaration)
{
throw new CodeGeneratorException( $"Function {function.Name} cannot be redefined in the same module" );
}
Debug.Assert( function.DISubProgram != null, "Expected function with non-null DISubProgram" );
LexicalBlocks.Push( function.DISubProgram );
try
{
var entryBlock = function.AppendBasicBlock( "entry" );
InstructionBuilder.PositionAtEnd( entryBlock );
// Unset the location for the prologue emission (leading instructions with no
// location in a function are considered part of the prologue and the debugger
// will run past them when breaking on a function)
EmitLocation( null );
using(NamedValues.EnterScope())
{
foreach(var param in definition.Signature.Parameters)
{
var argSlot = InstructionBuilder.Alloca( function.Context.DoubleType )
.RegisterName( param.Name );
AddDebugInfoForAlloca( argSlot, function, param );
InstructionBuilder.Store( function.Parameters[ param.Index ], argSlot );
NamedValues[ param.Name ] = argSlot;
}
foreach(LocalVariableDeclaration local in definition.LocalVariables)
{
var localSlot = InstructionBuilder.Alloca( function.Context.DoubleType )
.RegisterName( local.Name );
AddDebugInfoForAlloca( localSlot, function, local );
NamedValues[ local.Name ] = localSlot;
}
EmitBranchToNewBlock( "body" );
var funcReturn = definition.Body.Accept( this ) ?? throw new CodeGeneratorException( ExpectValidFunc );
InstructionBuilder.Return( funcReturn );
CurrentDIBuilder.Finish( function.DISubProgram );
function.Verify();
if(definition.IsAnonymous)
{
function.AddAttribute( FunctionAttributeIndex.Function, "alwaysinline" )
.Linkage( Linkage.Private );
AnonymousFunctions.Add( function );
}
return function;
}
}
catch(CodeGeneratorException)
{
function.EraseFromParent();
throw;
}
}
#endregion
#region VariableReferenceExpression
public override Value? Visit( VariableReferenceExpression reference )
{
ArgumentNullException.ThrowIfNull( reference );
var value = LookupVariable( reference.Name );
EmitLocation( reference );
// since the Alloca is created as a non-opaque pointer it is OK to just use the
// ElementType. If full opaque pointer support was used, then the Lookup map
// would need to include the type of the value allocated.
return InstructionBuilder.Load( value.ElementType, value )
.RegisterName( reference.Name );
}
#endregion
#region ConditionalExpression
public override Value? Visit( ConditionalExpression conditionalExpression )
{
ArgumentNullException.ThrowIfNull( conditionalExpression );
Debug.Assert( InstructionBuilder is not null, "Internal error Instruction builder should be set in Generate already" );
var result = LookupVariable( conditionalExpression.ResultVariable.Name );
EmitLocation( conditionalExpression );
var condition = conditionalExpression.Condition.Accept( this );
if(condition == null)
{
return null;
}
EmitLocation( conditionalExpression );
var condBool = InstructionBuilder.Compare( RealPredicate.OrderedAndNotEqual, condition, Context.CreateConstant( 0.0 ) )
.RegisterName( "ifcond" );
var function = InstructionBuilder.InsertFunction ?? throw new InternalCodeGeneratorException( "ICE: expected block that is attached to a function at this point" );
var thenBlock = function.AppendBasicBlock( "then" );
var elseBlock = function.AppendBasicBlock( "else" );
var continueBlock = function.AppendBasicBlock( "ifcont" );
InstructionBuilder.Branch( condBool, thenBlock, elseBlock );
// generate then block instructions
InstructionBuilder.PositionAtEnd( thenBlock );
// InstructionBuilder.InserBlock after this point is !null
Debug.Assert( InstructionBuilder.InsertBlock != null, "expected non-null InsertBlock" );
var thenValue = conditionalExpression.ThenExpression.Accept( this );
if(thenValue == null)
{
return null;
}
InstructionBuilder.Store( thenValue, result );
InstructionBuilder.Branch( continueBlock );
// generate else block
InstructionBuilder.PositionAtEnd( elseBlock );
var elseValue = conditionalExpression.ElseExpression.Accept( this );
if(elseValue == null)
{
return null;
}
InstructionBuilder.Store( elseValue, result );
InstructionBuilder.Branch( continueBlock );
// generate continue block
InstructionBuilder.PositionAtEnd( continueBlock );
// since the Alloca is created as a non-opaque pointer it is OK to just use the
// ElementType. If full opaque pointer support was used, then the Lookup map
// would need to include the type of the value allocated.
return InstructionBuilder.Load( result.ElementType, result )
.RegisterName( "ifresult" );
}
#endregion
#region ForInExpression
public override Value? Visit( ForInExpression forInExpression )
{
ArgumentNullException.ThrowIfNull( forInExpression );
Debug.Assert( InstructionBuilder is not null, "Internal error Instruction builder should be set in Generate already" );
EmitLocation( forInExpression );
var function = InstructionBuilder.InsertFunction ?? throw new InternalCodeGeneratorException( "ICE: Expected block attached to a function at this point" );
string varName = forInExpression.LoopVariable.Name;
Alloca allocaVar = LookupVariable( varName );
// Emit the start code first, without 'variable' in scope.
Value? startVal;
if(forInExpression.LoopVariable.Initializer != null)
{
startVal = forInExpression.LoopVariable.Initializer.Accept( this );
if(startVal is null)
{
return null;
}
}
else
{
startVal = Context.CreateConstant( 0.0 );
}
Debug.Assert( InstructionBuilder.InsertBlock != null, "expected non-null InsertBlock" );
// store the value into allocated location
InstructionBuilder.Store( startVal, allocaVar );
// Make the new basic block for the loop header.
var loopBlock = function.AppendBasicBlock( "loop" );
// Insert an explicit fall through from the current block to the loopBlock.
InstructionBuilder.Branch( loopBlock );
// Start insertion in loopBlock.
InstructionBuilder.PositionAtEnd( loopBlock );
// Within the loop, the variable is defined equal to the PHI node.
// So, push a new scope for it and any values the body might set
using(NamedValues.EnterScope())
{
EmitBranchToNewBlock( "ForInScope" );
// Emit the body of the loop. This, like any other expression, can change the
// current BB. Note that we ignore the value computed by the body, but don't
// allow an error.
if(forInExpression.Body.Accept( this ) == null)
{
return null;
}
Value? stepValue = forInExpression.Step.Accept( this );
if(stepValue == null)
{
return null;
}
// Compute the end condition.
Value? endCondition = forInExpression.Condition.Accept( this );
if(endCondition == null)
{
return null;
}
// since the Alloca is created as a non-opaque pointer it is OK to just use the
// ElementType. If full opaque pointer support was used, then the Lookup map
// would need to include the type of the value allocated.
var curVar = InstructionBuilder.Load( allocaVar.ElementType, allocaVar )
.RegisterName( varName );
var nextVar = InstructionBuilder.FAdd( curVar, stepValue )
.RegisterName( "nextvar" );
InstructionBuilder.Store( nextVar, allocaVar );
// Convert condition to a bool by comparing non-equal to 0.0.
endCondition = InstructionBuilder.Compare( RealPredicate.OrderedAndNotEqual, endCondition, Context.CreateConstant( 0.0 ) )
.RegisterName( "loopcond" );
// Create the "after loop" block and insert it.
var afterBlock = function.AppendBasicBlock( "afterloop" );
// Insert the conditional branch into the end of LoopEndBB.
InstructionBuilder.Branch( endCondition, loopBlock, afterBlock );
InstructionBuilder.PositionAtEnd( afterBlock );
// for expression always returns 0.0 for consistency, there is no 'void'
return Context.DoubleType.GetNullValue();
}
}
#endregion
#region VarInExpression
public override Value? Visit( VarInExpression varInExpression )
{
ArgumentNullException.ThrowIfNull( varInExpression );
EmitLocation( varInExpression );
using(NamedValues.EnterScope())
{
EmitBranchToNewBlock( "VarInScope"u8 );
foreach(var localVar in varInExpression.LocalVariables)
{
EmitLocation( localVar );
Alloca alloca = LookupVariable( localVar.Name );
Value initValue = Context.CreateConstant( 0.0 );
if(localVar.Initializer != null)
{
initValue = localVar.Initializer.Accept( this ) ?? throw new CodeGeneratorException( ExpectValidExpr );
}
InstructionBuilder.Store( initValue, alloca );
}
EmitLocation( varInExpression );
return varInExpression.Body.Accept( this );
}
}
#endregion
private Alloca LookupVariable( LazyEncodedString name )
{
if(!NamedValues.TryGetValue( name, out Alloca? value ))
{
// Source input is validated by the parser and AstBuilder, therefore
// this is the result of an internal error in the generator rather
// then some sort of user error.
throw new CodeGeneratorException( $"ICE: Unknown variable name: {name}" );
}
return value;
}
private void EmitBranchToNewBlock( LazyEncodedString blockName )
{
var newBlock = InstructionBuilder.InsertFunction?.AppendBasicBlock( blockName )
?? throw new InternalCodeGeneratorException("ICE: Expected an insertion block attached to a function at this point" );
InstructionBuilder.Branch( newBlock );
InstructionBuilder.PositionAtEnd( newBlock );
}
#region EmitLocation
private void EmitLocation( IAstNode? node )
{
DILocalScope? scope = null;
if(LexicalBlocks.Count > 0)
{
scope = LexicalBlocks.Peek();
}
else if(InstructionBuilder.InsertFunction != null && InstructionBuilder.InsertFunction.DISubProgram != null)
{
scope = InstructionBuilder.InsertFunction.DISubProgram;
}
DILocation? loc = null;
if(scope != null)
{
loc = new DILocation( InstructionBuilder.Context
, (uint)(node?.Location.Start.Line ?? 0)
, (uint)(node?.Location.Start.Column ?? 0)
, scope
);
}
InstructionBuilder.SetDebugLocation( loc );
}
#endregion
#region GetOrDeclareFunction
// Retrieves a Function for a prototype from the current module if it exists,
// otherwise declares the function and returns the newly declared function.
private Function GetOrDeclareFunction( Prototype prototype )
{
Debug.Assert( CurrentDIBuilder is not null, "Internal error CurrentDIBuilder should be set in Generate already" );
if(Module is null)
{
throw new InvalidOperationException( "ICE: Can't get or declare a function without an active module" );
}
if(Module.TryGetFunction( prototype.Name, out Function? function ))
{
return function;
}
// extern declarations don't get debug information
Function retVal;
if(prototype.IsExtern)
{
var llvmSignature = Context.GetFunctionType( Context.DoubleType, prototype.Parameters.Select( _ => Context.DoubleType ) );
retVal = Module.CreateFunction( prototype.Name, llvmSignature );
}
else
{
var parameters = prototype.Parameters;
// DICompileUnit and File are checked for null in constructor
var debugFile = CurrentDIBuilder.CreateFile( CurrentDIBuilder.CompileUnit!.File!.FileName, CurrentDIBuilder.CompileUnit!.File.Directory );
var signature = Context.CreateFunctionType(CurrentDIBuilder, DoubleType!, prototype.Parameters.Select( _ => DoubleType! ) );
var lastParamLocation = parameters.Count > 0 ? parameters[ parameters.Count - 1 ].Location : prototype.Location;
retVal = Module.CreateFunction( CurrentDIBuilder
, scope: CurrentDIBuilder.CompileUnit
, name: prototype.Name
, linkageName: null
, file: debugFile
, line: (uint)prototype.Location.Start.Line
, signature
, isLocalToUnit: false
, isDefinition: true
, scopeLine: (uint)lastParamLocation.End.Line
, debugFlags: prototype.IsCompilerGenerated ? DebugInfoFlags.Artificial : DebugInfoFlags.Prototyped
, isOptimized: false
);
}
int index = 0;
foreach(var argId in prototype.Parameters)
{
retVal.Parameters[ index ].Name = argId.Name;
++index;
}
return retVal;
}
#endregion
private const string ExpectValidExpr = "Expected a valid expression";
private const string ExpectValidFunc = "Expected a valid function";
#region AddDebugInfoForAlloca
private void AddDebugInfoForAlloca( Alloca argSlot, Function function, ParameterDeclaration param)
{
Debug.Assert( CurrentDIBuilder is not null, "Internal error CurrentDIBuilder should be set in Generate already" );
uint line = ( uint )param.Location.Start.Line;
uint col = ( uint )param.Location.Start.Column;
// Keep compiler happy on null checks by asserting on expectations
// The items were created in this file with all necessary info so
// these properties should never be null.
Debug.Assert( function.DISubProgram != null, "expected function with non-null DISubProgram" );
Debug.Assert( function.DISubProgram.File != null, "expected function with a non-null DISubProgram.File" );
Debug.Assert( InstructionBuilder.InsertBlock != null, "expected Instruction builder with non-null insertion block" );
DILocalVariable debugVar = CurrentDIBuilder.CreateArgument( scope: function.DISubProgram
, name: param.Name
, file: function.DISubProgram.File
, line
, type: DoubleType!
, alwaysPreserve: true
, debugFlags: DebugInfoFlags.None
, argNo: checked(( ushort )( param.Index + 1 )) // Debug index starts at 1!
);
CurrentDIBuilder.InsertDeclare( storage: argSlot
, varInfo: debugVar
, location: new DILocation( Context, line, col, function.DISubProgram )
, insertAtEnd: InstructionBuilder.InsertBlock
);
}
private void AddDebugInfoForAlloca( Alloca argSlot, Function function, LocalVariableDeclaration localVar )
{
Debug.Assert( CurrentDIBuilder is not null, "Internal error CurrentDIBuilder should be set in Generate already" );
uint line = ( uint )localVar.Location.Start.Line;
uint col = ( uint )localVar.Location.Start.Column;
// Keep compiler happy on null checks by asserting on expectations
// The items were created in this file with all necessary info so
// these properties should never be null.
Debug.Assert( function.DISubProgram != null, "expected function with non-null DISubProgram" );
Debug.Assert( function.DISubProgram.File != null, "expected function with non-null DISubProgram.File" );
Debug.Assert( InstructionBuilder.InsertBlock != null, "expected Instruction builder with non-null insertion block" );
DILocalVariable debugVar = CurrentDIBuilder.CreateLocalVariable( scope: function.DISubProgram
, name: localVar.Name
, file: function.DISubProgram.File
, line
, type: DoubleType!
, alwaysPreserve: false
, debugFlags: DebugInfoFlags.None
);
CurrentDIBuilder.InsertDeclare( storage: argSlot
, varInfo: debugVar
, location: new DILocation( Context, line, col, function.DISubProgram )
, insertAtEnd: InstructionBuilder.InsertBlock
);
}
#endregion
#region PrivateMembers
private readonly Module Module;
private IDIBuilder? CurrentDIBuilder;
private readonly DynamicRuntimeState RuntimeState;
private readonly Context Context;
private readonly InstructionBuilder InstructionBuilder;
private readonly ScopeStack<Alloca> NamedValues = new( );
private readonly TargetMachine TargetMachine;
private readonly List<Function> AnonymousFunctions = [];
private DebugBasicType? DoubleType;
private readonly Stack<DILocalScope> LexicalBlocks = [];
private readonly string SourcePath;
#endregion
}
}