@@ -348,7 +348,9 @@ auto Codegen::DeclarationVisitor::operator()(FunctionDefinitionAST* ast)
348
348
349
349
// Add the function body.
350
350
auto entryBlock = gen.builder_ .createBlock (&func.getBody ());
351
- for (const auto & input : func.getFunctionType ().getInputs ()) {
351
+ auto inputs = func.getFunctionType ().getInputs ();
352
+
353
+ for (const auto & input : inputs) {
352
354
entryBlock->addArgument (input, loc);
353
355
}
354
356
@@ -370,17 +372,36 @@ auto Codegen::DeclarationVisitor::operator()(FunctionDefinitionAST* ast)
370
372
371
373
// function state
372
374
std::swap (gen.function_ , func);
375
+ std::swap (gen.entryBlock_ , entryBlock);
373
376
std::swap (gen.exitBlock_ , exitBlock);
374
377
std::swap (gen.exitValue_ , exitValue);
375
378
std::swap (gen.locals_ , locals);
376
379
380
+ mlir::Value thisValue;
381
+
382
+ // if this is a non static member function, we need to allocate the `this`
383
+ if (!functionSymbol->isStatic () &&
384
+ functionSymbol->enclosingSymbol ()->isClass ()) {
385
+ auto classSymbol =
386
+ symbol_cast<ClassSymbol>(functionSymbol->enclosingSymbol ());
387
+
388
+ auto thisType = gen.convertType (classSymbol->type ());
389
+ auto ptrType = gen.builder_ .getType <mlir::cxx::PointerType>(thisType);
390
+
391
+ thisValue = gen.newTemp (classSymbol->type (), ast->firstSourceLocation ());
392
+
393
+ // store the `this` pointer in the entry block
394
+ gen.builder_ .create <mlir::cxx::StoreOp>(
395
+ loc, gen.entryBlock_ ->getArgument (0 ), thisValue);
396
+ }
397
+
377
398
FunctionParametersSymbol* params = nullptr ;
378
399
for (auto member : ast->symbol ->scope ()->symbols ()) {
379
400
params = symbol_cast<FunctionParametersSymbol>(member);
380
401
if (!params) continue ;
381
402
382
403
int argc = 0 ;
383
- auto args = entryBlock ->getArguments ();
404
+ auto args = gen. entryBlock_ ->getArguments ();
384
405
for (auto param : params->scope ()->symbols ()) {
385
406
auto arg = symbol_cast<ParameterSymbol>(param);
386
407
if (!arg) continue ;
@@ -399,6 +420,8 @@ auto Codegen::DeclarationVisitor::operator()(FunctionDefinitionAST* ast)
399
420
}
400
421
}
401
422
423
+ std::swap (gen.thisValue_ , thisValue);
424
+
402
425
allocateLocals (functionSymbol);
403
426
404
427
// generate code for the function body
@@ -428,7 +451,10 @@ auto Codegen::DeclarationVisitor::operator()(FunctionDefinitionAST* ast)
428
451
}
429
452
430
453
// restore the state
454
+ std::swap (gen.thisValue_ , thisValue);
455
+
431
456
std::swap (gen.function_ , func);
457
+ std::swap (gen.entryBlock_ , entryBlock);
432
458
std::swap (gen.exitBlock_ , exitBlock);
433
459
std::swap (gen.exitValue_ , exitValue);
434
460
std::swap (gen.locals_ , locals);
0 commit comments