Skip to content

Commit

Permalink
add: generate LLVM foreign function declarations
Browse files Browse the repository at this point in the history
  • Loading branch information
Jabolol committed Jan 10, 2025
1 parent 1bb2fa1 commit a3191b7
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions lib/Codegen/Codegen.hs
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ codegen program =
generateGlobal :: (MonadCodegen m) => AT.Expr -> m ()
generateGlobal expr = case expr of
AT.Function {} -> CM.void $ generateFunction expr
AT.ForeignFunction {} -> CM.void $ generateForeignFunction expr
_ -> E.throwError $ CodegenError (U.getLoc expr) $ UnsupportedTopLevel expr

-- | Generate LLVM code for an expression.
Expand All @@ -164,6 +165,7 @@ instance ExprGen AT.Expr where
AT.Lit {} -> generateLiteral expr
AT.Var {} -> generateVar expr
AT.Function {} -> generateFunction expr
AT.ForeignFunction {} -> generateForeignFunction expr
AT.Declaration {} -> generateDeclaration expr
AT.If {} -> generateIf expr
AT.Block {} -> generateBlock expr
Expand Down Expand Up @@ -357,6 +359,20 @@ generateFunction (AT.Function _ name (AT.TFunction ret params False) paramNames
generateFunction expr =
E.throwError $ CodegenError (U.getLoc expr) $ UnsupportedDefinition expr

-- | Generate LLVM code for foreign function definitions.
generateForeignFunction :: (MonadCodegen m) => AT.Expr -> m AST.Operand
generateForeignFunction (AT.ForeignFunction _ name (AT.TFunction ret params False)) = do
let funcType = T.ptr $ T.FunctionType (toLLVM ret) (map toLLVM params) False
funcName = AST.Name $ U.stringToByteString name

_ <- M.extern funcName (map toLLVM params) (toLLVM ret)

addGlobalVar name $ AST.ConstantOperand $ C.GlobalReference funcType funcName

pure $ AST.ConstantOperand $ C.GlobalReference funcType funcName
generateForeignFunction expr =
E.throwError $ CodegenError (U.getLoc expr) $ UnsupportedDefinition expr

-- | Generate LLVM code for declarations.
generateDeclaration :: (MonadCodegen m) => AT.Expr -> m AST.Operand
generateDeclaration (AT.Declaration _ name typ mInitExpr) = do
Expand Down

0 comments on commit a3191b7

Please # to comment.