{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE TupleSections #-}

-- | Code generation for server executables.
module Futhark.CodeGen.Backends.GenericC.Server
  ( serverDefs,
  )
where

import Data.Bifunctor (first, second)
import Data.FileEmbed
import qualified Data.Map as M
import Futhark.CodeGen.Backends.GenericC.Options
import Futhark.CodeGen.Backends.SimpleRep
import Futhark.CodeGen.ImpCode
import qualified Language.C.Quote.OpenCL as C
import qualified Language.C.Syntax as C

genericOptions :: [Option]
genericOptions :: [Option]
genericOptions =
  [ Option :: String -> Maybe Char -> OptionArgument -> String -> Stm -> Option
Option
      { optionLongName :: String
optionLongName = String
"debugging",
        optionShortName :: Maybe Char
optionShortName = Char -> Maybe Char
forall a. a -> Maybe a
Just Char
'D',
        optionArgument :: OptionArgument
optionArgument = OptionArgument
NoArgument,
        optionDescription :: String
optionDescription = String
"Perform possibly expensive internal correctness checks and verbose logging.",
        optionAction :: Stm
optionAction = [C.cstm|futhark_context_config_set_debugging(cfg, 1);|]
      },
    Option :: String -> Maybe Char -> OptionArgument -> String -> Stm -> Option
Option
      { optionLongName :: String
optionLongName = String
"log",
        optionShortName :: Maybe Char
optionShortName = Char -> Maybe Char
forall a. a -> Maybe a
Just Char
'L',
        optionArgument :: OptionArgument
optionArgument = OptionArgument
NoArgument,
        optionDescription :: String
optionDescription = String
"Print various low-overhead logging information while running.",
        optionAction :: Stm
optionAction = [C.cstm|futhark_context_config_set_logging(cfg, 1);|]
      },
    Option :: String -> Maybe Char -> OptionArgument -> String -> Stm -> Option
Option
      { optionLongName :: String
optionLongName = String
"help",
        optionShortName :: Maybe Char
optionShortName = Char -> Maybe Char
forall a. a -> Maybe a
Just Char
'h',
        optionArgument :: OptionArgument
optionArgument = OptionArgument
NoArgument,
        optionDescription :: String
optionDescription = String
"Print help information and exit.",
        optionAction :: Stm
optionAction =
          [C.cstm|{
                   printf("Usage: %s [OPTION]...\nOptions:\n\n%s\nFor more information, consult the Futhark User's Guide or the man pages.\n",
                          fut_progname, option_descriptions);
                   exit(0);
                  }|]
      }
  ]

typeStructName :: ExternalValue -> String
typeStructName :: ExternalValue -> String
typeStructName (TransparentValue (ScalarValue PrimType
pt Signedness
signed VName
_)) =
  let name :: String
name = Bool -> PrimType -> String
prettySigned (Signedness
signed Signedness -> Signedness -> Bool
forall a. Eq a => a -> a -> Bool
== Signedness
TypeUnsigned) PrimType
pt
   in String
"type_" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
name
typeStructName (TransparentValue (ArrayValue VName
_ Space
_ PrimType
pt Signedness
signed [DimSize]
shape)) =
  let rank :: Int
rank = [DimSize] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [DimSize]
shape
      name :: String
name = PrimType -> Signedness -> Int -> String
arrayName PrimType
pt Signedness
signed Int
rank
   in String
"type_" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
name
typeStructName (OpaqueValue String
name [ValueDesc]
vds) =
  String
"type_" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String -> [ValueDesc] -> String
opaqueName String
name [ValueDesc]
vds

valueDescBoilerplate :: ExternalValue -> (String, (C.Initializer, [C.Definition]))
valueDescBoilerplate :: ExternalValue -> (String, (Initializer, [Definition]))
valueDescBoilerplate ev :: ExternalValue
ev@(TransparentValue (ScalarValue PrimType
pt Signedness
signed VName
_)) =
  let name :: String
name = Bool -> PrimType -> String
prettySigned (Signedness
signed Signedness -> Signedness -> Bool
forall a. Eq a => a -> a -> Bool
== Signedness
TypeUnsigned) PrimType
pt
      type_name :: String
type_name = ExternalValue -> String
typeStructName ExternalValue
ev
   in (String
name, ([C.cinit|&$id:type_name|], [Definition]
forall a. Monoid a => a
mempty))
valueDescBoilerplate ev :: ExternalValue
ev@(TransparentValue (ArrayValue VName
_ Space
_ PrimType
pt Signedness
signed [DimSize]
shape)) =
  let rank :: Int
rank = [DimSize] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [DimSize]
shape
      name :: String
name = PrimType -> Signedness -> Int -> String
arrayName PrimType
pt Signedness
signed Int
rank
      pt_name :: String
pt_name = Bool -> PrimType -> String
prettySigned (Signedness
signed Signedness -> Signedness -> Bool
forall a. Eq a => a -> a -> Bool
== Signedness
TypeUnsigned) PrimType
pt
      pretty_name :: String
pretty_name = [String] -> String
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat (Int -> String -> [String]
forall a. Int -> a -> [a]
replicate Int
rank String
"[]") String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
pt_name
      type_name :: String
type_name = ExternalValue -> String
typeStructName ExternalValue
ev
      aux_name :: String
aux_name = String
type_name String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"_aux"
      info_name :: String
info_name = String
pt_name String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"_info"
      array_new :: String
array_new = String
"futhark_new_" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
name
      array_new_wrap :: String
array_new_wrap = String
"futhark_new_" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
name String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"_wrap"
      array_free :: String
array_free = String
"futhark_free_" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
name
      array_shape :: String
array_shape = String
"futhark_shape_" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
name
      array_values :: String
array_values = String
"futhark_values_" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
name
      shape_args :: [Exp]
shape_args = [[C.cexp|shape[$int:i]|] | Int
i <- [Int
0 .. Int
rank Int -> Int -> Int
forall a. Num a => a -> a -> a
-Int
1]]
   in ( String
name,
        ( [C.cinit|&$id:type_name|],
          [C.cunit|
              void* $id:array_new_wrap(struct futhark_context *ctx,
                                       const void* p,
                                       const typename int64_t* shape) {
                return $id:array_new(ctx, p, $args:shape_args);
              }
              struct array_aux $id:aux_name = {
                .name = $string:pretty_name,
                .rank = $int:rank,
                .info = &$id:info_name,
                .new = (typename array_new_fn)$id:array_new_wrap,
                .free = (typename array_free_fn)$id:array_free,
                .shape = (typename array_shape_fn)$id:array_shape,
                .values = (typename array_values_fn)$id:array_values
              };
              struct type $id:type_name = {
                .name = $string:pretty_name,
                .restore = (typename restore_fn)restore_array,
                .store = (typename store_fn)store_array,
                .free = (typename free_fn)free_array,
                .aux = &$id:aux_name
              };|]
        )
      )
valueDescBoilerplate ev :: ExternalValue
ev@(OpaqueValue String
name [ValueDesc]
vds) =
  let type_name :: String
type_name = ExternalValue -> String
typeStructName ExternalValue
ev
      aux_name :: String
aux_name = String
type_name String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"_aux"
      opaque_free :: String
opaque_free = String
"futhark_free_" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String -> [ValueDesc] -> String
opaqueName String
name [ValueDesc]
vds
      opaque_store :: String
opaque_store = String
"futhark_store_" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String -> [ValueDesc] -> String
opaqueName String
name [ValueDesc]
vds
      opaque_restore :: String
opaque_restore = String
"futhark_restore_" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String -> [ValueDesc] -> String
opaqueName String
name [ValueDesc]
vds
   in ( String
name,
        ( [C.cinit|&$id:type_name|],
          [C.cunit|
              struct opaque_aux $id:aux_name = {
                .free = (typename opaque_free_fn)$id:opaque_free
              };
              struct type $id:type_name = {
                .name = $string:name,
                .restore = (typename restore_fn)$id:opaque_store,
                .store = (typename store_fn)$id:opaque_restore,
                .free = (typename free_fn)free_opaque,
                .aux = &$id:aux_name
              };|]
        )
      )

functionExternalValues :: Function a -> [ExternalValue]
functionExternalValues :: Function a -> [ExternalValue]
functionExternalValues Function a
fun = Function a -> [ExternalValue]
forall a. FunctionT a -> [ExternalValue]
functionResult Function a
fun [ExternalValue] -> [ExternalValue] -> [ExternalValue]
forall a. [a] -> [a] -> [a]
++ Function a -> [ExternalValue]
forall a. FunctionT a -> [ExternalValue]
functionArgs Function a
fun

entryTypeBoilerplate :: Functions a -> ([C.Initializer], [C.Definition])
entryTypeBoilerplate :: Functions a -> ([Initializer], [Definition])
entryTypeBoilerplate (Functions [(Name, Function a)]
funs) =
  ([[Definition]] -> [Definition])
-> ([Initializer], [[Definition]]) -> ([Initializer], [Definition])
forall (p :: * -> * -> *) b c a.
Bifunctor p =>
(b -> c) -> p a b -> p a c
second [[Definition]] -> [Definition]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat (([Initializer], [[Definition]]) -> ([Initializer], [Definition]))
-> ([Initializer], [[Definition]]) -> ([Initializer], [Definition])
forall a b. (a -> b) -> a -> b
$
    [(Initializer, [Definition])] -> ([Initializer], [[Definition]])
forall a b. [(a, b)] -> ([a], [b])
unzip ([(Initializer, [Definition])] -> ([Initializer], [[Definition]]))
-> [(Initializer, [Definition])] -> ([Initializer], [[Definition]])
forall a b. (a -> b) -> a -> b
$
      Map String (Initializer, [Definition])
-> [(Initializer, [Definition])]
forall k a. Map k a -> [a]
M.elems (Map String (Initializer, [Definition])
 -> [(Initializer, [Definition])])
-> Map String (Initializer, [Definition])
-> [(Initializer, [Definition])]
forall a b. (a -> b) -> a -> b
$
        [(String, (Initializer, [Definition]))]
-> Map String (Initializer, [Definition])
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList ([(String, (Initializer, [Definition]))]
 -> Map String (Initializer, [Definition]))
-> [(String, (Initializer, [Definition]))]
-> Map String (Initializer, [Definition])
forall a b. (a -> b) -> a -> b
$
          (ExternalValue -> (String, (Initializer, [Definition])))
-> [ExternalValue] -> [(String, (Initializer, [Definition]))]
forall a b. (a -> b) -> [a] -> [b]
map ExternalValue -> (String, (Initializer, [Definition]))
valueDescBoilerplate ([ExternalValue] -> [(String, (Initializer, [Definition]))])
-> [ExternalValue] -> [(String, (Initializer, [Definition]))]
forall a b. (a -> b) -> a -> b
$
            ((Name, Function a) -> [ExternalValue])
-> [(Name, Function a)] -> [ExternalValue]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (Function a -> [ExternalValue]
forall a. FunctionT a -> [ExternalValue]
functionExternalValues (Function a -> [ExternalValue])
-> ((Name, Function a) -> Function a)
-> (Name, Function a)
-> [ExternalValue]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Name, Function a) -> Function a
forall a b. (a, b) -> b
snd) ([(Name, Function a)] -> [ExternalValue])
-> [(Name, Function a)] -> [ExternalValue]
forall a b. (a -> b) -> a -> b
$
              ((Name, Function a) -> Bool)
-> [(Name, Function a)] -> [(Name, Function a)]
forall a. (a -> Bool) -> [a] -> [a]
filter (Function a -> Bool
forall a. FunctionT a -> Bool
functionEntry (Function a -> Bool)
-> ((Name, Function a) -> Function a) -> (Name, Function a) -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Name, Function a) -> Function a
forall a b. (a, b) -> b
snd) [(Name, Function a)]
funs

oneEntryBoilerplate :: (Name, Function a) -> ([C.Definition], C.Initializer)
oneEntryBoilerplate :: (Name, Function a) -> ([Definition], Initializer)
oneEntryBoilerplate (Name
name, Function a
fun) =
  let entry_f :: String
entry_f = String
"futhark_entry_" String -> String -> String
forall a. [a] -> [a] -> [a]
++ Name -> String
forall a. Pretty a => a -> String
pretty Name
name
      call_f :: String
call_f = String
"call_" String -> String -> String
forall a. [a] -> [a] -> [a]
++ Name -> String
forall a. Pretty a => a -> String
pretty Name
name
      out_types :: [ExternalValue]
out_types = Function a -> [ExternalValue]
forall a. FunctionT a -> [ExternalValue]
functionResult Function a
fun
      in_types :: [ExternalValue]
in_types = Function a -> [ExternalValue]
forall a. FunctionT a -> [ExternalValue]
functionArgs Function a
fun
      out_types_name :: String
out_types_name = Name -> String
forall a. Pretty a => a -> String
pretty Name
name String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"_out_types"
      in_types_name :: String
in_types_name = Name -> String
forall a. Pretty a => a -> String
pretty Name
name String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"_in_types"
      ([BlockItem]
out_items, [Exp]
out_args)
        | [ExternalValue] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [ExternalValue]
out_types = ([C.citems|(void)outs;|], [Exp]
forall a. Monoid a => a
mempty)
        | Bool
otherwise = [(BlockItem, Exp)] -> ([BlockItem], [Exp])
forall a b. [(a, b)] -> ([a], [b])
unzip ([(BlockItem, Exp)] -> ([BlockItem], [Exp]))
-> [(BlockItem, Exp)] -> ([BlockItem], [Exp])
forall a b. (a -> b) -> a -> b
$ (Int -> ExternalValue -> (BlockItem, Exp))
-> [Int] -> [ExternalValue] -> [(BlockItem, Exp)]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith Int -> ExternalValue -> (BlockItem, Exp)
loadOut [Int
0 ..] [ExternalValue]
out_types
      ([BlockItem]
in_items, [Exp]
in_args)
        | [ExternalValue] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [ExternalValue]
in_types = ([C.citems|(void)ins;|], [Exp]
forall a. Monoid a => a
mempty)
        | Bool
otherwise = [(BlockItem, Exp)] -> ([BlockItem], [Exp])
forall a b. [(a, b)] -> ([a], [b])
unzip ([(BlockItem, Exp)] -> ([BlockItem], [Exp]))
-> [(BlockItem, Exp)] -> ([BlockItem], [Exp])
forall a b. (a -> b) -> a -> b
$ (Int -> ExternalValue -> (BlockItem, Exp))
-> [Int] -> [ExternalValue] -> [(BlockItem, Exp)]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith Int -> ExternalValue -> (BlockItem, Exp)
loadIn [Int
0 ..] [ExternalValue]
in_types
   in ( [C.cunit|
                struct type* $id:out_types_name[] = {
                  $inits:(map typeStructInit out_types),
                  NULL
                };
                struct type* $id:in_types_name[] = {
                  $inits:(map typeStructInit in_types),
                  NULL
                };
                int $id:call_f(struct futhark_context *ctx, void **outs, void **ins) {
                  $items:out_items
                  $items:in_items
                  return $id:entry_f(ctx, $args:out_args, $args:in_args);
                }
                |],
        [C.cinit|{
            .name = $string:(pretty name),
            .f = $id:call_f,
            .in_types = $id:in_types_name,
            .out_types = $id:out_types_name
            }|]
      )
  where
    typeStructInit :: ExternalValue -> Initializer
typeStructInit ExternalValue
t = [C.cinit|&$id:(typeStructName t)|]

    loadOut :: Int -> ExternalValue -> (BlockItem, Exp)
loadOut Int
i ExternalValue
ev =
      let v :: String
v = String
"out" String -> String -> String
forall a. [a] -> [a] -> [a]
++ Int -> String
forall a. Show a => a -> String
show (Int
i :: Int)
       in ( [C.citem|$ty:(externalValueType ev) *$id:v = outs[$int:i];|],
            [C.cexp|$id:v|]
          )
    loadIn :: Int -> ExternalValue -> (BlockItem, Exp)
loadIn Int
i ExternalValue
ev =
      let v :: String
v = String
"in" String -> String -> String
forall a. [a] -> [a] -> [a]
++ Int -> String
forall a. Show a => a -> String
show (Int
i :: Int)
          evt :: Type
evt = ExternalValue -> Type
externalValueType ExternalValue
ev
       in ( [C.citem|$ty:evt $id:v = *($ty:evt*)ins[$int:i];|],
            [C.cexp|$id:v|]
          )

entryBoilerplate :: Functions a -> ([C.Definition], [C.Initializer])
entryBoilerplate :: Functions a -> ([Definition], [Initializer])
entryBoilerplate (Functions [(Name, Function a)]
funs) =
  ([[Definition]] -> [Definition])
-> ([[Definition]], [Initializer]) -> ([Definition], [Initializer])
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first [[Definition]] -> [Definition]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat (([[Definition]], [Initializer]) -> ([Definition], [Initializer]))
-> ([[Definition]], [Initializer]) -> ([Definition], [Initializer])
forall a b. (a -> b) -> a -> b
$ [([Definition], Initializer)] -> ([[Definition]], [Initializer])
forall a b. [(a, b)] -> ([a], [b])
unzip ([([Definition], Initializer)] -> ([[Definition]], [Initializer]))
-> [([Definition], Initializer)] -> ([[Definition]], [Initializer])
forall a b. (a -> b) -> a -> b
$ ((Name, Function a) -> ([Definition], Initializer))
-> [(Name, Function a)] -> [([Definition], Initializer)]
forall a b. (a -> b) -> [a] -> [b]
map (Name, Function a) -> ([Definition], Initializer)
forall a. (Name, Function a) -> ([Definition], Initializer)
oneEntryBoilerplate ([(Name, Function a)] -> [([Definition], Initializer)])
-> [(Name, Function a)] -> [([Definition], Initializer)]
forall a b. (a -> b) -> a -> b
$ ((Name, Function a) -> Bool)
-> [(Name, Function a)] -> [(Name, Function a)]
forall a. (a -> Bool) -> [a] -> [a]
filter (Function a -> Bool
forall a. FunctionT a -> Bool
functionEntry (Function a -> Bool)
-> ((Name, Function a) -> Function a) -> (Name, Function a) -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Name, Function a) -> Function a
forall a b. (a, b) -> b
snd) [(Name, Function a)]
funs

mkBoilerplate ::
  Functions a ->
  ([C.Definition], [C.Initializer], [C.Initializer])
mkBoilerplate :: Functions a -> ([Definition], [Initializer], [Initializer])
mkBoilerplate Functions a
funs =
  let ([Initializer]
type_inits, [Definition]
type_defs) = Functions a -> ([Initializer], [Definition])
forall a. Functions a -> ([Initializer], [Definition])
entryTypeBoilerplate Functions a
funs
      ([Definition]
entry_defs, [Initializer]
entry_inits) = Functions a -> ([Definition], [Initializer])
forall a. Functions a -> ([Definition], [Initializer])
entryBoilerplate Functions a
funs
   in ([Definition]
type_defs [Definition] -> [Definition] -> [Definition]
forall a. [a] -> [a] -> [a]
++ [Definition]
entry_defs, [Initializer]
type_inits, [Initializer]
entry_inits)

{-# NOINLINE serverDefs #-}

-- | Generate Futhark server executable code.
serverDefs :: [Option] -> Functions a -> [C.Definition]
serverDefs :: [Option] -> Functions a -> [Definition]
serverDefs [Option]
options Functions a
funs =
  let server_h :: String
server_h = $(embedStringFile "rts/c/server.h")
      values_h :: String
values_h = $(embedStringFile "rts/c/values.h")
      tuning_h :: String
tuning_h = $(embedStringFile "rts/c/tuning.h")
      option_parser :: Func
option_parser =
        String -> [Option] -> Func
generateOptionParser String
"parse_options" ([Option] -> Func) -> [Option] -> Func
forall a b. (a -> b) -> a -> b
$ [Option]
genericOptions [Option] -> [Option] -> [Option]
forall a. [a] -> [a] -> [a]
++ [Option]
options
      ([Definition]
boilerplate_defs, [Initializer]
type_inits, [Initializer]
entry_point_inits) =
        Functions a -> ([Definition], [Initializer], [Initializer])
forall a.
Functions a -> ([Definition], [Initializer], [Initializer])
mkBoilerplate Functions a
funs
   in [C.cunit|
$esc:("#include <getopt.h>")
$esc:("#include <ctype.h>")
$esc:("#include <inttypes.h>")

// If the entry point is NULL, the program will terminate after doing initialisation and such.  It is not used for anything else in server mode.
static const char *entry_point = "main";

$esc:values_h
$esc:server_h
$esc:tuning_h

$edecls:boilerplate_defs

struct type* types[] = {
  $inits:type_inits,
  NULL
};

struct entry_point entry_points[] = {
  $inits:entry_point_inits,
  { .name = NULL }
};

struct futhark_prog prog = {
  .types = types,
  .entry_points = entry_points
};

$func:option_parser

int main(int argc, char** argv) {
  fut_progname = argv[0];

  struct futhark_context_config *cfg = futhark_context_config_new();
  assert(cfg != NULL);

  int parsed_options = parse_options(cfg, argc, argv);
  argc -= parsed_options;
  argv += parsed_options;

  if (argc != 0) {
    futhark_panic(1, "Excess non-option: %s\n", argv[0]);
  }

  struct futhark_context *ctx = futhark_context_new(cfg);
  assert (ctx != NULL);

  futhark_context_set_logging_file(ctx, stdout);

  char* error = futhark_context_get_error(ctx);
  if (error != NULL) {
    futhark_panic(1, "Error during context initialisation:\n%s", error);
  }

  if (entry_point != NULL) {
    run_server(&prog, ctx);
  }

  futhark_context_free(ctx);
  futhark_context_config_free(cfg);
}
|]