-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | An optimising compiler for a functional, array-oriented language. -- -- See the website at https://futhark-lang.org @package futhark @version 0.7.4 -- | This module defines a generator for getopt_long based command -- line argument parsing. Each option is associated with arbitrary C code -- that will perform side effects, usually by setting some global -- variables. module Futhark.CodeGen.Backends.GenericC.Options -- | Specification if a single command line option. The option must have a -- long name, and may also have a short name. -- -- In the action, the option argument (if any) is stored as in the -- char*-typed variable optarg. data Option Option :: String -> Maybe Char -> OptionArgument -> Stm -> Option [optionLongName] :: Option -> String [optionShortName] :: Option -> Maybe Char [optionArgument] :: Option -> OptionArgument [optionAction] :: Option -> Stm -- | Whether an option accepts an argument. data OptionArgument NoArgument :: OptionArgument RequiredArgument :: OptionArgument OptionalArgument :: OptionArgument -- | Generate an option parser as a function of the given name, that -- accepts the given command line options. The result is a function that -- should be called with argc and argv. The function -- returns the number of argv elements that have been processed. -- -- If option parsing fails for any reason, the entire process will -- terminate with error code 1. generateOptionParser :: String -> [Option] -> Func module Futhark.CodeGen.Backends.GenericCSharp.Definitions csFunctions :: String csReader :: String csMemory :: String csMemoryOpenCL :: String csScalar :: String csPanic :: String csExceptions :: String csOpenCL :: String module Futhark.CodeGen.Backends.GenericPython.Definitions pyFunctions :: String pyUtility :: String pyValues :: String pyPanic :: String module Futhark.CodeGen.OpenCL.Kernels -- | A heuristic for setting the default value for something. data SizeHeuristic SizeHeuristic :: String -> DeviceType -> WhichSize -> HeuristicValue -> SizeHeuristic [platformName] :: SizeHeuristic -> String [deviceType] :: SizeHeuristic -> DeviceType [heuristicSize] :: SizeHeuristic -> WhichSize [heuristicValue] :: SizeHeuristic -> HeuristicValue -- | The type of OpenCL device that this heuristic applies to. data DeviceType DeviceCPU :: DeviceType DeviceGPU :: DeviceType -- | A size that can be assigned a default. data WhichSize LockstepWidth :: WhichSize NumGroups :: WhichSize GroupSize :: WhichSize TileSize :: WhichSize -- | The value supplies by a heuristic can be a constant, or inferred from -- some device information. data HeuristicValue HeuristicConst :: Int -> HeuristicValue HeuristicDeviceInfo :: String -> HeuristicValue -- | All of our heuristics. sizeHeuristicsTable :: [SizeHeuristic] -- | mapTranspose name elem_type transpose_type Generate a -- transpose kernel with requested name for elements of type -- elem_type. There are special support to handle input arrays -- with low width or low height, which can be indicated by -- transpose_type. -- -- Normally when transposing a [2][n] array we would use a -- FUT_BLOCK_DIM x FUT_BLOCK_DIM group to process a -- [2][FUT_BLOCK_DIM] slice of the input array. This would mean -- that many of the threads in a group would be inactive. We try to -- remedy this by using a special kernel that will process a larger part -- of the input, by using more complex indexing. In our example, we could -- use all threads in a group if we are processing -- (2/FUT_BLOCK_DIM) as large a slice of each rows per group. -- The variable mulx contains this factor for the kernel to -- handle input arrays with low height. -- -- See issue #308 on GitHub for more details. mapTranspose :: ToIdent a => a -> Type -> TransposeType -> Func -- | Which form of transposition to generate code for. data TransposeType TransposeNormal :: TransposeType TransposeLowWidth :: TransposeType TransposeLowHeight :: TransposeType -- | For small arrays that do not benefit from coalescing. TransposeSmall :: TransposeType instance GHC.Show.Show Futhark.CodeGen.OpenCL.Kernels.TransposeType instance GHC.Classes.Ord Futhark.CodeGen.OpenCL.Kernels.TransposeType instance GHC.Classes.Eq Futhark.CodeGen.OpenCL.Kernels.TransposeType -- | Futhark error definitions. module Futhark.Error data CompilerError -- | An error that happened due to something the user did, such as provide -- incorrect code or options. ExternalError :: Text -> CompilerError -- | An internal compiler error. The second text is extra data for -- debugging, which can be written to a file. InternalError :: Text -> Text -> ErrorClass -> CompilerError -- | There are two classes of internal errors: actual bugs, and -- implementation limitations. The latter are already known and need not -- be reported. data ErrorClass CompilerBug :: ErrorClass CompilerLimitation :: ErrorClass externalError :: MonadError CompilerError m => Text -> m a externalErrorS :: MonadError CompilerError m => String -> m a -- | An error that is not the users fault, but a bug (or limitation) in the -- compiler. Compiler passes should only ever report this error - any -- problems after the type checker are *our* fault, not the users. data InternalError internalError :: MonadError CompilerError m => InternalError -> Text -> m a compilerBug :: MonadError InternalError m => Text -> m a compilerBugS :: MonadError InternalError m => String -> m a compilerLimitation :: MonadError InternalError m => Text -> m a compilerLimitationS :: MonadError InternalError m => String -> m a instance GHC.Show.Show Futhark.Error.ErrorClass instance GHC.Classes.Ord Futhark.Error.ErrorClass instance GHC.Classes.Eq Futhark.Error.ErrorClass instance GHC.Show.Show Futhark.Error.CompilerError -- | Types (and a few other simple definitions) for futhark-pkg. module Futhark.Pkg.Types -- | A package path is a unique identifier for a package, for example -- github.comuserfoo. type PkgPath = Text -- | Turn a package path (which always uses forward slashes) into a file -- path in the local file system (which might use different slashes). pkgPathFilePath :: PkgPath -> FilePath -- | The dependencies of a (revision of a) package is a mapping from -- package paths to minimum versions (and an optional hash pinning). newtype PkgRevDeps PkgRevDeps :: Map PkgPath (SemVer, Maybe Text) -> PkgRevDeps -- | Convert a SemVer back to its textual representation. prettySemVer :: SemVer -> Text -- | An (Ideal) version number that conforms to Semantic Versioning. This -- is a prescriptive parser, meaning it follows the SemVer -- standard. -- -- Legal semvers are of the form: MAJOR.MINOR.PATCH-PREREL+META -- -- Example: 1.2.3-r1+commithash -- -- Extra Rules: -- --
-- > let loc = Loc (Pos "filename" 3 5 7) (Pos "filename" 5 7 9) -- > in putStrLn $ prettyPragma 80 $ srcloc loc <> text "foo" </> text "bar" </> text "baz" ---- -- will be printed as -- --
-- foo -- #line 3 "filename" -- bar -- baz --prettyPragma :: Int -> Doc -> String -- | Render and display a document with #line pragmas. prettyPragmaS :: Int -> Doc -> ShowS -- | Display a rendered document with #line pragmas. displayPragmaS :: RDoc -> ShowS -- | Render and convert a document to a Doc compactly. prettyCompact :: Doc -> String -- | Render and display a document compactly. prettyCompactS :: Doc -> ShowS -- | Render and display a document. prettyS :: Int -> Doc -> ShowS -- | Display a rendered document. displayS :: RDoc -> ShowS -- | Render a document without indentation on infinitely long lines. Since -- no 'pretty' printing is involved, this renderer is fast. The resulting -- output contains fewer characters. renderCompact :: Doc -> RDoc -- | Render a document given a maximum width. render :: Int -> Doc -> RDoc -- | Equivalent of error, but with a document instead of a string. errordoc :: () => Doc -> a -- | Equivalent of fail, but with a document instead of a string. faildoc :: Monad m => Doc -> m a -- | The document fillbreak i d renders document -- d, appending spaces until the width is equal -- to i. If the width of d is already greater than -- i, the nesting level is increased by i and a -- line is appended. fillbreak :: Int -> Doc -> Doc -- | The document fill i d renders document x, -- appending spaces until the width is equal to i. If -- the width of d is already greater than i, nothing is -- appended. fill :: Int -> Doc -> Doc -- | The document width d f is produced by concatenating -- d with the result of calling f with the width of the -- document d. width :: Doc -> (Int -> Doc) -> Doc -- | The document column f is produced by calling -- f with the current nesting level. nesting :: (Int -> Doc) -> Doc -- | The document column f is produced by calling -- f with the current column. column :: (Int -> Doc) -> Doc -- | The document nest i d renders the document d -- with the current indentation level increased by i. nest :: Int -> Doc -> Doc -- | The document indent i d renders d with a -- nesting level set to the current column plus i, -- including the first line. indent :: Int -> Doc -> Doc -- | The document hang i d renders d with a -- nesting level set to the current column plus i, not -- including the first line. hang :: Int -> Doc -> Doc -- | The document align d renders d with a nesting -- level set to the current column. align :: Doc -> Doc -- | The document list ds separates ds with commas -- and encloses them with brackets. list :: [Doc] -> Doc -- | The document tuple ds separates ds with -- commas and encloses them with parentheses. tuple :: [Doc] -> Doc -- | The document enclosesep l r p ds separates ds -- with the punctuation p and encloses the result using -- l and r. When wrapped, punctuation appears at the -- end of the line. The enclosed portion of the document is aligned one -- column to the right of the opening document. -- --
-- > ws = map text (words "The quick brown fox jumps over the lazy dog") -- > test = pretty 15 (enclosesep lparen rparen comma ws) ---- -- will be layed out as: -- --
-- (The, quick, -- brown, fox, -- jumps, over, -- the, lazy, -- dog) --enclosesep :: Doc -> Doc -> Doc -> [Doc] -> Doc -- | The document semisep ds semicolon-space separates -- ds, aligning the resulting document to the current nesting -- level. semisep :: [Doc] -> Doc -- | The document commasep ds comma-space separates -- ds, aligning the resulting document to the current nesting -- level. commasep :: [Doc] -> Doc -- | The document punctuate p ds obeys the law: -- --
-- punctuate p [d1, d2, ..., dn] = [d1 <> p, d2 <> p, ..., dn] --punctuate :: Doc -> [Doc] -> [Doc] -- | The document sep ds concatenates the documents -- ds with the space document as long as there is room, -- and uses line when there isn't. sep :: [Doc] -> Doc -- | The document cat ds concatenates the documents -- ds with the empty document as long as there is room, -- and uses line when there isn't. cat :: [Doc] -> Doc -- | The document stack ds concatenates the documents -- ds with line. stack :: [Doc] -> Doc -- | The document spread ds concatenates the documents -- ds with space. spread :: [Doc] -> Doc -- | The document folddoc f ds obeys the laws: -- -- folddoc :: (Doc -> Doc -> Doc) -> [Doc] -> Doc -- | The document parensIf p d encloses the document -- d in parenthesis if p is True, and -- otherwise yields just d. parensIf :: Bool -> Doc -> Doc -- | The document parens d encloses the aligned document -- d in (...). parens :: Doc -> Doc -- | The document brackets d encloses the aligned document -- d in [...]. brackets :: Doc -> Doc -- | The document braces d encloses the aligned document -- d in {...}. braces :: Doc -> Doc -- | The document backquotes d encloses the aligned -- document d in `...`. backquotes :: Doc -> Doc -- | The document angles d encloses the aligned document -- d in <...>. angles :: Doc -> Doc -- | The document dquotes d encloses the aligned document -- d in "...". dquotes :: Doc -> Doc -- | The document squotes d encloses the alinged document -- d in '...'. squotes :: Doc -> Doc -- | The document enclose l r d encloses the document -- d between the documents l and r using -- <>. It obeys the law -- --
-- enclose l r d = l <> d <> r --enclose :: Doc -> Doc -> Doc -> Doc -- | The document flatten d will flatten d to -- one line. flatten :: Doc -> Doc -- | The document group d will flatten d to -- one line if there is room for it, otherwise the original -- d. group :: Doc -> Doc -- | Provide alternative layouts of the same content. Invariant: both -- arguments must flatten to the same document. (<|>) :: Doc -> Doc -> Doc infixl 3 <|> -- | Concatenates two documents with a softbreak in between. (/>) :: Doc -> Doc -> Doc infixr 5 /> -- | Concatenates two documents with a softline in between, with -- identity empty. (<+/>) :: Doc -> Doc -> Doc infixr 5 <+/> -- | Concatenates two documents with a line in between, with -- identity empty. (>) :: Doc -> Doc -> Doc infixr 5 > -- | Concatenates two documents with a space in between, with -- identity empty. (<+>) :: Doc -> Doc -> Doc infixr 6 <+> -- | Becomes empty if there is room, otherwise line. softbreak :: Doc -- | Becomes space if there is room, otherwise line. -- --
-- pretty 11 $ text "foo" <+/> text "bar" <+/> text "baz" =="foo bar baz" -- pretty 7 $ text "foo" <+/> text "bar" <+/> text "baz" == "foo bar\nbaz" -- pretty 6 $ text "foo" <+/> text "bar" <+/> text "baz" == "foo\nbar\nbaz" --softline :: Doc -- | The document line advances to the next line and -- indents to the current indentation level. When undone by group, -- it behaves like space. line :: Doc -- | The document srcloc x tags the current line with -- locOf x. Only shown when running prettyPragma -- and friends. srcloc :: Located a => a -> Doc -- | The empty document. empty :: Doc -- | The document rparen consists of a right brace, ")". rparen :: Doc -- | The document lparen consists of a right brace, "(". lparen :: Doc -- | The document rbracket consists of a right brace, -- "]". rbracket :: Doc -- | The document lbracket consists of a right brace, -- "[". lbracket :: Doc -- | The document rbrace consists of a right brace, "}". rbrace :: Doc -- | The document lbrace consists of a left brace, "{". lbrace :: Doc -- | The document rangle consists of a greater-than sign, -- ">". rangle :: Doc -- | The document langle consists of a less-than sign, -- "<". langle :: Doc -- | The document dquote consists of a double quote, -- "\"". dquote :: Doc -- | The document squote consists of a single quote, -- "\'". squote :: Doc -- | The document backquote consists of a backquote, "`". backquote :: Doc -- | The document space n consists of n spaces. spaces :: Int -> Doc -- | The document space consists of a space, " ". space :: Doc -- | The document semi consists of a semicolon, ";". semi :: Doc -- | The document equals consists of an equals sign, "=". equals :: Doc -- | The document dot consists of a period, ".". dot :: Doc -- | The document comma consists of a comma, ",". comma :: Doc -- | The document colon consists of a colon, ":". colon :: Doc -- | The document star consists of an asterisk, "*". star :: Doc -- | The document lazyText s consists of the Text -- s, which should not contain any newlines. lazyText :: Text -> Doc -- | The document strictText s consists of the Text -- s, which should not contain any newlines. strictText :: Text -> Doc -- | The document rational r is equivalent to text (show -- r). rational :: Rational -> Doc -- | The document double d is equivalent to text (show -- d). double :: Double -> Doc -- | The document float f is equivalent to text (show f). float :: Float -> Doc -- | The document integer i is equivalent to text (show -- i). text. integer :: Integer -> Doc -- | The document int i is equivalent to text (show i). int :: Int -> Doc -- | The document string s consists of all the characters -- in s but with newlines replaced by line. string :: String -> Doc -- | The document char c consists the single character -- c. char :: Char -> Doc -- | The document bool b is equivalent to text (show b). bool :: Bool -> Doc -- | The document text s consists of the string s, -- which should not contain any newlines. For a string that may include -- newlines, use string. text :: String -> Doc -- | The abstract type of documents. data Doc -- | A rendered document. data RDoc -- | The empty document REmpty :: RDoc -- | A single character RChar :: {-# UNPACK #-} !Char -> RDoc -> RDoc -- | Doc with associated length (to avoid recomputation) RString :: {-# UNPACK #-} !Int -> String -> RDoc -> RDoc -- | Text RText :: Text -> RDoc -> RDoc -- | Text RLazyText :: Text -> RDoc -> RDoc -- | Tag output with source location RPos :: Pos -> RDoc -> RDoc -- | A newline with the indentation of the subsequent line. If this is -- followed by a RPos, output an appropriate #line pragma -- before the newline. RLine :: {-# UNPACK #-} !Int -> RDoc -> RDoc -- | Prettyprint a value, wrapped to 80 characters. pretty :: Pretty a => a -> String -- | Re-export of pretty. prettyDoc :: Int -> Doc -> String -- | Prettyprint a list enclosed in curly braces. prettyTuple :: Pretty a => [a] -> String -- | Prettyprint a value to a Text, wrapped to 80 characters. prettyText :: Pretty a => a -> Text -- | Prettyprint a value without any width restriction. prettyOneLine :: Pretty a => a -> String -- | The document apply ds separates ds with -- commas and encloses them with parentheses. apply :: [Doc] -> Doc -- | Make sure that the given document is printed on just a single line. oneLine :: Doc -> Doc -- | Stack and prepend a list of Docs to another Doc, -- separated by a linebreak. If the list is empty, the second Doc -- will be returned without a preceding linebreak. annot :: [Doc] -> Doc -> Doc -- | Surround the given document with enclosers and add linebreaks and -- indents. nestedBlock :: String -> String -> Doc -> Doc -- | Definitions of primitive types, the values that inhabit these types, -- and operations on these values. A primitive value can also be called a -- scalar. -- -- Essentially, this module describes the subset of the (internal) -- Futhark language that operates on primitive types. module Futhark.Representation.Primitive -- | An integer type, ordered by size. Note that signedness is not a -- property of the type, but a property of the operations performed on -- values of these types. data IntType Int8 :: IntType Int16 :: IntType Int32 :: IntType Int64 :: IntType -- | A list of all integer types. allIntTypes :: [IntType] -- | A floating point type. data FloatType Float32 :: FloatType Float64 :: FloatType -- | A list of all floating-point types. allFloatTypes :: [FloatType] -- | Low-level primitive types. data PrimType IntType :: IntType -> PrimType FloatType :: FloatType -> PrimType Bool :: PrimType Cert :: PrimType -- | A list of all primitive types. allPrimTypes :: [PrimType] -- | An integer value. data IntValue Int8Value :: !Int8 -> IntValue Int16Value :: !Int16 -> IntValue Int32Value :: !Int32 -> IntValue Int64Value :: !Int64 -> IntValue -- | Create an IntValue from a type and an Integer. intValue :: Integral int => IntType -> int -> IntValue intValueType :: IntValue -> IntType -- | Convert an IntValue to any Integral type. valueIntegral :: Integral int => IntValue -> int -- | A floating-point value. data FloatValue Float32Value :: !Float -> FloatValue Float64Value :: !Double -> FloatValue -- | Create a FloatValue from a type and a Rational. floatValue :: Real num => FloatType -> num -> FloatValue floatValueType :: FloatValue -> FloatType -- | Non-array values. data PrimValue IntValue :: !IntValue -> PrimValue FloatValue :: !FloatValue -> PrimValue BoolValue :: !Bool -> PrimValue -- | The only value of type cert. Checked :: PrimValue -- | The type of a basic value. primValueType :: PrimValue -> PrimType -- | A "blank" value of the given primitive type - this is zero, or -- whatever is close to it. Don't depend on this value, but use it for -- e.g. creating arrays to be populated by do-loops. blankPrimValue :: PrimType -> PrimValue -- | Various unary operators. It is a bit ad-hoc what is a unary operator -- and what is a built-in function. Perhaps these should all go away -- eventually. data UnOp -- | E.g., ! True == False. Not :: UnOp -- | E.g., ~(~1) = 1. Complement :: IntType -> UnOp -- | abs(-2) = 2. Abs :: IntType -> UnOp -- | fabs(-2.0) = 2.0. FAbs :: FloatType -> UnOp -- | Signed sign function: ssignum(-2) = -1. SSignum :: IntType -> UnOp -- | Unsigned sign function: usignum(2) = 1. USignum :: IntType -> UnOp -- | A list of all unary operators for all types. allUnOps :: [UnOp] -- | Binary operators. These correspond closely to the binary operators in -- LLVM. Most are parametrised by their expected input and output types. data BinOp -- | Integer addition. Add :: IntType -> BinOp -- | Floating-point addition. FAdd :: FloatType -> BinOp -- | Integer subtraction. Sub :: IntType -> BinOp -- | Floating-point subtraction. FSub :: FloatType -> BinOp -- | Integer multiplication. Mul :: IntType -> BinOp -- | Floating-point multiplication. FMul :: FloatType -> BinOp -- | Unsigned integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. UDiv :: IntType -> BinOp -- | Signed integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. SDiv :: IntType -> BinOp -- | Floating-point division. FDiv :: FloatType -> BinOp -- | Unsigned integer modulus; the countepart to UDiv. UMod :: IntType -> BinOp -- | Signed integer modulus; the countepart to SDiv. SMod :: IntType -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- sdiv instruction in LLVM. SQuot :: IntType -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- srem instruction in LLVM. SRem :: IntType -> BinOp -- | Returns the smallest of two signed integers. SMin :: IntType -> BinOp -- | Returns the smallest of two unsigned integers. UMin :: IntType -> BinOp -- | Returns the smallest of two floating-point numbers. FMin :: FloatType -> BinOp -- | Returns the greatest of two signed integers. SMax :: IntType -> BinOp -- | Returns the greatest of two unsigned integers. UMax :: IntType -> BinOp -- | Returns the greatest of two floating-point numbers. FMax :: FloatType -> BinOp -- | Left-shift. Shl :: IntType -> BinOp -- | Logical right-shift, zero-extended. LShr :: IntType -> BinOp -- | Arithmetic right-shift, sign-extended. AShr :: IntType -> BinOp -- | Bitwise and. And :: IntType -> BinOp -- | Bitwise or. Or :: IntType -> BinOp -- | Bitwise exclusive-or. Xor :: IntType -> BinOp -- | Integer exponentiation. Pow :: IntType -> BinOp -- | Floating-point exponentiation. FPow :: FloatType -> BinOp -- | Boolean and - not short-circuiting. LogAnd :: BinOp -- | Boolean or - not short-circuiting. LogOr :: BinOp -- | A list of all binary operators for all types. allBinOps :: [BinOp] -- | Conversion operators try to generalise the from t0 x to t1 -- instructions from LLVM. data ConvOp -- | Zero-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. ZExt :: IntType -> IntType -> ConvOp -- | Sign-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. SExt :: IntType -> IntType -> ConvOp -- | Convert value of the former floating-point type to the latter. If the -- new type is smaller, the result is a truncation. FPConv :: FloatType -> FloatType -> ConvOp -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). FPToUI :: FloatType -> IntType -> ConvOp -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). FPToSI :: FloatType -> IntType -> ConvOp -- | Convert an unsigned integer to a floating-point value. UIToFP :: IntType -> FloatType -> ConvOp -- | Convert a signed integer to a floating-point value. SIToFP :: IntType -> FloatType -> ConvOp -- | Convert an integer to a boolean value. Zero becomes false; anything -- else is true. IToB :: IntType -> ConvOp -- | Convert a boolean to an integer. True is converted to 1 and False to -- 0. BToI :: IntType -> ConvOp -- | A list of all conversion operators for all types. allConvOps :: [ConvOp] -- | Comparison operators are like BinOps, but they return -- PrimTypes. The somewhat ugly constructor names are straight out -- of LLVM. data CmpOp -- | All types equality. CmpEq :: PrimType -> CmpOp -- | Unsigned less than. CmpUlt :: IntType -> CmpOp -- | Unsigned less than or equal. CmpUle :: IntType -> CmpOp -- | Signed less than. CmpSlt :: IntType -> CmpOp -- | Signed less than or equal. CmpSle :: IntType -> CmpOp -- | Floating-point less than. FCmpLt :: FloatType -> CmpOp -- | Floating-point less than or equal. FCmpLe :: FloatType -> CmpOp -- | Boolean less than. CmpLlt :: CmpOp -- | Boolean less than or equal. CmpLle :: CmpOp -- | A list of all comparison operators for all types. allCmpOps :: [CmpOp] doUnOp :: UnOp -> PrimValue -> Maybe PrimValue -- | E.g., ~(~1) = 1. doComplement :: IntValue -> IntValue -- | abs(-2) = 2. doAbs :: IntValue -> IntValue -- | abs(-2.0) = 2.0. doFAbs :: FloatValue -> FloatValue -- | ssignum(-2) = -1. doSSignum :: IntValue -> IntValue -- | usignum(-2) = -1. doUSignum :: IntValue -> IntValue doBinOp :: BinOp -> PrimValue -> PrimValue -> Maybe PrimValue -- | Integer addition. doAdd :: IntValue -> IntValue -> IntValue -- | Integer multiplication. doMul :: IntValue -> IntValue -> IntValue -- | Signed integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. doSDiv :: IntValue -> IntValue -> Maybe IntValue -- | Signed integer modulus; the countepart to SDiv. doSMod :: IntValue -> IntValue -> Maybe IntValue -- | Signed integer exponentatation. doPow :: IntValue -> IntValue -> Maybe IntValue doConvOp :: ConvOp -> PrimValue -> Maybe PrimValue -- | Zero-extend the given integer value to the size of the given type. If -- the type is smaller than the given value, the result is a truncation. doZExt :: IntValue -> IntType -> IntValue -- | Sign-extend the given integer value to the size of the given type. If -- the type is smaller than the given value, the result is a truncation. doSExt :: IntValue -> IntType -> IntValue -- | Convert the former floating-point type to the latter. doFPConv :: FloatValue -> FloatType -> FloatValue -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). doFPToUI :: FloatValue -> IntType -> IntValue -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). doFPToSI :: FloatValue -> IntType -> IntValue -- | Convert an unsigned integer to a floating-point value. doUIToFP :: IntValue -> FloatType -> FloatValue -- | Convert a signed integer to a floating-point value. doSIToFP :: IntValue -> FloatType -> FloatValue -- | Translate an IntValue to IntType. This is guaranteed to -- fit. intToInt64 :: IntValue -> Int64 -- | Translate an IntValue to Word64. This is guaranteed to -- fit. intToWord64 :: IntValue -> Word64 doCmpOp :: CmpOp -> PrimValue -> PrimValue -> Maybe Bool -- | Compare any two primtive values for exact equality. doCmpEq :: PrimValue -> PrimValue -> Bool -- | Unsigned less than. doCmpUlt :: IntValue -> IntValue -> Bool -- | Unsigned less than or equal. doCmpUle :: IntValue -> IntValue -> Bool -- | Signed less than. doCmpSlt :: IntValue -> IntValue -> Bool -- | Signed less than or equal. doCmpSle :: IntValue -> IntValue -> Bool -- | Floating-point less than. doFCmpLt :: FloatValue -> FloatValue -> Bool -- | Floating-point less than or equal. doFCmpLe :: FloatValue -> FloatValue -> Bool -- | The result type of a binary operator. binOpType :: BinOp -> PrimType -- | The operand and result type of a unary operator. unOpType :: UnOp -> PrimType -- | The operand types of a comparison operator. cmpOpType :: CmpOp -> PrimType -- | The input and output types of a conversion operator. convOpType :: ConvOp -> (PrimType, PrimType) -- | A mapping from names of primitive functions to their parameter types, -- their result type, and a function for evaluating them. primFuns :: Map String ([PrimType], PrimType, [PrimValue] -> Maybe PrimValue) -- | Is the given value kind of zero? zeroIsh :: PrimValue -> Bool -- | Is the given value kind of one? oneIsh :: PrimValue -> Bool -- | Is the given value kind of negative? negativeIsh :: PrimValue -> Bool -- | The size of a value of a given primitive type in bites. primBitSize :: PrimType -> Int -- | The size of a value of a given primitive type in eight-bit bytes. primByteSize :: Num a => PrimType -> a -- | True if the given binary operator is commutative. commutativeBinOp :: BinOp -> Bool convOpFun :: ConvOp -> String -- | True if signed. Only makes a difference for integer types. prettySigned :: Bool -> PrimType -> String instance GHC.Show.Show Futhark.Representation.Primitive.ConvOp instance GHC.Classes.Ord Futhark.Representation.Primitive.ConvOp instance GHC.Classes.Eq Futhark.Representation.Primitive.ConvOp instance GHC.Show.Show Futhark.Representation.Primitive.CmpOp instance GHC.Classes.Ord Futhark.Representation.Primitive.CmpOp instance GHC.Classes.Eq Futhark.Representation.Primitive.CmpOp instance GHC.Show.Show Futhark.Representation.Primitive.BinOp instance GHC.Classes.Ord Futhark.Representation.Primitive.BinOp instance GHC.Classes.Eq Futhark.Representation.Primitive.BinOp instance GHC.Show.Show Futhark.Representation.Primitive.UnOp instance GHC.Classes.Ord Futhark.Representation.Primitive.UnOp instance GHC.Classes.Eq Futhark.Representation.Primitive.UnOp instance GHC.Show.Show Futhark.Representation.Primitive.PrimValue instance GHC.Classes.Ord Futhark.Representation.Primitive.PrimValue instance GHC.Classes.Eq Futhark.Representation.Primitive.PrimValue instance GHC.Show.Show Futhark.Representation.Primitive.FloatValue instance GHC.Classes.Ord Futhark.Representation.Primitive.FloatValue instance GHC.Classes.Eq Futhark.Representation.Primitive.FloatValue instance GHC.Show.Show Futhark.Representation.Primitive.IntValue instance GHC.Classes.Ord Futhark.Representation.Primitive.IntValue instance GHC.Classes.Eq Futhark.Representation.Primitive.IntValue instance GHC.Show.Show Futhark.Representation.Primitive.PrimType instance GHC.Classes.Ord Futhark.Representation.Primitive.PrimType instance GHC.Classes.Eq Futhark.Representation.Primitive.PrimType instance GHC.Enum.Bounded Futhark.Representation.Primitive.FloatType instance GHC.Enum.Enum Futhark.Representation.Primitive.FloatType instance GHC.Show.Show Futhark.Representation.Primitive.FloatType instance GHC.Classes.Ord Futhark.Representation.Primitive.FloatType instance GHC.Classes.Eq Futhark.Representation.Primitive.FloatType instance GHC.Enum.Bounded Futhark.Representation.Primitive.IntType instance GHC.Enum.Enum Futhark.Representation.Primitive.IntType instance GHC.Show.Show Futhark.Representation.Primitive.IntType instance GHC.Classes.Ord Futhark.Representation.Primitive.IntType instance GHC.Classes.Eq Futhark.Representation.Primitive.IntType instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Representation.Primitive.ConvOp instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Representation.Primitive.CmpOp instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Representation.Primitive.BinOp instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Representation.Primitive.UnOp instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Representation.Primitive.PrimValue instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Representation.Primitive.FloatValue instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Representation.Primitive.IntValue instance GHC.Enum.Enum Futhark.Representation.Primitive.PrimType instance GHC.Enum.Bounded Futhark.Representation.Primitive.PrimType instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Representation.Primitive.PrimType instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Representation.Primitive.FloatType instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Representation.Primitive.IntType -- | Basic table building for prettier futhark-test output. module Futhark.Util.Table -- | Builds a table from a list of entries and a padding amount that -- determines padding from the right side of the widest entry in each -- column. buildTable :: [[Entry]] -> Int -> String -- | Makes a table entry with the default SGR mode. mkEntry :: String -> (String, [SGR]) -- | A table entry. Consists of the content as well a list of SGR commands -- to color/stylelize the entry. type Entry = (String, [SGR]) instance GHC.Show.Show Futhark.Util.Table.RowTemplate -- | This module contains very basic definitions for Futhark - so basic, -- that they can be shared between the internal and external -- representation. module Language.Futhark.Core -- | The uniqueness attribute of a type. This essentially indicates whether -- or not in-place modifications are acceptable. With respect to -- ordering, Unique is greater than Nonunique. data Uniqueness -- | May have references outside current function. Nonunique :: Uniqueness -- | No references outside current function. Unique :: Uniqueness data StreamOrd InOrder :: StreamOrd Disorder :: StreamOrd -- | Whether some operator is commutative or not. The Monoid -- instance returns the least commutative of its arguments. data Commutativity Noncommutative :: Commutativity Commutative :: Commutativity -- | A human-readable location string, of the form -- filename:lineno:columnno. locStr :: SrcLoc -> String -- | The abstract (not really) type representing names in the Futhark -- compiler. Strings, being lists of characters, are very slow, -- while Texts are based on byte-arrays. data Name -- | Convert a name to the corresponding list of characters. nameToString :: Name -> String -- | Convert a list of characters to the corresponding name. nameFromString :: String -> Name -- | Convert a name to the corresponding Text. nameToText :: Name -> Text -- | Convert a Text to the corresponding name. nameFromText :: Text -> Name -- | A name tagged with some integer. Only the integer is used in -- comparisons, no matter the type of vn. data VName VName :: !Name -> !Int -> VName -- | Return the tag contained in the VName. baseTag :: VName -> Int -- | Return the name contained in the VName. baseName :: VName -> Name -- | Return the base Name converted to a string. baseString :: VName -> String -- | Prettyprint a value, wrapped to 80 characters. pretty :: Pretty a => a -> String -- | The name of the default program entry point (main). defaultEntryPoint :: Name -- | 8-bit signed integer type data Int8 -- | 16-bit signed integer type data Int16 -- | 32-bit signed integer type data Int32 -- | 64-bit signed integer type data Int64 -- | 8-bit unsigned integer type data Word8 -- | 16-bit unsigned integer type data Word16 -- | 32-bit unsigned integer type data Word32 -- | 64-bit unsigned integer type data Word64 instance GHC.Show.Show Language.Futhark.Core.VName instance GHC.Base.Semigroup Language.Futhark.Core.Name instance Data.String.IsString Language.Futhark.Core.Name instance GHC.Classes.Ord Language.Futhark.Core.Name instance GHC.Classes.Eq Language.Futhark.Core.Name instance GHC.Show.Show Language.Futhark.Core.Name instance GHC.Show.Show Language.Futhark.Core.Commutativity instance GHC.Classes.Ord Language.Futhark.Core.Commutativity instance GHC.Classes.Eq Language.Futhark.Core.Commutativity instance GHC.Show.Show Language.Futhark.Core.StreamOrd instance GHC.Classes.Ord Language.Futhark.Core.StreamOrd instance GHC.Classes.Eq Language.Futhark.Core.StreamOrd instance GHC.Show.Show Language.Futhark.Core.Uniqueness instance GHC.Classes.Ord Language.Futhark.Core.Uniqueness instance GHC.Classes.Eq Language.Futhark.Core.Uniqueness instance GHC.Classes.Eq Language.Futhark.Core.VName instance GHC.Classes.Ord Language.Futhark.Core.VName instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Core.Name instance GHC.Base.Semigroup Language.Futhark.Core.Commutativity instance GHC.Base.Monoid Language.Futhark.Core.Commutativity instance GHC.Base.Semigroup Language.Futhark.Core.Uniqueness instance GHC.Base.Monoid Language.Futhark.Core.Uniqueness instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Core.Uniqueness -- | The most primitive ("core") aspects of the AST. Split out of -- Futhark.Representation.AST.Syntax in order for -- Futhark.Representation.AST.Annotations to use these -- definitions. This module is re-exported from -- Futhark.Representation.AST.Syntax and there should be no reason -- to include it explicitly. module Futhark.Representation.AST.Syntax.Core -- | The uniqueness attribute of a type. This essentially indicates whether -- or not in-place modifications are acceptable. With respect to -- ordering, Unique is greater than Nonunique. data Uniqueness -- | May have references outside current function. Nonunique :: Uniqueness -- | No references outside current function. Unique :: Uniqueness -- | A fancier name for '()' - encodes no uniqueness information. data NoUniqueness NoUniqueness :: NoUniqueness -- | The size of an array type as a list of its dimension sizes, with the -- type of sizes being parametric. newtype ShapeBase d Shape :: [d] -> ShapeBase d [shapeDims] :: ShapeBase d -> [d] -- | The size of an array as a list of subexpressions. If a variable, that -- variable must be in scope where this array is used. type Shape = ShapeBase SubExp -- | Something that may be existential. data Ext a Ext :: Int -> Ext a Free :: a -> Ext a -- | The size of this dimension. type ExtSize = Ext SubExp -- | Like ShapeBase but some of its elements may be bound in a local -- environment instead. These are denoted with integral indices. type ExtShape = ShapeBase ExtSize -- | The size of an array type as merely the number of dimensions, with no -- further information. newtype Rank Rank :: Int -> Rank -- | A class encompassing types containing array shape information. class (Monoid a, Eq a, Ord a) => ArrayShape a -- | Return the rank of an array with the given size. shapeRank :: ArrayShape a => a -> Int -- | stripDims n shape strips the outer n dimensions from -- shape. stripDims :: ArrayShape a => Int -> a -> a -- | Check whether one shape if a subset of another shape. subShapeOf :: ArrayShape a => a -> a -> Bool -- | The memory space of a block. If DefaultSpace, this is the -- "default" space, whatever that is. The exact meaning of the -- SpaceID depends on the backend used. In GPU kernels, for -- example, this is used to distinguish between constant, global and -- shared memory spaces. In GPU-enabled host code, it is used to -- distinguish between host memory (DefaultSpace) and GPU space. data Space DefaultSpace :: Space Space :: SpaceId -> Space -- | A string representing a specific non-default memory space. type SpaceId = String -- | An Futhark type is either an array or an element type. When comparing -- types for equality with ==, shapes must match. data TypeBase shape u Prim :: PrimType -> TypeBase shape u Array :: PrimType -> shape -> u -> TypeBase shape u Mem :: SubExp -> Space -> TypeBase shape u -- | A type with shape information, used for describing the type of -- variables. type Type = TypeBase Shape NoUniqueness -- | A type with existentially quantified shapes - used as part of function -- (and function-like) return types. Generally only makes sense when used -- in a list. type ExtType = TypeBase ExtShape NoUniqueness -- | A type with shape and uniqueness information, used declaring return- -- and parameters types. type DeclType = TypeBase Shape Uniqueness -- | An ExtType with uniqueness information, used for function -- return types. type DeclExtType = TypeBase ExtShape Uniqueness -- | Information about which parts of a value/type are consumed. For -- example, we might say that a function taking three arguments of types -- ([int], *[int], [int]) has diet [Observe, Consume, -- Observe]. data Diet -- | Consumes this value. Consume :: Diet -- | Only observes value in this position, does not consume. Observe :: Diet -- | An error message is a list of error parts, which are concatenated to -- form the final message. newtype ErrorMsg a ErrorMsg :: [ErrorMsgPart a] -> ErrorMsg a -- | A part of an error message. data ErrorMsgPart a -- | A literal string. ErrorString :: String -> ErrorMsgPart a -- | A run-time integer value. ErrorInt32 :: a -> ErrorMsgPart a -- | Non-array values. data PrimValue IntValue :: !IntValue -> PrimValue FloatValue :: !FloatValue -> PrimValue BoolValue :: !Bool -> PrimValue -- | The only value of type cert. Checked :: PrimValue -- | An identifier consists of its name and the type of the value bound to -- the identifier. data Ident Ident :: VName -> Type -> Ident [identName] :: Ident -> VName [identType] :: Ident -> Type -- | A list of names used for certificates in some expressions. newtype Certificates Certificates :: [VName] -> Certificates [unCertificates] :: Certificates -> [VName] -- | A subexpression is either a scalar constant or a variable. One -- important property is that evaluation of a subexpression is guaranteed -- to complete in constant time. data SubExp Constant :: PrimValue -> SubExp Var :: VName -> SubExp -- | A function parameter. data ParamT attr Param :: VName -> attr -> ParamT attr -- | Name of the parameter. [paramName] :: ParamT attr -> VName -- | Function parameter attribute. [paramAttr] :: ParamT attr -> attr -- | A type alias for namespace control. type Param = ParamT -- | How to index a single dimension of an array. data DimIndex d -- | Fix index in this dimension. DimFix :: d -> DimIndex d -- | DimSlice start_offset num_elems stride. DimSlice :: d -> d -> d -> DimIndex d -- | A list of DimFixs, indicating how an array should be sliced. -- Whenever a function accepts a Slice, that slice should be -- total, i.e, cover all dimensions of the array. Deviators should be -- indicated by taking a list of DimIndexes instead. type Slice d = [DimIndex d] -- | If the argument is a DimFix, return its component. dimFix :: DimIndex d -> Maybe d -- | If the slice is all DimFixs, return the components. sliceIndices :: Slice d -> Maybe [d] -- | The dimensions of the array produced by this slice. sliceDims :: Slice d -> [d] -- | A slice with a stride of one. unitSlice :: Num d => d -> d -> DimIndex d -- | Fix the DimSlices of a slice. The number of indexes must equal -- the length of sliceDims for the slice. fixSlice :: Num d => Slice d -> [d] -> [d] -- | An element of a pattern - consisting of an name (essentially a pair of -- the name andtype), a Bindage, and an addditional parametric -- attribute. This attribute is what is expected to contain the type of -- the resulting variable. data PatElemT attr PatElem :: VName -> attr -> PatElemT attr -- | The name being bound. [patElemName] :: PatElemT attr -> VName -- | Pattern element attribute. [patElemAttr] :: PatElemT attr -> attr -- | A set of names. type Names = Set VName instance GHC.Show.Show a => GHC.Show.Show (Futhark.Representation.AST.Syntax.Core.ErrorMsg a) instance GHC.Classes.Ord a => GHC.Classes.Ord (Futhark.Representation.AST.Syntax.Core.ErrorMsg a) instance GHC.Classes.Eq a => GHC.Classes.Eq (Futhark.Representation.AST.Syntax.Core.ErrorMsg a) instance GHC.Show.Show a => GHC.Show.Show (Futhark.Representation.AST.Syntax.Core.ErrorMsgPart a) instance GHC.Classes.Ord a => GHC.Classes.Ord (Futhark.Representation.AST.Syntax.Core.ErrorMsgPart a) instance GHC.Classes.Eq a => GHC.Classes.Eq (Futhark.Representation.AST.Syntax.Core.ErrorMsgPart a) instance GHC.Classes.Eq attr => GHC.Classes.Eq (Futhark.Representation.AST.Syntax.Core.PatElemT attr) instance GHC.Show.Show attr => GHC.Show.Show (Futhark.Representation.AST.Syntax.Core.PatElemT attr) instance GHC.Classes.Ord attr => GHC.Classes.Ord (Futhark.Representation.AST.Syntax.Core.PatElemT attr) instance GHC.Show.Show d => GHC.Show.Show (Futhark.Representation.AST.Syntax.Core.DimIndex d) instance GHC.Classes.Ord d => GHC.Classes.Ord (Futhark.Representation.AST.Syntax.Core.DimIndex d) instance GHC.Classes.Eq d => GHC.Classes.Eq (Futhark.Representation.AST.Syntax.Core.DimIndex d) instance GHC.Classes.Eq attr => GHC.Classes.Eq (Futhark.Representation.AST.Syntax.Core.ParamT attr) instance GHC.Show.Show attr => GHC.Show.Show (Futhark.Representation.AST.Syntax.Core.ParamT attr) instance GHC.Classes.Ord attr => GHC.Classes.Ord (Futhark.Representation.AST.Syntax.Core.ParamT attr) instance GHC.Show.Show Futhark.Representation.AST.Syntax.Core.Ident instance (GHC.Classes.Ord shape, GHC.Classes.Ord u) => GHC.Classes.Ord (Futhark.Representation.AST.Syntax.Core.TypeBase shape u) instance (GHC.Classes.Eq shape, GHC.Classes.Eq u) => GHC.Classes.Eq (Futhark.Representation.AST.Syntax.Core.TypeBase shape u) instance (GHC.Show.Show shape, GHC.Show.Show u) => GHC.Show.Show (Futhark.Representation.AST.Syntax.Core.TypeBase shape u) instance GHC.Classes.Ord Futhark.Representation.AST.Syntax.Core.SubExp instance GHC.Classes.Eq Futhark.Representation.AST.Syntax.Core.SubExp instance GHC.Show.Show Futhark.Representation.AST.Syntax.Core.SubExp instance GHC.Show.Show Futhark.Representation.AST.Syntax.Core.Certificates instance GHC.Classes.Ord Futhark.Representation.AST.Syntax.Core.Certificates instance GHC.Classes.Eq Futhark.Representation.AST.Syntax.Core.Certificates instance GHC.Show.Show Futhark.Representation.AST.Syntax.Core.Diet instance GHC.Classes.Ord Futhark.Representation.AST.Syntax.Core.Diet instance GHC.Classes.Eq Futhark.Representation.AST.Syntax.Core.Diet instance GHC.Show.Show Futhark.Representation.AST.Syntax.Core.NoUniqueness instance GHC.Classes.Ord Futhark.Representation.AST.Syntax.Core.NoUniqueness instance GHC.Classes.Eq Futhark.Representation.AST.Syntax.Core.NoUniqueness instance GHC.Classes.Ord Futhark.Representation.AST.Syntax.Core.Space instance GHC.Classes.Eq Futhark.Representation.AST.Syntax.Core.Space instance GHC.Show.Show Futhark.Representation.AST.Syntax.Core.Space instance GHC.Classes.Ord Futhark.Representation.AST.Syntax.Core.Rank instance GHC.Classes.Eq Futhark.Representation.AST.Syntax.Core.Rank instance GHC.Show.Show Futhark.Representation.AST.Syntax.Core.Rank instance GHC.Show.Show a => GHC.Show.Show (Futhark.Representation.AST.Syntax.Core.Ext a) instance GHC.Classes.Ord a => GHC.Classes.Ord (Futhark.Representation.AST.Syntax.Core.Ext a) instance GHC.Classes.Eq a => GHC.Classes.Eq (Futhark.Representation.AST.Syntax.Core.Ext a) instance GHC.Show.Show d => GHC.Show.Show (Futhark.Representation.AST.Syntax.Core.ShapeBase d) instance GHC.Classes.Ord d => GHC.Classes.Ord (Futhark.Representation.AST.Syntax.Core.ShapeBase d) instance GHC.Classes.Eq d => GHC.Classes.Eq (Futhark.Representation.AST.Syntax.Core.ShapeBase d) instance Data.String.IsString (Futhark.Representation.AST.Syntax.Core.ErrorMsg a) instance GHC.Base.Functor Futhark.Representation.AST.Syntax.Core.ErrorMsg instance Data.Foldable.Foldable Futhark.Representation.AST.Syntax.Core.ErrorMsg instance Data.Traversable.Traversable Futhark.Representation.AST.Syntax.Core.ErrorMsg instance Data.String.IsString (Futhark.Representation.AST.Syntax.Core.ErrorMsgPart a) instance GHC.Base.Functor Futhark.Representation.AST.Syntax.Core.ErrorMsgPart instance Data.Foldable.Foldable Futhark.Representation.AST.Syntax.Core.ErrorMsgPart instance Data.Traversable.Traversable Futhark.Representation.AST.Syntax.Core.ErrorMsgPart instance GHC.Base.Functor Futhark.Representation.AST.Syntax.Core.PatElemT instance GHC.Base.Functor Futhark.Representation.AST.Syntax.Core.DimIndex instance Data.Foldable.Foldable Futhark.Representation.AST.Syntax.Core.DimIndex instance Data.Traversable.Traversable Futhark.Representation.AST.Syntax.Core.DimIndex instance Data.Foldable.Foldable Futhark.Representation.AST.Syntax.Core.ParamT instance GHC.Base.Functor Futhark.Representation.AST.Syntax.Core.ParamT instance Data.Traversable.Traversable Futhark.Representation.AST.Syntax.Core.ParamT instance GHC.Classes.Eq Futhark.Representation.AST.Syntax.Core.Ident instance GHC.Classes.Ord Futhark.Representation.AST.Syntax.Core.Ident instance Futhark.Representation.AST.Syntax.Core.ArrayShape (Futhark.Representation.AST.Syntax.Core.ShapeBase Futhark.Representation.AST.Syntax.Core.ExtSize) instance Futhark.Representation.AST.Syntax.Core.ArrayShape (Futhark.Representation.AST.Syntax.Core.ShapeBase Futhark.Representation.AST.Syntax.Core.SubExp) instance GHC.Base.Semigroup Futhark.Representation.AST.Syntax.Core.Certificates instance GHC.Base.Monoid Futhark.Representation.AST.Syntax.Core.Certificates instance Futhark.Representation.AST.Syntax.Core.ArrayShape Futhark.Representation.AST.Syntax.Core.Rank instance GHC.Base.Semigroup Futhark.Representation.AST.Syntax.Core.Rank instance GHC.Base.Monoid Futhark.Representation.AST.Syntax.Core.Rank instance GHC.Base.Semigroup (Futhark.Representation.AST.Syntax.Core.ShapeBase d) instance GHC.Base.Monoid (Futhark.Representation.AST.Syntax.Core.ShapeBase d) instance GHC.Base.Functor Futhark.Representation.AST.Syntax.Core.ShapeBase -- | Possibly convenient facilities for constructing constants. module Futhark.Representation.AST.Attributes.Constants -- | If a Haskell type is an instance of IsValue, it means that a -- value of that type can be converted to a Futhark PrimValue. -- This is intended to cut down on boilerplate when writing compiler code -- - for example, you'll quickly grow tired of writing Constant -- (LogVal True) loc. class IsValue a value :: IsValue a => a -> PrimValue -- | Create a Constant SubExp containing the given value. constant :: IsValue v => v -> SubExp -- | Utility definition for reasons of type ambiguity. intConst :: IntType -> Integer -> SubExp -- | Utility definition for reasons of type ambiguity. floatConst :: FloatType -> Double -> SubExp instance Futhark.Representation.AST.Attributes.Constants.IsValue GHC.Types.Int instance Futhark.Representation.AST.Attributes.Constants.IsValue GHC.Int.Int8 instance Futhark.Representation.AST.Attributes.Constants.IsValue GHC.Int.Int16 instance Futhark.Representation.AST.Attributes.Constants.IsValue GHC.Int.Int32 instance Futhark.Representation.AST.Attributes.Constants.IsValue GHC.Int.Int64 instance Futhark.Representation.AST.Attributes.Constants.IsValue GHC.Word.Word8 instance Futhark.Representation.AST.Attributes.Constants.IsValue GHC.Word.Word16 instance Futhark.Representation.AST.Attributes.Constants.IsValue GHC.Word.Word32 instance Futhark.Representation.AST.Attributes.Constants.IsValue GHC.Word.Word64 instance Futhark.Representation.AST.Attributes.Constants.IsValue GHC.Types.Double instance Futhark.Representation.AST.Attributes.Constants.IsValue GHC.Types.Float instance Futhark.Representation.AST.Attributes.Constants.IsValue GHC.Types.Bool instance Futhark.Representation.AST.Attributes.Constants.IsValue Futhark.Representation.Primitive.PrimValue instance Futhark.Representation.AST.Attributes.Constants.IsValue Futhark.Representation.Primitive.IntValue instance Futhark.Representation.AST.Attributes.Constants.IsValue Futhark.Representation.Primitive.FloatValue -- | Functions for inspecting and constructing various types. module Futhark.Representation.AST.Attributes.Types -- | Remove shape information from a type. rankShaped :: ArrayShape shape => TypeBase shape u -> TypeBase Rank u -- | Return the dimensionality of a type. For non-arrays, this is zero. For -- a one-dimensional array it is one, for a two-dimensional it is two, -- and so forth. arrayRank :: ArrayShape shape => TypeBase shape u -> Int -- | Return the shape of a type - for non-arrays, this is the -- mempty. arrayShape :: ArrayShape shape => TypeBase shape u -> shape -- | Modify the shape of an array - for non-arrays, this does nothing. modifyArrayShape :: ArrayShape newshape => (oldshape -> newshape) -> TypeBase oldshape u -> TypeBase newshape u -- | Set the shape of an array. If the given type is not an array, return -- the type unchanged. setArrayShape :: ArrayShape newshape => TypeBase oldshape u -> newshape -> TypeBase newshape u -- | True if the given type has a dimension that is existentially sized. existential :: ExtType -> Bool -- | Return the uniqueness of a type. uniqueness :: TypeBase shape Uniqueness -> Uniqueness -- | Set the uniqueness attribute of a type. setUniqueness :: TypeBase shape Uniqueness -> Uniqueness -> TypeBase shape Uniqueness -- | unique t is True if the type of the argument is -- unique. unique :: TypeBase shape Uniqueness -> Bool -- | Convert types with non-existential shapes to types with -- non-existential shapes. Only the representation is changed, so all the -- shapes will be Free. staticShapes :: [TypeBase Shape u] -> [TypeBase ExtShape u] -- | As staticShapes, but on a single type. staticShapes1 :: TypeBase Shape u -> TypeBase ExtShape u -- | A type is a primitive type if it is not an array or memory block. primType :: TypeBase shape u -> Bool -- | arrayOf t s u constructs an array type. The convenience -- compared to using the Array constructor directly is that -- t can itself be an array. If t is an -- n-dimensional array, and s is a list of length -- n, the resulting type is of an n+m dimensions. The -- uniqueness of the new array will be u, no matter the -- uniqueness of t. If the shape s has rank 0, then the -- t will be returned, although if it is an array, with the -- uniqueness changed to u. arrayOf :: ArrayShape shape => TypeBase shape u_unused -> shape -> u -> TypeBase shape u -- | Construct an array whose rows are the given type, and the outer size -- is the given dimension. This is just a convenient wrapper around -- arrayOf. arrayOfRow :: ArrayShape (ShapeBase d) => TypeBase (ShapeBase d) NoUniqueness -> d -> TypeBase (ShapeBase d) NoUniqueness -- | Construct an array whose rows are the given type, and the outer size -- is the given ShapeBase. This is just a convenient wrapper -- around arrayOf. arrayOfShape :: Type -> Shape -> Type -- | Replace the size of the outermost dimension of an array. If the given -- type is not an array, it is returned unchanged. setOuterSize :: ArrayShape (ShapeBase d) => TypeBase (ShapeBase d) u -> d -> TypeBase (ShapeBase d) u -- | Replace the size of the given dimension of an array. If the given type -- is not an array, it is returned unchanged. setDimSize :: ArrayShape (ShapeBase d) => Int -> TypeBase (ShapeBase d) u -> d -> TypeBase (ShapeBase d) u -- | Replace the outermost dimension of an array shape. setOuterDim :: ShapeBase d -> d -> ShapeBase d -- | Replace the specified dimension of an array shape. setDim :: Int -> ShapeBase d -> d -> ShapeBase d -- | Set the dimensions of an array. If the given type is not an array, -- return the type unchanged. setArrayDims :: TypeBase oldshape u -> [SubExp] -> TypeBase Shape u -- | Set the existential dimensions of an array. If the given type is not -- an array, return the type unchanged. setArrayExtDims :: TypeBase oldshape u -> [ExtSize] -> TypeBase ExtShape u -- | peelArray n t returns the type resulting from peeling the -- first n array dimensions from t. Returns -- Nothing if t has less than n dimensions. peelArray :: ArrayShape shape => Int -> TypeBase shape u -> Maybe (TypeBase shape u) -- | stripArray n t removes the n outermost layers of the -- array. Essentially, it is the type of indexing an array of type -- t with n indexes. stripArray :: ArrayShape shape => Int -> TypeBase shape u -> TypeBase shape u -- | Return the dimensions of a type - for non-arrays, this is the empty -- list. arrayDims :: TypeBase Shape u -> [SubExp] -- | Return the existential dimensions of a type - for non-arrays, this is -- the empty list. arrayExtDims :: TypeBase ExtShape u -> [ExtSize] -- | Return the size of the given dimension. If the dimension does not -- exist, the zero constant is returned. shapeSize :: Int -> Shape -> SubExp -- | Return the size of the given dimension. If the dimension does not -- exist, the zero constant is returned. arraySize :: Int -> TypeBase Shape u -> SubExp -- | Return the size of the given dimension in the first element of the -- given type list. If the dimension does not exist, or no types are -- given, the zero constant is returned. arraysSize :: Int -> [TypeBase Shape u] -> SubExp -- | Return the immediate row-type of an array. For [[int]], this -- would be [int]. rowType :: ArrayShape shape => TypeBase shape u -> TypeBase shape u -- | Returns the bottommost type of an array. For [[int]], this -- would be int. If the given type is not an array, it is -- returned. elemType :: TypeBase shape u -> PrimType -- | Swap the two outer dimensions of the type. transposeType :: Type -> Type -- | Rearrange the dimensions of the type. If the length of the permutation -- does not match the rank of the type, the permutation will be extended -- with identity. rearrangeType :: [Int] -> Type -> Type -- | diet t returns a description of how a function parameter of -- type t might consume its argument. diet :: TypeBase shape Uniqueness -> Diet -- | x `subtypeOf` y is true if x is a subtype of -- y (or equal to y), meaning x is valid -- whenever y is. subtypeOf :: (Ord u, ArrayShape shape) => TypeBase shape u -> TypeBase shape u -> Bool -- | xs `subtypesOf` ys is true if xs is the same size as -- ys, and each element in xs is a subtype of the -- corresponding element in ys.. subtypesOf :: (Ord u, ArrayShape shape) => [TypeBase shape u] -> [TypeBase shape u] -> Bool toDecl :: TypeBase shape NoUniqueness -> Uniqueness -> TypeBase shape Uniqueness fromDecl :: TypeBase shape Uniqueness -> TypeBase shape NoUniqueness -- | Given the existential return type of a function, and the shapes of the -- values returned by the function, return the existential shape context. -- That is, those sizes that are existential in the return type. extractShapeContext :: [TypeBase ExtShape u] -> [[a]] -> [a] -- | The set of identifiers used for the shape context in the given -- ExtTypes. shapeContext :: [TypeBase ExtShape u] -> Set Int -- | The size of the set that would be returned by shapeContext. shapeContextSize :: [ExtType] -> Int -- | If all dimensions of the given RetType are statically known, -- return the corresponding list of Type. hasStaticShape :: ExtType -> Maybe Type hasStaticShapes :: [ExtType] -> Maybe [Type] -- | Given two lists of ExtTypes of the same length, return a list -- of ExtTypes that is a subtype (as per isSubtypeOf) of -- the two operands. generaliseExtTypes :: [TypeBase ExtShape u] -> [TypeBase ExtShape u] -> [TypeBase ExtShape u] -- | Given a list of ExtTypes and a list of "forbidden" names, -- modify the dimensions of the ExtTypes such that they are -- Ext where they were previously Free with a variable in -- the set of forbidden names. existentialiseExtTypes :: [VName] -> [ExtType] -> [ExtType] -- | In the call shapeMapping ts1 ts2, the lists ts1 and -- ts must be of equal length and their corresponding elements -- have the same types modulo exact dimensions (but matching array rank -- is important). The result is a mapping from named dimensions of -- ts1 to the corresponding dimension in ts2. -- -- This function is useful when ts1 are the value parameters of -- some function and ts2 are the value arguments, and we need to -- figure out which shape context to pass. shapeMapping :: [TypeBase Shape u0] -> [TypeBase Shape u1] -> Map VName SubExp -- | Like shapeMapping, but works with explicit dimensions. shapeMapping' :: [TypeBase Shape u] -> [[a]] -> Map VName a -- | Like shapeMapping, but produces a mapping for the dimensions -- context. shapeExtMapping :: [TypeBase ExtShape u] -> [TypeBase Shape u1] -> Map Int SubExp int8 :: PrimType int16 :: PrimType int32 :: PrimType int64 :: PrimType float32 :: PrimType float64 :: PrimType -- | Typeclass for things that contain Types. class Typed t typeOf :: Typed t => t -> Type -- | Typeclass for things that contain DeclTypes. class DeclTyped t declTypeOf :: DeclTyped t => t -> DeclType -- | Typeclass for things that contain ExtTypes. class FixExt t => ExtTyped t extTypeOf :: ExtTyped t => t -> ExtType -- | Typeclass for things that contain DeclExtTypes. class FixExt t => DeclExtTyped t declExtTypeOf :: DeclExtTyped t => t -> DeclExtType -- | Typeclass for things whose type can be changed. class Typed a => SetType a setType :: SetType a => a -> Type -> a -- | Something with an existential context that can be (partially) fixed. class FixExt t -- | Fix the given existentional variable to the indicated free value. fixExt :: FixExt t => Int -> SubExp -> t -> t instance Futhark.Representation.AST.Attributes.Types.ExtTyped Futhark.Representation.AST.Syntax.Core.ExtType instance Futhark.Representation.AST.Attributes.Types.DeclExtTyped Futhark.Representation.AST.Syntax.Core.DeclExtType instance (Futhark.Representation.AST.Attributes.Types.FixExt shape, Futhark.Representation.AST.Syntax.Core.ArrayShape shape) => Futhark.Representation.AST.Attributes.Types.FixExt (Futhark.Representation.AST.Syntax.Core.TypeBase shape u) instance Futhark.Representation.AST.Attributes.Types.FixExt d => Futhark.Representation.AST.Attributes.Types.FixExt (Futhark.Representation.AST.Syntax.Core.ShapeBase d) instance Futhark.Representation.AST.Attributes.Types.FixExt a => Futhark.Representation.AST.Attributes.Types.FixExt [a] instance Futhark.Representation.AST.Attributes.Types.FixExt Futhark.Representation.AST.Syntax.Core.ExtSize instance Futhark.Representation.AST.Attributes.Types.FixExt () instance Futhark.Representation.AST.Attributes.Types.SetType Futhark.Representation.AST.Syntax.Core.Type instance Futhark.Representation.AST.Attributes.Types.SetType b => Futhark.Representation.AST.Attributes.Types.SetType (a, b) instance Futhark.Representation.AST.Attributes.Types.SetType attr => Futhark.Representation.AST.Attributes.Types.SetType (Futhark.Representation.AST.Syntax.Core.PatElemT attr) instance Futhark.Representation.AST.Attributes.Types.DeclTyped Futhark.Representation.AST.Syntax.Core.DeclType instance Futhark.Representation.AST.Attributes.Types.DeclTyped attr => Futhark.Representation.AST.Attributes.Types.DeclTyped (Futhark.Representation.AST.Syntax.Core.Param attr) instance Futhark.Representation.AST.Attributes.Types.Typed Futhark.Representation.AST.Syntax.Core.Type instance Futhark.Representation.AST.Attributes.Types.Typed Futhark.Representation.AST.Syntax.Core.DeclType instance Futhark.Representation.AST.Attributes.Types.Typed Futhark.Representation.AST.Syntax.Core.Ident instance Futhark.Representation.AST.Attributes.Types.Typed attr => Futhark.Representation.AST.Attributes.Types.Typed (Futhark.Representation.AST.Syntax.Core.Param attr) instance Futhark.Representation.AST.Attributes.Types.Typed attr => Futhark.Representation.AST.Attributes.Types.Typed (Futhark.Representation.AST.Syntax.Core.PatElemT attr) instance Futhark.Representation.AST.Attributes.Types.Typed b => Futhark.Representation.AST.Attributes.Types.Typed (a, b) -- | This module exports a type class covering representations of function -- return types. module Futhark.Representation.AST.RetType -- | A type representing the return type of a body. It should contain at -- least the information contained in a list of ExtTypes, but may -- have more, notably an existential context. class (Show rt, Eq rt, Ord rt, ExtTyped rt) => IsBodyType rt -- | Construct a body type from a primitive type. primBodyType :: IsBodyType rt => PrimType -> rt bodyTypeValues :: IsBodyType rt => [rt] -> [ExtType] -- | A type representing the return type of a function. In practice, a list -- of these will be used. It should contain at least the information -- contained in an ExtType, but may have more, notably an -- existential context. class (Show rt, Eq rt, Ord rt, DeclExtTyped rt) => IsRetType rt -- | Contruct a return type from a primitive type. primRetType :: IsRetType rt => PrimType -> rt -- | Given a function return type, the parameters of the function, and the -- arguments for a concrete call, return the instantiated return type for -- the concrete call, if valid. applyRetType :: (IsRetType rt, Typed attr) => [rt] -> [Param attr] -> [(SubExp, Type)] -> Maybe [rt] retTypeValues :: IsRetType rt => [rt] -> [DeclExtType] -- | Given shape parameter names and value parameter types, produce the -- types of arguments accepted. expectedTypes :: Typed t => [VName] -> [t] -> [SubExp] -> [Type] instance Futhark.Representation.AST.RetType.IsRetType Futhark.Representation.AST.Syntax.Core.DeclExtType instance Futhark.Representation.AST.RetType.IsBodyType Futhark.Representation.AST.Syntax.Core.ExtType module Futhark.Representation.AST.Annotations class (Show (LetAttr l), Show (ExpAttr l), Show (BodyAttr l), Show (FParamAttr l), Show (LParamAttr l), Show (RetType l), Show (BranchType l), Show (Op l), Eq (LetAttr l), Eq (ExpAttr l), Eq (BodyAttr l), Eq (FParamAttr l), Eq (LParamAttr l), Eq (RetType l), Eq (BranchType l), Eq (Op l), Ord (LetAttr l), Ord (ExpAttr l), Ord (BodyAttr l), Ord (FParamAttr l), Ord (LParamAttr l), Ord (RetType l), Ord (BranchType l), Ord (Op l), IsRetType (RetType l), IsBodyType (BranchType l), Typed (FParamAttr l), Typed (LParamAttr l), Typed (LetAttr l), DeclTyped (FParamAttr l)) => Annotations l where { -- | Annotation for every let-pattern element. type family LetAttr l :: *; -- | Annotation for every expression. type family ExpAttr l :: *; -- | Annotation for every body. type family BodyAttr l :: *; -- | Annotation for every (non-lambda) function parameter. type family FParamAttr l :: *; -- | Annotation for every lambda function parameter. type family LParamAttr l :: *; -- | The return type annotation of function calls. type family RetType l :: *; -- | The return type annotation of branches. type family BranchType l :: *; -- | Extensible operation. type family Op l :: *; type LetAttr l = Type; type ExpAttr l = (); type BodyAttr l = (); type FParamAttr l = DeclType; type LParamAttr l = Type; type RetType l = DeclExtType; type BranchType l = ExtType; type Op l = (); } -- | Futhark core language skeleton. Concrete representations further -- extend this skeleton by defining a "lore", which specifies concrete -- annotations (Futhark.Representation.AST.Annotations) and -- semantics. module Futhark.Representation.AST.Syntax -- | The uniqueness attribute of a type. This essentially indicates whether -- or not in-place modifications are acceptable. With respect to -- ordering, Unique is greater than Nonunique. data Uniqueness -- | May have references outside current function. Nonunique :: Uniqueness -- | No references outside current function. Unique :: Uniqueness -- | A fancier name for '()' - encodes no uniqueness information. data NoUniqueness NoUniqueness :: NoUniqueness -- | The size of an array type as merely the number of dimensions, with no -- further information. newtype Rank Rank :: Int -> Rank -- | A class encompassing types containing array shape information. class (Monoid a, Eq a, Ord a) => ArrayShape a -- | Return the rank of an array with the given size. shapeRank :: ArrayShape a => a -> Int -- | stripDims n shape strips the outer n dimensions from -- shape. stripDims :: ArrayShape a => Int -> a -> a -- | Check whether one shape if a subset of another shape. subShapeOf :: ArrayShape a => a -> a -> Bool -- | The memory space of a block. If DefaultSpace, this is the -- "default" space, whatever that is. The exact meaning of the -- SpaceID depends on the backend used. In GPU kernels, for -- example, this is used to distinguish between constant, global and -- shared memory spaces. In GPU-enabled host code, it is used to -- distinguish between host memory (DefaultSpace) and GPU space. data Space DefaultSpace :: Space Space :: SpaceId -> Space -- | An Futhark type is either an array or an element type. When comparing -- types for equality with ==, shapes must match. data TypeBase shape u Prim :: PrimType -> TypeBase shape u Array :: PrimType -> shape -> u -> TypeBase shape u Mem :: SubExp -> Space -> TypeBase shape u -- | Information about which parts of a value/type are consumed. For -- example, we might say that a function taking three arguments of types -- ([int], *[int], [int]) has diet [Observe, Consume, -- Observe]. data Diet -- | Consumes this value. Consume :: Diet -- | Only observes value in this position, does not consume. Observe :: Diet -- | An identifier consists of its name and the type of the value bound to -- the identifier. data Ident Ident :: VName -> Type -> Ident [identName] :: Ident -> VName [identType] :: Ident -> Type -- | A subexpression is either a scalar constant or a variable. One -- important property is that evaluation of a subexpression is guaranteed -- to complete in constant time. data SubExp Constant :: PrimValue -> SubExp Var :: VName -> SubExp -- | A type alias for namespace control. type PatElem lore = PatElemT (LetAttr lore) -- | An element of a pattern - consisting of an name (essentially a pair of -- the name andtype), a Bindage, and an addditional parametric -- attribute. This attribute is what is expected to contain the type of -- the resulting variable. data PatElemT attr PatElem :: VName -> attr -> PatElemT attr -- | The name being bound. [patElemName] :: PatElemT attr -> VName -- | Pattern element attribute. [patElemAttr] :: PatElemT attr -> attr -- | A pattern is conceptually just a list of names and their types. data PatternT attr Pattern :: [PatElemT attr] -> [PatElemT attr] -> PatternT attr -- | existential context (sizes and memory blocks) [patternContextElements] :: PatternT attr -> [PatElemT attr] -- | "real" values [patternValueElements] :: PatternT attr -> [PatElemT attr] -- | A type alias for namespace control. type Pattern lore = PatternT (LetAttr lore) -- | Auxilliary Information associated with a statement. data StmAux attr StmAux :: !Certificates -> attr -> StmAux attr [stmAuxCerts] :: StmAux attr -> !Certificates [stmAuxAttr] :: StmAux attr -> attr -- | A local variable binding. data Stm lore Let :: Pattern lore -> StmAux (ExpAttr lore) -> Exp lore -> Stm lore [stmPattern] :: Stm lore -> Pattern lore [stmAux] :: Stm lore -> StmAux (ExpAttr lore) [stmExp] :: Stm lore -> Exp lore -- | A sequence of statements. type Stms lore = Seq (Stm lore) -- | The result of a body is a sequence of subexpressions. type Result = [SubExp] -- | A body consists of a number of bindings, terminating in a result -- (essentially a tuple literal). data BodyT lore Body :: BodyAttr lore -> Stms lore -> Result -> BodyT lore [bodyAttr] :: BodyT lore -> BodyAttr lore [bodyStms] :: BodyT lore -> Stms lore [bodyResult] :: BodyT lore -> Result -- | Type alias for namespace reasons. type Body = BodyT -- | A primitive operation that returns something of known size and does -- not itself contain any bindings. data BasicOp lore -- | A variable or constant. SubExp :: SubExp -> BasicOp lore -- | Semantically and operationally just identity, but is -- invisible/impenetrable to optimisations (hopefully). This is just a -- hack to avoid optimisation (so, to work around compiler limitations). Opaque :: SubExp -> BasicOp lore -- | Array literals, e.g., [ [1+x, 3], [2, 1+4] ]. Second arg is -- the element type of the rows of the array. Scalar operations ArrayLit :: [SubExp] -> Type -> BasicOp lore -- | Unary operation. UnOp :: UnOp -> SubExp -> BasicOp lore -- | Binary operation. BinOp :: BinOp -> SubExp -> SubExp -> BasicOp lore -- | Comparison - result type is always boolean. CmpOp :: CmpOp -> SubExp -> SubExp -> BasicOp lore -- | Conversion "casting". ConvOp :: ConvOp -> SubExp -> BasicOp lore -- | Turn a boolean into a certificate, halting the program with the given -- error message if the boolean is false. Assert :: SubExp -> ErrorMsg SubExp -> (SrcLoc, [SrcLoc]) -> BasicOp lore -- | The certificates for bounds-checking are part of the Stm. Index :: VName -> Slice SubExp -> BasicOp lore -- | An in-place update of the given array at the given position. Consumes -- the array. Update :: VName -> Slice SubExp -> SubExp -> BasicOp lore -- | concat0([1],[2, 3, 4]) = [1, 2, 3, 4]@. Concat :: Int -> VName -> [VName] -> SubExp -> BasicOp lore -- | Copy the given array. The result will not alias anything. Copy :: VName -> BasicOp lore -- | Manifest an array with dimensions represented in the given order. The -- result will not alias anything. Manifest :: [Int] -> VName -> BasicOp lore -- | iota(n, x, s) = [x,x+s,..,x+(n-1)*s]. -- -- The IntType indicates the type of the array returned and the -- offset/stride arguments, but not the length argument. Iota :: SubExp -> SubExp -> SubExp -> IntType -> BasicOp lore -- |
-- replicate([3][2],1) = [[1,1], [1,1], [1,1]] --Replicate :: Shape -> SubExp -> BasicOp lore -- | Repeat each dimension of the input array some number of times, given -- by the corresponding shape. For an array of rank k, the list -- must contain k shapes. A shape may be empty (in which case -- the dimension is not repeated, but it is still present). The last -- shape indicates the amount of extra innermost dimensions. All other -- extra dimensions are added *before* the original dimension. Repeat :: [Shape] -> Shape -> VName -> BasicOp lore -- | Create array of given type and shape, with undefined elements. Scratch :: PrimType -> [SubExp] -> BasicOp lore -- | 1st arg is the new shape, 2nd arg is the input array *) Reshape :: ShapeChange SubExp -> VName -> BasicOp lore -- | Permute the dimensions of the input array. The list of integers is a -- list of dimensions (0-indexed), which must be a permutation of -- [0,n-1], where n is the number of dimensions in the -- input array. Rearrange :: [Int] -> VName -> BasicOp lore -- | Rotate the dimensions of the input array. The list of subexpressions -- specify how much each dimension is rotated. The length of this list -- must be equal to the rank of the array. Rotate :: [SubExp] -> VName -> BasicOp lore -- | First variable is the flag array, second is the element arrays. If no -- arrays are given, the returned offsets are zero, and no arrays are -- returned. Partition :: Int -> VName -> [VName] -> BasicOp lore -- | Various unary operators. It is a bit ad-hoc what is a unary operator -- and what is a built-in function. Perhaps these should all go away -- eventually. data UnOp -- | E.g., ! True == False. Not :: UnOp -- | E.g., ~(~1) = 1. Complement :: IntType -> UnOp -- | abs(-2) = 2. Abs :: IntType -> UnOp -- | fabs(-2.0) = 2.0. FAbs :: FloatType -> UnOp -- | Signed sign function: ssignum(-2) = -1. SSignum :: IntType -> UnOp -- | Unsigned sign function: usignum(2) = 1. USignum :: IntType -> UnOp -- | Binary operators. These correspond closely to the binary operators in -- LLVM. Most are parametrised by their expected input and output types. data BinOp -- | Integer addition. Add :: IntType -> BinOp -- | Floating-point addition. FAdd :: FloatType -> BinOp -- | Integer subtraction. Sub :: IntType -> BinOp -- | Floating-point subtraction. FSub :: FloatType -> BinOp -- | Integer multiplication. Mul :: IntType -> BinOp -- | Floating-point multiplication. FMul :: FloatType -> BinOp -- | Unsigned integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. UDiv :: IntType -> BinOp -- | Signed integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. SDiv :: IntType -> BinOp -- | Floating-point division. FDiv :: FloatType -> BinOp -- | Unsigned integer modulus; the countepart to UDiv. UMod :: IntType -> BinOp -- | Signed integer modulus; the countepart to SDiv. SMod :: IntType -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- sdiv instruction in LLVM. SQuot :: IntType -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- srem instruction in LLVM. SRem :: IntType -> BinOp -- | Returns the smallest of two signed integers. SMin :: IntType -> BinOp -- | Returns the smallest of two unsigned integers. UMin :: IntType -> BinOp -- | Returns the smallest of two floating-point numbers. FMin :: FloatType -> BinOp -- | Returns the greatest of two signed integers. SMax :: IntType -> BinOp -- | Returns the greatest of two unsigned integers. UMax :: IntType -> BinOp -- | Returns the greatest of two floating-point numbers. FMax :: FloatType -> BinOp -- | Left-shift. Shl :: IntType -> BinOp -- | Logical right-shift, zero-extended. LShr :: IntType -> BinOp -- | Arithmetic right-shift, sign-extended. AShr :: IntType -> BinOp -- | Bitwise and. And :: IntType -> BinOp -- | Bitwise or. Or :: IntType -> BinOp -- | Bitwise exclusive-or. Xor :: IntType -> BinOp -- | Integer exponentiation. Pow :: IntType -> BinOp -- | Floating-point exponentiation. FPow :: FloatType -> BinOp -- | Boolean and - not short-circuiting. LogAnd :: BinOp -- | Boolean or - not short-circuiting. LogOr :: BinOp -- | Comparison operators are like BinOps, but they return -- PrimTypes. The somewhat ugly constructor names are straight out -- of LLVM. data CmpOp -- | All types equality. CmpEq :: PrimType -> CmpOp -- | Unsigned less than. CmpUlt :: IntType -> CmpOp -- | Unsigned less than or equal. CmpUle :: IntType -> CmpOp -- | Signed less than. CmpSlt :: IntType -> CmpOp -- | Signed less than or equal. CmpSle :: IntType -> CmpOp -- | Floating-point less than. FCmpLt :: FloatType -> CmpOp -- | Floating-point less than or equal. FCmpLe :: FloatType -> CmpOp -- | Boolean less than. CmpLlt :: CmpOp -- | Boolean less than or equal. CmpLle :: CmpOp -- | Conversion operators try to generalise the from t0 x to t1 -- instructions from LLVM. data ConvOp -- | Zero-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. ZExt :: IntType -> IntType -> ConvOp -- | Sign-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. SExt :: IntType -> IntType -> ConvOp -- | Convert value of the former floating-point type to the latter. If the -- new type is smaller, the result is a truncation. FPConv :: FloatType -> FloatType -> ConvOp -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). FPToUI :: FloatType -> IntType -> ConvOp -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). FPToSI :: FloatType -> IntType -> ConvOp -- | Convert an unsigned integer to a floating-point value. UIToFP :: IntType -> FloatType -> ConvOp -- | Convert a signed integer to a floating-point value. SIToFP :: IntType -> FloatType -> ConvOp -- | Convert an integer to a boolean value. Zero becomes false; anything -- else is true. IToB :: IntType -> ConvOp -- | Convert a boolean to an integer. True is converted to 1 and False to -- 0. BToI :: IntType -> ConvOp -- | The new dimension in a Reshape-like operation. This allows us -- to disambiguate "real" reshapes, that change the actual shape of the -- array, from type coercions that are just present to make the types -- work out. data DimChange d -- | The new dimension is guaranteed to be numerically equal to the old -- one. DimCoercion :: d -> DimChange d -- | The new dimension is not necessarily numerically equal to the old one. DimNew :: d -> DimChange d -- | A list of DimChanges, indicating the new dimensions of an -- array. type ShapeChange d = [DimChange d] -- | The root Futhark expression type. The ExpT constructor contains -- a lore-specific operation. Do-loops, branches and function calls are -- special. Everything else is a simple BasicOp. data ExpT lore -- | A simple (non-recursive) operation. BasicOp :: BasicOp lore -> ExpT lore Apply :: Name -> [(SubExp, Diet)] -> [RetType lore] -> (Safety, SrcLoc, [SrcLoc]) -> ExpT lore If :: SubExp -> BodyT lore -> BodyT lore -> IfAttr (BranchType lore) -> ExpT lore -- | loop {a} = {v} (for i < n|while b) do b. The merge -- parameters are divided into context and value part. DoLoop :: [(FParam lore, SubExp)] -> [(FParam lore, SubExp)] -> LoopForm lore -> BodyT lore -> ExpT lore Op :: Op lore -> ExpT lore -- | A type alias for namespace control. type Exp = ExpT -- | For-loop or while-loop? data LoopForm lore ForLoop :: VName -> IntType -> SubExp -> [(LParam lore, VName)] -> LoopForm lore WhileLoop :: VName -> LoopForm lore -- | Data associated with a branch. data IfAttr rt IfAttr :: [rt] -> IfSort -> IfAttr rt [ifReturns] :: IfAttr rt -> [rt] [ifSort] :: IfAttr rt -> IfSort data IfSort -- | An ordinary branch. IfNormal :: IfSort -- | A branch where the "true" case is what we are actually interested in, -- and the "false" case is only present as a fallback for when the true -- case cannot be safely evaluated. the compiler is permitted to optimise -- away the branch if the true case contains only safe statements. IfFallback :: IfSort -- | Whether something is safe or unsafe (mostly function calls, and in the -- context of whether operations are dynamically checked). When we inline -- an Unsafe function, we remove all safety checks in its body. -- The Ord instance picks Unsafe as being less than -- Safe. data Safety Unsafe :: Safety Safe :: Safety -- | Anonymous function for use in a SOAC. data LambdaT lore Lambda :: [LParam lore] -> BodyT lore -> [Type] -> LambdaT lore [lambdaParams] :: LambdaT lore -> [LParam lore] [lambdaBody] :: LambdaT lore -> BodyT lore [lambdaReturnType] :: LambdaT lore -> [Type] -- | Type alias for namespacing reasons. type Lambda = LambdaT -- | A function parameter. data ParamT attr Param :: VName -> attr -> ParamT attr -- | Name of the parameter. [paramName] :: ParamT attr -> VName -- | Function parameter attribute. [paramAttr] :: ParamT attr -> attr type FParam lore = ParamT (FParamAttr lore) type LParam lore = ParamT (LParamAttr lore) -- | Function Declarations data FunDefT lore FunDef :: Maybe EntryPoint -> Name -> [RetType lore] -> [FParam lore] -> BodyT lore -> FunDefT lore -- | Contains a value if this function is an entry point. [funDefEntryPoint] :: FunDefT lore -> Maybe EntryPoint [funDefName] :: FunDefT lore -> Name [funDefRetType] :: FunDefT lore -> [RetType lore] [funDefParams] :: FunDefT lore -> [FParam lore] [funDefBody] :: FunDefT lore -> BodyT lore -- | Type alias for namespace reasons. type FunDef = FunDefT -- | Information about the parameters and return value of an entry point. -- The first element is for parameters, the second for return value. type EntryPoint = ([EntryPointType], [EntryPointType]) -- | Every entry point argument and return value has an annotation -- indicating how it maps to the original source program type. data EntryPointType -- | Is an unsigned integer or array of unsigned integers. TypeUnsigned :: EntryPointType -- | A black box type comprising this many core values. The string is a -- human-readable description with no other semantics. TypeOpaque :: String -> Int -> EntryPointType -- | Maps directly. TypeDirect :: EntryPointType -- | An entire Futhark program. newtype ProgT lore Prog :: [FunDef lore] -> ProgT lore [progFunctions] :: ProgT lore -> [FunDef lore] -- | Type alias for namespace reasons. type Prog = ProgT oneStm :: Stm lore -> Stms lore stmsFromList :: [Stm lore] -> Stms lore stmsToList :: Stms lore -> [Stm lore] stmsHead :: Stms lore -> Maybe (Stm lore, Stms lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Show.Show (Futhark.Representation.AST.Syntax.ProgT lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Ord (Futhark.Representation.AST.Syntax.ProgT lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Eq (Futhark.Representation.AST.Syntax.ProgT lore) instance GHC.Classes.Ord Futhark.Representation.AST.Syntax.EntryPointType instance GHC.Show.Show Futhark.Representation.AST.Syntax.EntryPointType instance GHC.Classes.Eq Futhark.Representation.AST.Syntax.EntryPointType instance GHC.Classes.Ord rt => GHC.Classes.Ord (Futhark.Representation.AST.Syntax.IfAttr rt) instance GHC.Show.Show rt => GHC.Show.Show (Futhark.Representation.AST.Syntax.IfAttr rt) instance GHC.Classes.Eq rt => GHC.Classes.Eq (Futhark.Representation.AST.Syntax.IfAttr rt) instance GHC.Classes.Ord Futhark.Representation.AST.Syntax.IfSort instance GHC.Show.Show Futhark.Representation.AST.Syntax.IfSort instance GHC.Classes.Eq Futhark.Representation.AST.Syntax.IfSort instance GHC.Show.Show Futhark.Representation.AST.Syntax.Safety instance GHC.Classes.Ord Futhark.Representation.AST.Syntax.Safety instance GHC.Classes.Eq Futhark.Representation.AST.Syntax.Safety instance GHC.Show.Show (Futhark.Representation.AST.Syntax.BasicOp lore) instance GHC.Classes.Ord (Futhark.Representation.AST.Syntax.BasicOp lore) instance GHC.Classes.Eq (Futhark.Representation.AST.Syntax.BasicOp lore) instance GHC.Show.Show d => GHC.Show.Show (Futhark.Representation.AST.Syntax.DimChange d) instance GHC.Classes.Ord d => GHC.Classes.Ord (Futhark.Representation.AST.Syntax.DimChange d) instance GHC.Classes.Eq d => GHC.Classes.Eq (Futhark.Representation.AST.Syntax.DimChange d) instance GHC.Classes.Eq attr => GHC.Classes.Eq (Futhark.Representation.AST.Syntax.StmAux attr) instance GHC.Show.Show attr => GHC.Show.Show (Futhark.Representation.AST.Syntax.StmAux attr) instance GHC.Classes.Ord attr => GHC.Classes.Ord (Futhark.Representation.AST.Syntax.StmAux attr) instance GHC.Classes.Eq attr => GHC.Classes.Eq (Futhark.Representation.AST.Syntax.PatternT attr) instance GHC.Show.Show attr => GHC.Show.Show (Futhark.Representation.AST.Syntax.PatternT attr) instance GHC.Classes.Ord attr => GHC.Classes.Ord (Futhark.Representation.AST.Syntax.PatternT attr) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Ord (Futhark.Representation.AST.Syntax.Stm lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Show.Show (Futhark.Representation.AST.Syntax.Stm lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Eq (Futhark.Representation.AST.Syntax.Stm lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Ord (Futhark.Representation.AST.Syntax.BodyT lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Show.Show (Futhark.Representation.AST.Syntax.BodyT lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Eq (Futhark.Representation.AST.Syntax.BodyT lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Eq (Futhark.Representation.AST.Syntax.ExpT lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Show.Show (Futhark.Representation.AST.Syntax.ExpT lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Ord (Futhark.Representation.AST.Syntax.ExpT lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Eq (Futhark.Representation.AST.Syntax.LoopForm lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Show.Show (Futhark.Representation.AST.Syntax.LoopForm lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Ord (Futhark.Representation.AST.Syntax.LoopForm lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Eq (Futhark.Representation.AST.Syntax.LambdaT lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Show.Show (Futhark.Representation.AST.Syntax.LambdaT lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Ord (Futhark.Representation.AST.Syntax.LambdaT lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Eq (Futhark.Representation.AST.Syntax.FunDefT lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Show.Show (Futhark.Representation.AST.Syntax.FunDefT lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Ord (Futhark.Representation.AST.Syntax.FunDefT lore) instance GHC.Base.Functor Futhark.Representation.AST.Syntax.DimChange instance Data.Foldable.Foldable Futhark.Representation.AST.Syntax.DimChange instance Data.Traversable.Traversable Futhark.Representation.AST.Syntax.DimChange instance GHC.Base.Functor Futhark.Representation.AST.Syntax.PatternT instance GHC.Base.Semigroup (Futhark.Representation.AST.Syntax.PatternT attr) instance GHC.Base.Monoid (Futhark.Representation.AST.Syntax.PatternT attr) module Futhark.Representation.AST.Attributes.Reshape -- | The new dimension. newDim :: DimChange d -> d -- | The new dimensions resulting from a reshape operation. newDims :: ShapeChange d -> [d] -- | Construct a Reshape where all dimension changes are -- DimCoercions. -- -- The new shape resulting from a reshape operation. newShape :: ShapeChange SubExp -> Shape shapeCoerce :: [SubExp] -> VName -> Exp lore -- | Construct a pair suitable for a Repeat. repeatShapes :: [Shape] -> Type -> ([Shape], Shape) -- | reshapeOuter newshape n oldshape returns a Reshape -- expression that replaces the outer n dimensions of -- oldshape with newshape. reshapeOuter :: ShapeChange SubExp -> Int -> Shape -> ShapeChange SubExp -- | reshapeInner newshape n oldshape returns a Reshape -- expression that replaces the inner m-n dimensions (where -- m is the rank of oldshape) of src with -- newshape. reshapeInner :: ShapeChange SubExp -> Int -> Shape -> ShapeChange SubExp -- | Modify the shape of an array type as Repeat would do repeatDims :: [Shape] -> Shape -> Type -> Type -- | If the shape change is nothing but shape coercions, return the new -- dimensions. Otherwise, return Nothing. shapeCoercion :: ShapeChange d -> Maybe [d] -- | fuseReshape s1 s2 creates a new ShapeChange that is -- semantically the same as first applying s1 and then -- s2. This may take advantage of properties of -- DimCoercion versus DimNew to preserve information. fuseReshape :: Eq d => ShapeChange d -> ShapeChange d -> ShapeChange d -- | fuseReshapes s ss creates a fused ShapeChange that is -- logically the same as first applying s and then the changes -- in ss from left to right. fuseReshapes :: (Eq d, Foldable t) => ShapeChange d -> t (ShapeChange d) -> ShapeChange d -- | Given concrete information about the shape of the source array, -- convert some DimNews into DimCoercions. informReshape :: Eq d => [d] -> ShapeChange d -> ShapeChange d -- | reshapeIndex to_dims from_dims is transforms the index list -- is (which is into an array of shape from_dims) into -- an index list is', which is into an array of shape -- to_dims. is must have the same length as -- from_dims, and is' will have the same length as -- to_dims. reshapeIndex :: IntegralExp num => [num] -> [num] -> [num] -> [num] -- | flattenIndex dims is computes the flat index of is -- into an array with dimensions dims. The length of -- dims and is must be the same. flattenIndex :: IntegralExp num => [num] -> [num] -> num -- | unflattenIndex dims i computes a list of indices into an -- array with dimension dims given the flat index i. -- The resulting list will have the same size as dims. unflattenIndex :: IntegralExp num => [num] -> num -> [num] -- | Given a length n list of dimensions dims, -- sizeSizes dims will compute a length n+1 list of the -- size of each possible array slice. The first element of this list will -- be the product of dims, and the last element will be 1. sliceSizes :: IntegralExp num => [num] -> [num] -- | Inspecing and modifying PatternTs, function parameters and -- pattern elements. module Futhark.Representation.AST.Attributes.Patterns -- | An Ident corresponding to a parameter. paramIdent :: Typed attr => ParamT attr -> Ident -- | The Type of a parameter. paramType :: Typed attr => ParamT attr -> Type -- | The DeclType of a parameter. paramDeclType :: DeclTyped attr => ParamT attr -> DeclType -- | An Ident corresponding to a pattern element. patElemIdent :: Typed attr => PatElemT attr -> Ident -- | The type of a name bound by a PatElem. patElemType :: Typed attr => PatElemT attr -> Type -- | Set the lore of a PatElem. setPatElemLore :: PatElemT oldattr -> newattr -> PatElemT newattr -- | All pattern elements in the pattern - context first, then values. patternElements :: PatternT attr -> [PatElemT attr] -- | Return a list of the Idents bound by the PatternT. patternIdents :: Typed attr => PatternT attr -> [Ident] -- | Return a list of the context Idents bound by the -- PatternT. patternContextIdents :: Typed attr => PatternT attr -> [Ident] -- | Return a list of the value Idents bound by the PatternT. patternValueIdents :: Typed attr => PatternT attr -> [Ident] -- | Return a list of the Names bound by the PatternT. patternNames :: PatternT attr -> [VName] -- | Return a list of the Names bound by the value part of the -- PatternT. patternValueNames :: PatternT attr -> [VName] -- | Return a list of the Names bound by the context part of the -- PatternT. patternContextNames :: PatternT attr -> [VName] -- | Return a list of the typess bound by the PatternT. patternTypes :: Typed attr => PatternT attr -> [Type] -- | Return a list of the Typess bound by the value part of the -- PatternT. patternValueTypes :: Typed attr => PatternT attr -> [Type] -- | Return a list of the ExtTypess bound by the value part of the -- PatternT, with existentials where the sizes are part of the -- context part of the PatternT. patternExtTypes :: Typed attr => PatternT attr -> [ExtType] -- | Return the number of names bound by the PatternT. patternSize :: PatternT attr -> Int -- | Create a pattern using Type as the attribute. basicPattern :: [Ident] -> [Ident] -> PatternT Type -- | Futhark prettyprinter. This module defines Pretty instances for -- the AST defined in Futhark.Representation.AST.Syntax, but also -- a number of convenience functions if you don't want to use the -- interface from Pretty. module Futhark.Representation.AST.Pretty -- | Prettyprint a list enclosed in curly braces. prettyTuple :: Pretty a => [a] -> String -- | Prettyprint a value, wrapped to 80 characters. pretty :: Pretty a => a -> String -- | Class for values that may have some prettyprinted annotation. class PrettyAnnot a ppAnnot :: PrettyAnnot a => a -> Maybe Doc -- | The class of lores whose annotations can be prettyprinted. class (Annotations lore, Pretty (RetType lore), Pretty (BranchType lore), Pretty (ParamT (FParamAttr lore)), Pretty (ParamT (LParamAttr lore)), Pretty (PatElemT (LetAttr lore)), PrettyAnnot (PatElem lore), PrettyAnnot (FParam lore), PrettyAnnot (LParam lore), Pretty (Op lore)) => PrettyLore lore ppExpLore :: PrettyLore lore => ExpAttr lore -> Exp lore -> Maybe Doc ppTuple' :: Pretty a => [a] -> Doc bindingAnnotation :: PrettyLore lore => Stm lore -> Doc -> Doc instance Futhark.Representation.AST.Pretty.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.Stms lore) instance Futhark.Representation.AST.Pretty.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.Body lore) instance Futhark.Representation.AST.Pretty.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.Stm lore) instance Futhark.Representation.AST.Pretty.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.Exp lore) instance Futhark.Representation.AST.Pretty.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.Lambda lore) instance Futhark.Representation.AST.Pretty.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.FunDef lore) instance Futhark.Representation.AST.Pretty.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.Prog lore) instance Futhark.Representation.AST.Pretty.PrettyAnnot (Futhark.Representation.AST.Syntax.Core.PatElemT (Futhark.Representation.AST.Syntax.Core.TypeBase shape u)) instance Futhark.Representation.AST.Pretty.PrettyAnnot (Futhark.Representation.AST.Syntax.Core.ParamT (Futhark.Representation.AST.Syntax.Core.TypeBase shape u)) instance Futhark.Representation.AST.Pretty.PrettyAnnot () instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Core.VName instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Representation.AST.Syntax.Core.NoUniqueness instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Core.Commutativity instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Representation.AST.Syntax.Core.Shape instance Text.PrettyPrint.Mainland.Class.Pretty a => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.Core.Ext a) instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Representation.AST.Syntax.Core.ExtShape instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Representation.AST.Syntax.Core.Space instance Text.PrettyPrint.Mainland.Class.Pretty u => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.Core.TypeBase Futhark.Representation.AST.Syntax.Core.Shape u) instance Text.PrettyPrint.Mainland.Class.Pretty u => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.Core.TypeBase Futhark.Representation.AST.Syntax.Core.ExtShape u) instance Text.PrettyPrint.Mainland.Class.Pretty u => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.Core.TypeBase Futhark.Representation.AST.Syntax.Core.Rank u) instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Representation.AST.Syntax.Core.Ident instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Representation.AST.Syntax.Core.SubExp instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Representation.AST.Syntax.Core.Certificates instance Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.Core.PatElemT attr) => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.PatternT attr) instance Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.Core.PatElemT b) => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.Core.PatElemT (a, b)) instance Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.Core.PatElemT Futhark.Representation.AST.Syntax.Core.Type) instance Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.Core.ParamT b) => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.Core.ParamT (a, b)) instance Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.Core.ParamT Futhark.Representation.AST.Syntax.Core.DeclType) instance Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.Core.ParamT Futhark.Representation.AST.Syntax.Core.Type) instance Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.BasicOp lore) instance Text.PrettyPrint.Mainland.Class.Pretty a => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.Core.ErrorMsg a) instance Text.PrettyPrint.Mainland.Class.Pretty d => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.DimChange d) instance Text.PrettyPrint.Mainland.Class.Pretty d => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.Core.DimIndex d) module Futhark.Representation.Kernels.Sizes -- | The class of some kind of configurable size. Each class may impose -- constraints on the valid values. data SizeClass SizeThreshold :: KernelPath -> SizeClass SizeGroup :: SizeClass SizeNumGroups :: SizeClass SizeTile :: SizeClass -- | An indication of which comparisons have been performed to get to this -- point, as well as the result of each comparison. type KernelPath = [(VName, Bool)] instance GHC.Show.Show Futhark.Representation.Kernels.Sizes.SizeClass instance GHC.Classes.Ord Futhark.Representation.Kernels.Sizes.SizeClass instance GHC.Classes.Eq Futhark.Representation.Kernels.Sizes.SizeClass instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Representation.Kernels.Sizes.SizeClass -- | This module defines the concept of a type environment as a mapping -- from variable names to Types. Convenience facilities are also -- provided to communicate that some monad or applicative functor -- maintains type information. module Futhark.Representation.AST.Attributes.Scope -- | The class of applicative functors (or more common in practice: monads) -- that permit the lookup of variable types. A default method for -- lookupType exists, which is sufficient (if not always maximally -- efficient, and using error to fail) when askScope is -- defined. class (Applicative m, Annotations lore) => HasScope lore m | m -> lore -- | Return the type of the given variable, or fail if it is not in the -- type environment. lookupType :: HasScope lore m => VName -> m Type -- | Return the info of the given variable, or fail if it is not in the -- type environment. lookupInfo :: HasScope lore m => VName -> m (NameInfo lore) -- | Return the type environment contained in the applicative functor. askScope :: HasScope lore m => m (Scope lore) -- | Return the result of applying some function to the type environment. asksScope :: HasScope lore m => (Scope lore -> a) -> m a -- | How some name in scope was bound. data NameInfo lore LetInfo :: LetAttr lore -> NameInfo lore FParamInfo :: FParamAttr lore -> NameInfo lore LParamInfo :: LParamAttr lore -> NameInfo lore IndexInfo :: IntType -> NameInfo lore -- | The class of monads that not only provide a Scope, but also the -- ability to locally extend it. A Reader containing a -- Scope is the prototypical example of such a monad. class (HasScope lore m, Monad m) => LocalScope lore m -- | Run a computation with an extended type environment. Note that this is -- intended to *add* to the current type environment, it does not replace -- it. localScope :: LocalScope lore m => Scope lore -> m a -> m a -- | A scope is a mapping from variable names to information about that -- name. type Scope lore = Map VName (NameInfo lore) -- | The class of things that can provide a scope. There is no overarching -- rule for what this means. For a Stm, it is the corresponding -- pattern. For a LambdaT, is is the parameters (including index). class Scoped lore a | a -> lore scopeOf :: Scoped lore a => a -> Scope lore inScopeOf :: (Scoped lore a, LocalScope lore m) => a -> m b -> m b scopeOfLParams :: LParamAttr lore ~ attr => [ParamT attr] -> Scope lore scopeOfFParams :: FParamAttr lore ~ attr => [ParamT attr] -> Scope lore scopeOfPattern :: LetAttr lore ~ attr => PatternT attr -> Scope lore scopeOfPatElem :: LetAttr lore ~ attr => PatElemT attr -> Scope lore type SameScope lore1 lore2 = (LetAttr lore1 ~ LetAttr lore2, FParamAttr lore1 ~ FParamAttr lore2, LParamAttr lore1 ~ LParamAttr lore2) -- | If two scopes are really the same, then you can convert one to the -- other. castScope :: SameScope fromlore tolore => Scope fromlore -> Scope tolore castNameInfo :: SameScope fromlore tolore => NameInfo fromlore -> NameInfo tolore -- | A monad transformer that carries around an extended Scope. Its -- lookupType method will first look in the extended Scope, -- and then use the lookupType method of the underlying monad. data ExtendedScope lore m a -- | Run a computation in the extended type environment. extendedScope :: ExtendedScope lore m a -> Scope lore -> m a instance GHC.Base.Monad m => Control.Monad.Reader.Class.MonadReader (Futhark.Representation.AST.Attributes.Scope.Scope lore) (Futhark.Representation.AST.Attributes.Scope.ExtendedScope lore m) instance GHC.Base.Monad m => GHC.Base.Monad (Futhark.Representation.AST.Attributes.Scope.ExtendedScope lore m) instance GHC.Base.Applicative m => GHC.Base.Applicative (Futhark.Representation.AST.Attributes.Scope.ExtendedScope lore m) instance GHC.Base.Functor m => GHC.Base.Functor (Futhark.Representation.AST.Attributes.Scope.ExtendedScope lore m) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Show.Show (Futhark.Representation.AST.Attributes.Scope.NameInfo lore) instance (Futhark.Representation.AST.Attributes.Scope.HasScope lore m, GHC.Base.Monad m) => Futhark.Representation.AST.Attributes.Scope.HasScope lore (Futhark.Representation.AST.Attributes.Scope.ExtendedScope lore m) instance Futhark.Representation.AST.Attributes.Scope.Scoped lore a => Futhark.Representation.AST.Attributes.Scope.Scoped lore [a] instance Futhark.Representation.AST.Attributes.Scope.Scoped lore (Futhark.Representation.AST.Syntax.Stms lore) instance Futhark.Representation.AST.Attributes.Scope.Scoped lore (Futhark.Representation.AST.Syntax.Stm lore) instance Futhark.Representation.AST.Attributes.Scope.Scoped lore (Futhark.Representation.AST.Syntax.FunDef lore) instance Futhark.Representation.AST.Attributes.Scope.Scoped lore (Language.Futhark.Core.VName, Futhark.Representation.AST.Attributes.Scope.NameInfo lore) instance Futhark.Representation.AST.Attributes.Scope.Scoped lore (Futhark.Representation.AST.Syntax.LoopForm lore) instance Futhark.Representation.AST.Attributes.Scope.Scoped lore (Futhark.Representation.AST.Syntax.Lambda lore) instance (GHC.Base.Monad m, Futhark.Representation.AST.Attributes.Scope.LocalScope lore m) => Futhark.Representation.AST.Attributes.Scope.LocalScope lore (Control.Monad.Trans.Except.ExceptT e m) instance (GHC.Base.Applicative m, GHC.Base.Monad m, Futhark.Representation.AST.Annotations.Annotations lore) => Futhark.Representation.AST.Attributes.Scope.LocalScope lore (Control.Monad.Trans.Reader.ReaderT (Futhark.Representation.AST.Attributes.Scope.Scope lore) m) instance (GHC.Base.Applicative m, GHC.Base.Monad m, GHC.Base.Monoid w, Futhark.Representation.AST.Annotations.Annotations lore) => Futhark.Representation.AST.Attributes.Scope.LocalScope lore (Control.Monad.Trans.RWS.Strict.RWST (Futhark.Representation.AST.Attributes.Scope.Scope lore) w s m) instance (GHC.Base.Applicative m, GHC.Base.Monad m, GHC.Base.Monoid w, Futhark.Representation.AST.Annotations.Annotations lore) => Futhark.Representation.AST.Attributes.Scope.LocalScope lore (Control.Monad.Trans.RWS.Lazy.RWST (Futhark.Representation.AST.Attributes.Scope.Scope lore) w s m) instance (GHC.Base.Applicative m, GHC.Base.Monad m, Futhark.Representation.AST.Annotations.Annotations lore) => Futhark.Representation.AST.Attributes.Scope.HasScope lore (Control.Monad.Trans.Reader.ReaderT (Futhark.Representation.AST.Attributes.Scope.Scope lore) m) instance (GHC.Base.Monad m, Futhark.Representation.AST.Attributes.Scope.HasScope lore m) => Futhark.Representation.AST.Attributes.Scope.HasScope lore (Control.Monad.Trans.Except.ExceptT e m) instance (GHC.Base.Applicative m, GHC.Base.Monad m, GHC.Base.Monoid w, Futhark.Representation.AST.Annotations.Annotations lore) => Futhark.Representation.AST.Attributes.Scope.HasScope lore (Control.Monad.Trans.RWS.Strict.RWST (Futhark.Representation.AST.Attributes.Scope.Scope lore) w s m) instance (GHC.Base.Applicative m, GHC.Base.Monad m, GHC.Base.Monoid w, Futhark.Representation.AST.Annotations.Annotations lore) => Futhark.Representation.AST.Attributes.Scope.HasScope lore (Control.Monad.Trans.RWS.Lazy.RWST (Futhark.Representation.AST.Attributes.Scope.Scope lore) w s m) instance Futhark.Representation.AST.Annotations.Annotations lore => Futhark.Representation.AST.Attributes.Types.Typed (Futhark.Representation.AST.Attributes.Scope.NameInfo lore) -- | Functions for generic traversals across Futhark syntax trees. The -- motivation for this module came from dissatisfaction with rewriting -- the same trivial tree recursions for every module. A possible -- alternative would be to use normal "Scrap your -- boilerplate"-techniques, but these are rejected for two reasons: -- --
-- instance MonadFreshNames vn MyMonad where -- getNameSource = get -- putNameSource = put --class (Applicative m, Monad m) => MonadFreshNames m getNameSource :: MonadFreshNames m => m VNameSource putNameSource :: MonadFreshNames m => VNameSource -> m () -- | Run a computation needing a fresh name source and returning a new one, -- using getNameSource and putNameSource before and after -- the computation. modifyNameSource :: MonadFreshNames m => (VNameSource -> (a, VNameSource)) -> m a -- | Produce a fresh name, using the given name as a template. newName :: MonadFreshNames m => VName -> m VName -- | As newName, but takes a String for the name template. newNameFromString :: MonadFreshNames m => String -> m VName -- | Produce a fresh ID, using the given base name as a template. newID :: MonadFreshNames m => Name -> m VName -- | As newID, but takes a String for the name template. newIDFromString :: MonadFreshNames m => String -> m VName -- | Produce a fresh VName, using the given base name as a template. newVName :: MonadFreshNames m => String -> m VName -- | Produce a fresh VName, using the given name as a template, but -- possibly appending something more.. newVName' :: MonadFreshNames m => (String -> String) -> String -> m VName -- | Produce a fresh Ident, using the given name as a template. newIdent :: MonadFreshNames m => String -> Type -> m Ident -- | Produce a fresh Ident, using the given Ident as a -- template, but possibly modifying the name. newIdent' :: MonadFreshNames m => (String -> String) -> Ident -> m Ident -- | Produce several Idents, using the given name as a template, -- based on a list of types. newIdents :: MonadFreshNames m => String -> [Type] -> m [Ident] -- | Produce a fresh ParamT, using the given name as a template. newParam :: MonadFreshNames m => String -> attr -> m (Param attr) -- | Produce a fresh ParamT, using the given ParamT as a -- template, but possibly modifying the name. newParam' :: MonadFreshNames m => (String -> String) -> Param attr -> m (Param attr) -- | A name source is conceptually an infinite sequence of names with no -- repeating entries. In practice, when asked for a name, the name source -- will return the name along with a new name source, which should then -- be used in place of the original. -- -- The Ord instance is based on how many names have been extracted -- from the name source. data VNameSource -- | A blank name source. blankNameSource :: VNameSource -- | A new name source that starts counting from the given number. newNameSource :: Int -> VNameSource -- | Produce a fresh VName, using the given base name as a template. newVNameFromName :: VNameSource -> Name -> (VName, VNameSource) instance (GHC.Base.Applicative im, GHC.Base.Monad im) => Futhark.MonadFreshNames.MonadFreshNames (Control.Monad.Trans.State.Lazy.StateT Futhark.FreshNames.VNameSource im) instance (GHC.Base.Applicative im, GHC.Base.Monad im) => Futhark.MonadFreshNames.MonadFreshNames (Control.Monad.Trans.State.Strict.StateT Futhark.FreshNames.VNameSource im) instance (GHC.Base.Applicative im, GHC.Base.Monad im, GHC.Base.Monoid w) => Futhark.MonadFreshNames.MonadFreshNames (Control.Monad.Trans.RWS.Lazy.RWST r w Futhark.FreshNames.VNameSource im) instance (GHC.Base.Applicative im, GHC.Base.Monad im, GHC.Base.Monoid w) => Futhark.MonadFreshNames.MonadFreshNames (Control.Monad.Trans.RWS.Strict.RWST r w Futhark.FreshNames.VNameSource im) instance Futhark.MonadFreshNames.MonadFreshNames m => Futhark.MonadFreshNames.MonadFreshNames (Control.Monad.Trans.Reader.ReaderT s m) instance (Futhark.MonadFreshNames.MonadFreshNames m, GHC.Base.Monoid s) => Futhark.MonadFreshNames.MonadFreshNames (Control.Monad.Trans.Writer.Lazy.WriterT s m) instance (Futhark.MonadFreshNames.MonadFreshNames m, GHC.Base.Monoid s) => Futhark.MonadFreshNames.MonadFreshNames (Control.Monad.Trans.Writer.Strict.WriterT s m) instance Futhark.MonadFreshNames.MonadFreshNames m => Futhark.MonadFreshNames.MonadFreshNames (Control.Monad.Trans.Maybe.MaybeT m) instance Futhark.MonadFreshNames.MonadFreshNames m => Futhark.MonadFreshNames.MonadFreshNames (Control.Monad.Trans.Except.ExceptT e m) -- | This module provides facilities for transforming Futhark programs such -- that names are unique, via the renameProg function. -- Additionally, the module also supports adding integral "tags" to names -- (incarnated as the ID type), in order to support more -- efficient comparisons and renamings. This is done by tagProg. -- The intent is that you call tagProg once at some early stage, -- then use renameProg from then on. Functions are also provided -- for removing the tags again from expressions, patterns and typs. module Futhark.Transform.Rename -- | Rename variables such that each is unique. The semantics of the -- program are unaffected, under the assumption that the program was -- correct to begin with. In particular, the renaming may make an invalid -- program valid. renameProg :: (Renameable lore, MonadFreshNames m) => Prog lore -> m (Prog lore) -- | Rename bound variables such that each is unique. The semantics of the -- expression is unaffected, under the assumption that the expression was -- correct to begin with. Any free variables are left untouched. renameExp :: (Renameable lore, MonadFreshNames m) => Exp lore -> m (Exp lore) -- | Rename bound variables such that each is unique. The semantics of the -- binding is unaffected, under the assumption that the binding was -- correct to begin with. Any free variables are left untouched, as are -- the names in the pattern of the binding. renameStm :: (Renameable lore, MonadFreshNames m) => Stm lore -> m (Stm lore) -- | Rename bound variables such that each is unique. The semantics of the -- body is unaffected, under the assumption that the body was correct to -- begin with. Any free variables are left untouched. renameBody :: (Renameable lore, MonadFreshNames m) => Body lore -> m (Body lore) -- | Rename bound variables such that each is unique. The semantics of the -- lambda is unaffected, under the assumption that the body was correct -- to begin with. Any free variables are left untouched. Note in -- particular that the parameters of the lambda are renamed. renameLambda :: (Renameable lore, MonadFreshNames m) => Lambda lore -> m (Lambda lore) -- | Rename bound variables such that each is unique. The semantics of the -- function is unaffected, under the assumption that the body was correct -- to begin with. Any free variables are left untouched. Note in -- particular that the parameters of the lambda are renamed. renameFun :: (Renameable lore, MonadFreshNames m) => FunDef lore -> m (FunDef lore) -- | Produce an equivalent pattern but with each pattern element given a -- new name. renamePattern :: (Rename attr, MonadFreshNames m) => PatternT attr -> m (PatternT attr) -- | The monad in which renaming is performed. type RenameM = StateT VNameSource (Reader RenameEnv) -- | Perform a renaming using the Substitute instance. This only -- works if the argument does not itself perform any name binding, but it -- can save on boilerplate for simple types. substituteRename :: Substitute a => a -> RenameM a -- | Create a bunch of new names and bind them for substitution. bindingForRename :: [VName] -> RenameM a -> RenameM a -- | Rename some statements, then execute an action with the name -- substitutions induced by the statements active. renamingStms :: Renameable lore => Stms lore -> (Stms lore -> RenameM a) -> RenameM a -- | Members of class Rename can be uniquely renamed. class Rename a -- | Rename the given value such that it does not contain shadowing, and -- has incorporated any substitutions present in the RenameM -- environment. rename :: Rename a => a -> RenameM a -- | Lores in which all annotations are renameable. type Renameable lore = (Rename (LetAttr lore), Rename (ExpAttr lore), Rename (BodyAttr lore), Rename (FParamAttr lore), Rename (LParamAttr lore), Rename (RetType lore), Rename (BranchType lore), Rename (Op lore)) instance Futhark.Transform.Rename.Renameable lore => Futhark.Transform.Rename.Rename (Futhark.Representation.AST.Syntax.FunDef lore) instance Futhark.Transform.Rename.Renameable lore => Futhark.Transform.Rename.Rename (Futhark.Representation.AST.Syntax.Body lore) instance Futhark.Transform.Rename.Renameable lore => Futhark.Transform.Rename.Rename (Futhark.Representation.AST.Syntax.Stm lore) instance Futhark.Transform.Rename.Renameable lore => Futhark.Transform.Rename.Rename (Futhark.Representation.AST.Syntax.Exp lore) instance Futhark.Transform.Rename.Renameable lore => Futhark.Transform.Rename.Rename (Futhark.Representation.AST.Syntax.Lambda lore) instance Futhark.Transform.Rename.Rename Language.Futhark.Core.VName instance Futhark.Transform.Rename.Rename a => Futhark.Transform.Rename.Rename [a] instance (Futhark.Transform.Rename.Rename a, Futhark.Transform.Rename.Rename b) => Futhark.Transform.Rename.Rename (a, b) instance (Futhark.Transform.Rename.Rename a, Futhark.Transform.Rename.Rename b, Futhark.Transform.Rename.Rename c) => Futhark.Transform.Rename.Rename (a, b, c) instance Futhark.Transform.Rename.Rename a => Futhark.Transform.Rename.Rename (GHC.Maybe.Maybe a) instance Futhark.Transform.Rename.Rename GHC.Types.Bool instance Futhark.Transform.Rename.Rename Futhark.Representation.AST.Syntax.Core.Ident instance Futhark.Transform.Rename.Rename Futhark.Representation.AST.Syntax.Core.SubExp instance Futhark.Transform.Rename.Rename attr => Futhark.Transform.Rename.Rename (Futhark.Representation.AST.Syntax.Core.ParamT attr) instance Futhark.Transform.Rename.Rename attr => Futhark.Transform.Rename.Rename (Futhark.Representation.AST.Syntax.PatternT attr) instance Futhark.Transform.Rename.Rename attr => Futhark.Transform.Rename.Rename (Futhark.Representation.AST.Syntax.Core.PatElemT attr) instance Futhark.Transform.Rename.Rename Futhark.Representation.AST.Syntax.Core.Certificates instance Futhark.Transform.Rename.Rename attr => Futhark.Transform.Rename.Rename (Futhark.Representation.AST.Syntax.StmAux attr) instance Futhark.Transform.Rename.Rename shape => Futhark.Transform.Rename.Rename (Futhark.Representation.AST.Syntax.Core.TypeBase shape u) instance Futhark.Transform.Rename.Rename Futhark.Representation.AST.Syntax.Core.Names instance Futhark.Transform.Rename.Rename Futhark.Representation.AST.Syntax.Core.Rank instance Futhark.Transform.Rename.Rename d => Futhark.Transform.Rename.Rename (Futhark.Representation.AST.Syntax.Core.ShapeBase d) instance Futhark.Transform.Rename.Rename Futhark.Representation.AST.Syntax.Core.ExtSize instance Futhark.Transform.Rename.Rename () instance Futhark.Transform.Rename.Rename d => Futhark.Transform.Rename.Rename (Futhark.Representation.AST.Syntax.Core.DimIndex d) -- | This module provides various simple ways to query and manipulate -- fundamental Futhark terms, such as types and values. The intent is to -- keep Futhark.Reprsentation.AST.Syntax simple, and put whatever -- embellishments we need here. This is an internal, desugared -- representation. module Futhark.Representation.AST.Attributes -- | isBuiltInFunction k is True if k is an -- element of builtInFunctions. isBuiltInFunction :: Name -> Bool -- | A map of all built-in functions and their types. builtInFunctions :: Map Name (PrimType, [PrimType]) -- | Find the function of the given name in the Futhark program. funDefByName :: Name -> Prog lore -> Maybe (FunDef lore) -- | If the expression is a BasicOp, return that BasicOp, -- otherwise Nothing. asBasicOp :: Exp lore -> Maybe (BasicOp lore) -- | An expression is safe if it is always well-defined (assuming that any -- required certificates have been checked) in any context. For example, -- array indexing is not safe, as the index may be out of bounds. On the -- other hand, adding two numbers cannot fail. safeExp :: IsOp (Op lore) => Exp lore -> Bool -- | Return the variable names used in Var subexpressions. May -- contain duplicates. subExpVars :: [SubExp] -> [VName] -- | If the BasicOp is a Var return the variable name. subExpVar :: SubExp -> Maybe VName -- | Return the variable dimension sizes. May contain duplicates. shapeVars :: Shape -> [VName] -- | Does the given lambda represent a known commutative function? Based on -- pattern matching and checking whether the lambda represents a known -- arithmetic operator; don't expect anything clever here. commutativeLambda :: Lambda lore -> Bool -- | How many value parameters are accepted by this entry point? This is -- used to determine which of the function parameters correspond to the -- parameters of the original function (they must all come at the end). entryPointSize :: EntryPointType -> Int -- | A StmAux with empty Certificates. defAux :: attr -> StmAux attr -- | The certificates associated with a statement. stmCerts :: Stm lore -> Certificates -- | Add certificates to a statement. certify :: Certificates -> Stm lore -> Stm lore -- | Construct the type of an expression that would match the pattern. expExtTypesFromPattern :: Typed attr => PatternT attr -> [ExtType] -- | A type class for operations. class (Eq op, Ord op, Show op, TypedOp op, Rename op, Substitute op, FreeIn op, Pretty op) => IsOp op -- | Like safeExp, but for arbitrary ops. safeOp :: IsOp op => op -> Bool -- | Should we try to hoist this out of branches? cheapOp :: IsOp op => op -> Bool -- | Lore-specific attributes; also means the lore supports some basic -- facilities. class (Annotations lore, PrettyLore lore, Renameable lore, Substitutable lore, FreeAttr (ExpAttr lore), FreeIn (LetAttr lore), FreeAttr (BodyAttr lore), FreeIn (FParamAttr lore), FreeIn (LParamAttr lore), FreeIn (RetType lore), FreeIn (BranchType lore), IsOp (Op lore)) => Attributes lore -- | Given a pattern, construct the type of a body that would match it. An -- implementation for many lores would be expExtTypesFromPattern. expTypesFromPattern :: (Attributes lore, HasScope lore m, Monad m) => Pattern lore -> m [BranchType lore] instance Futhark.Representation.AST.Attributes.IsOp () module Futhark.Representation.AST.Attributes.Aliases vnameAliases :: VName -> Names subExpAliases :: SubExp -> Names primOpAliases :: BasicOp lore -> [Names] expAliases :: Aliased lore => Exp lore -> [Names] patternAliases :: AliasesOf attr => PatternT attr -> [Names] class (Annotations lore, AliasedOp (Op lore), AliasesOf (LetAttr lore)) => Aliased lore bodyAliases :: Aliased lore => Body lore -> [Names] consumedInBody :: Aliased lore => Body lore -> Names -- | Something that contains alias information. class AliasesOf a -- | The alias of the argument element. aliasesOf :: AliasesOf a => a -> Names consumedInStm :: Aliased lore => Stm lore -> Names consumedInExp :: Aliased lore => Exp lore -> Names consumedByLambda :: Aliased lore => Lambda lore -> Names class IsOp op => AliasedOp op opAliases :: AliasedOp op => op -> [Names] consumedInOp :: AliasedOp op => op -> Names class AliasedOp (OpWithAliases op) => CanBeAliased op where { type family OpWithAliases op :: *; } removeOpAliases :: CanBeAliased op => OpWithAliases op -> op addOpAliases :: CanBeAliased op => op -> OpWithAliases op instance Futhark.Representation.AST.Attributes.Aliases.CanBeAliased () instance Futhark.Representation.AST.Attributes.Aliases.AliasedOp () instance Futhark.Representation.AST.Attributes.Aliases.AliasesOf Futhark.Representation.AST.Syntax.Core.Names instance Futhark.Representation.AST.Attributes.Aliases.AliasesOf attr => Futhark.Representation.AST.Attributes.Aliases.AliasesOf (Futhark.Representation.AST.Syntax.Core.PatElemT attr) -- | A convenient re-export of basic AST modules. Note that -- Futhark.Representation.AST.Lore is not exported, as this would -- cause name clashes. You are advised to use a qualified import of the -- lore module, if you need it. module Futhark.Representation.AST -- | A usage-table is sort of a bottom-up symbol table, describing how (and -- if) a variable is used. module Futhark.Analysis.UsageTable data UsageTable empty :: UsageTable contains :: UsageTable -> [VName] -> Bool without :: UsageTable -> [VName] -> UsageTable lookup :: VName -> UsageTable -> Maybe Usages keys :: UsageTable -> [VName] used :: VName -> UsageTable -> Bool -- | Expand the usage table based on aliasing information. expand :: (VName -> Names) -> UsageTable -> UsageTable isConsumed :: VName -> UsageTable -> Bool isInResult :: VName -> UsageTable -> Bool -- | Has the given name been used directly (i.e. could we rename it or -- remove it without anyone noticing?) isUsedDirectly :: VName -> UsageTable -> Bool allConsumed :: UsageTable -> Names usages :: Names -> UsageTable usage :: VName -> Usages -> UsageTable consumedUsage :: VName -> UsageTable inResultUsage :: VName -> UsageTable data Usages leftScope :: UsageTable -> UsageTable instance GHC.Show.Show Futhark.Analysis.UsageTable.UsageTable instance GHC.Classes.Eq Futhark.Analysis.UsageTable.UsageTable instance GHC.Show.Show Futhark.Analysis.UsageTable.Usages instance GHC.Classes.Ord Futhark.Analysis.UsageTable.Usages instance GHC.Classes.Eq Futhark.Analysis.UsageTable.Usages instance GHC.Base.Semigroup Futhark.Analysis.UsageTable.UsageTable instance GHC.Base.Monoid Futhark.Analysis.UsageTable.UsageTable instance Futhark.Transform.Substitute.Substitute Futhark.Analysis.UsageTable.UsageTable instance GHC.Base.Semigroup Futhark.Analysis.UsageTable.Usages instance GHC.Base.Monoid Futhark.Analysis.UsageTable.Usages module Futhark.Analysis.Usage usageInStm :: (Attributes lore, Aliased lore, UsageInOp (Op lore)) => Stm lore -> UsageTable usageInExp :: (Aliased lore, UsageInOp (Op lore)) => Exp lore -> UsageTable usageInLambda :: Aliased lore => Lambda lore -> [VName] -> UsageTable class UsageInOp op usageInOp :: UsageInOp op => op -> UsageTable instance Futhark.Analysis.Usage.UsageInOp () -- | Facilities for changing the lore of some fragment, with no context. module Futhark.Analysis.Rephrase rephraseProg :: Monad m => Rephraser m from to -> Prog from -> m (Prog to) rephraseFunDef :: Monad m => Rephraser m from to -> FunDef from -> m (FunDef to) rephraseExp :: Monad m => Rephraser m from to -> Exp from -> m (Exp to) rephraseBody :: Monad m => Rephraser m from to -> Body from -> m (Body to) rephraseStm :: Monad m => Rephraser m from to -> Stm from -> m (Stm to) rephraseLambda :: Monad m => Rephraser m from to -> Lambda from -> m (Lambda to) rephrasePattern :: Monad m => (from -> m to) -> PatternT from -> m (PatternT to) rephrasePatElem :: Monad m => (from -> m to) -> PatElemT from -> m (PatElemT to) data Rephraser m from to Rephraser :: (ExpAttr from -> m (ExpAttr to)) -> (LetAttr from -> m (LetAttr to)) -> (FParamAttr from -> m (FParamAttr to)) -> (LParamAttr from -> m (LParamAttr to)) -> (BodyAttr from -> m (BodyAttr to)) -> (RetType from -> m (RetType to)) -> (BranchType from -> m (BranchType to)) -> (Op from -> m (Op to)) -> Rephraser m from to [rephraseExpLore] :: Rephraser m from to -> ExpAttr from -> m (ExpAttr to) [rephraseLetBoundLore] :: Rephraser m from to -> LetAttr from -> m (LetAttr to) [rephraseFParamLore] :: Rephraser m from to -> FParamAttr from -> m (FParamAttr to) [rephraseLParamLore] :: Rephraser m from to -> LParamAttr from -> m (LParamAttr to) [rephraseBodyLore] :: Rephraser m from to -> BodyAttr from -> m (BodyAttr to) [rephraseRetType] :: Rephraser m from to -> RetType from -> m (RetType to) [rephraseBranchType] :: Rephraser m from to -> BranchType from -> m (BranchType to) [rephraseOp] :: Rephraser m from to -> Op from -> m (Op to) -- | Convert a binding from one lore to another, if possible. castStm :: (SameScope from to, ExpAttr from ~ ExpAttr to, BodyAttr from ~ BodyAttr to, RetType from ~ RetType to, BranchType from ~ BranchType to) => Stm from -> Maybe (Stm to) -- | Abstract Syntax Tree metrics. This is used in the -- futhark-test program. module Futhark.Analysis.Metrics newtype AstMetrics AstMetrics :: Map Text Int -> AstMetrics progMetrics :: OpMetrics (Op lore) => Prog lore -> AstMetrics class OpMetrics op opMetrics :: OpMetrics op => op -> MetricsM () seen :: Text -> MetricsM () inside :: Text -> MetricsM () -> MetricsM () data MetricsM a bodyMetrics :: OpMetrics (Op lore) => Body lore -> MetricsM () bindingMetrics :: OpMetrics (Op lore) => Stm lore -> MetricsM () lambdaMetrics :: OpMetrics (Op lore) => Lambda lore -> MetricsM () instance Control.Monad.Writer.Class.MonadWriter Futhark.Analysis.Metrics.CountMetrics Futhark.Analysis.Metrics.MetricsM instance GHC.Base.Functor Futhark.Analysis.Metrics.MetricsM instance GHC.Base.Applicative Futhark.Analysis.Metrics.MetricsM instance GHC.Base.Monad Futhark.Analysis.Metrics.MetricsM instance Futhark.Analysis.Metrics.OpMetrics () instance GHC.Base.Semigroup Futhark.Analysis.Metrics.CountMetrics instance GHC.Base.Monoid Futhark.Analysis.Metrics.CountMetrics instance GHC.Show.Show Futhark.Analysis.Metrics.AstMetrics instance GHC.Read.Read Futhark.Analysis.Metrics.AstMetrics -- | Facilities for inspecting the data dependencies of a program. module Futhark.Analysis.DataDependencies -- | A mapping from a variable name v, to those variables on which -- the value of v is dependent. The intuition is that we could -- remove all other variables, and v would still be computable. -- This also includes names bound in loops or by lambdas. type Dependencies = Map VName Names -- | Compute the data dependencies for an entire body. dataDependencies :: Attributes lore => Body lore -> Dependencies findNecessaryForReturned :: (Param attr -> Bool) -> [(Param attr, SubExp)] -> Map VName Names -> Names module Futhark.Analysis.ScalExp -- | Relational operators. data RelOp0 LTH0 :: RelOp0 LEQ0 :: RelOp0 -- | Representation of a scalar expression, which is: -- -- (i) an algebraic expression, e.g., min(a+b, a*b), -- -- (ii) a relational expression: a+b < 5, -- -- (iii) a logical expression: e1 and (not (a+b>5) data ScalExp Val :: PrimValue -> ScalExp Id :: VName -> PrimType -> ScalExp SNeg :: ScalExp -> ScalExp SNot :: ScalExp -> ScalExp SAbs :: ScalExp -> ScalExp SSignum :: ScalExp -> ScalExp SPlus :: ScalExp -> ScalExp -> ScalExp SMinus :: ScalExp -> ScalExp -> ScalExp STimes :: ScalExp -> ScalExp -> ScalExp SPow :: ScalExp -> ScalExp -> ScalExp SDiv :: ScalExp -> ScalExp -> ScalExp SMod :: ScalExp -> ScalExp -> ScalExp SQuot :: ScalExp -> ScalExp -> ScalExp SRem :: ScalExp -> ScalExp -> ScalExp MaxMin :: Bool -> [ScalExp] -> ScalExp RelExp :: RelOp0 -> ScalExp -> ScalExp SLogAnd :: ScalExp -> ScalExp -> ScalExp SLogOr :: ScalExp -> ScalExp -> ScalExp scalExpType :: ScalExp -> PrimType -- | Number of nodes in the scalar expression. scalExpSize :: ScalExp -> Int -- | Non-recursively convert a subexpression to a ScalExp. The -- (scalar) type of the subexpression must be given in advance. subExpToScalExp :: SubExp -> PrimType -> ScalExp toScalExp :: (HasScope t f, Monad f) => LookupVar -> Exp lore -> f (Maybe ScalExp) -- | If you have a scalar expression that has been created with incomplete -- symbol table information, you can use this function to grow its -- Id leaves. expandScalExp :: LookupVar -> ScalExp -> ScalExp -- | A function that checks whether a variable name corresponds to a scalar -- expression. type LookupVar = VName -> Maybe ScalExp -- | Conversion operators try to generalise the from t0 x to t1 -- instructions from LLVM. data ConvOp -- | Zero-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. ZExt :: IntType -> IntType -> ConvOp -- | Sign-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. SExt :: IntType -> IntType -> ConvOp -- | Convert value of the former floating-point type to the latter. If the -- new type is smaller, the result is a truncation. FPConv :: FloatType -> FloatType -> ConvOp -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). FPToUI :: FloatType -> IntType -> ConvOp -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). FPToSI :: FloatType -> IntType -> ConvOp -- | Convert an unsigned integer to a floating-point value. UIToFP :: IntType -> FloatType -> ConvOp -- | Convert a signed integer to a floating-point value. SIToFP :: IntType -> FloatType -> ConvOp -- | Convert an integer to a boolean value. Zero becomes false; anything -- else is true. IToB :: IntType -> ConvOp -- | Convert a boolean to an integer. True is converted to 1 and False to -- 0. BToI :: IntType -> ConvOp -- | Comparison operators are like BinOps, but they return -- PrimTypes. The somewhat ugly constructor names are straight out -- of LLVM. data CmpOp -- | All types equality. CmpEq :: PrimType -> CmpOp -- | Unsigned less than. CmpUlt :: IntType -> CmpOp -- | Unsigned less than or equal. CmpUle :: IntType -> CmpOp -- | Signed less than. CmpSlt :: IntType -> CmpOp -- | Signed less than or equal. CmpSle :: IntType -> CmpOp -- | Floating-point less than. FCmpLt :: FloatType -> CmpOp -- | Floating-point less than or equal. FCmpLe :: FloatType -> CmpOp -- | Boolean less than. CmpLlt :: CmpOp -- | Boolean less than or equal. CmpLle :: CmpOp -- | Binary operators. These correspond closely to the binary operators in -- LLVM. Most are parametrised by their expected input and output types. data BinOp -- | Integer addition. Add :: IntType -> BinOp -- | Floating-point addition. FAdd :: FloatType -> BinOp -- | Integer subtraction. Sub :: IntType -> BinOp -- | Floating-point subtraction. FSub :: FloatType -> BinOp -- | Integer multiplication. Mul :: IntType -> BinOp -- | Floating-point multiplication. FMul :: FloatType -> BinOp -- | Unsigned integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. UDiv :: IntType -> BinOp -- | Floating-point division. FDiv :: FloatType -> BinOp -- | Unsigned integer modulus; the countepart to UDiv. UMod :: IntType -> BinOp -- | Returns the smallest of two signed integers. SMin :: IntType -> BinOp -- | Returns the smallest of two unsigned integers. UMin :: IntType -> BinOp -- | Returns the smallest of two floating-point numbers. FMin :: FloatType -> BinOp -- | Returns the greatest of two signed integers. SMax :: IntType -> BinOp -- | Returns the greatest of two unsigned integers. UMax :: IntType -> BinOp -- | Returns the greatest of two floating-point numbers. FMax :: FloatType -> BinOp -- | Left-shift. Shl :: IntType -> BinOp -- | Logical right-shift, zero-extended. LShr :: IntType -> BinOp -- | Arithmetic right-shift, sign-extended. AShr :: IntType -> BinOp -- | Bitwise and. And :: IntType -> BinOp -- | Bitwise or. Or :: IntType -> BinOp -- | Bitwise exclusive-or. Xor :: IntType -> BinOp -- | Integer exponentiation. Pow :: IntType -> BinOp -- | Floating-point exponentiation. FPow :: FloatType -> BinOp -- | Boolean and - not short-circuiting. LogAnd :: BinOp -- | Boolean or - not short-circuiting. LogOr :: BinOp -- | Various unary operators. It is a bit ad-hoc what is a unary operator -- and what is a built-in function. Perhaps these should all go away -- eventually. data UnOp -- | E.g., ! True == False. Not :: UnOp -- | E.g., ~(~1) = 1. Complement :: IntType -> UnOp -- | abs(-2) = 2. Abs :: IntType -> UnOp -- | fabs(-2.0) = 2.0. FAbs :: FloatType -> UnOp -- | Unsigned sign function: usignum(2) = 1. USignum :: IntType -> UnOp -- | Non-array values. data PrimValue IntValue :: !IntValue -> PrimValue FloatValue :: !FloatValue -> PrimValue BoolValue :: !Bool -> PrimValue -- | The only value of type cert. Checked :: PrimValue -- | A floating-point value. data FloatValue Float32Value :: !Float -> FloatValue Float64Value :: !Double -> FloatValue -- | An integer value. data IntValue Int8Value :: !Int8 -> IntValue Int16Value :: !Int16 -> IntValue Int32Value :: !Int32 -> IntValue Int64Value :: !Int64 -> IntValue -- | Low-level primitive types. data PrimType IntType :: IntType -> PrimType FloatType :: FloatType -> PrimType Bool :: PrimType Cert :: PrimType -- | A floating point type. data FloatType Float32 :: FloatType Float64 :: FloatType -- | An integer type, ordered by size. Note that signedness is not a -- property of the type, but a property of the operations performed on -- values of these types. data IntType Int8 :: IntType Int16 :: IntType Int32 :: IntType Int64 :: IntType -- | A list of all integer types. allIntTypes :: [IntType] -- | A list of all floating-point types. allFloatTypes :: [FloatType] -- | A list of all primitive types. allPrimTypes :: [PrimType] -- | Create an IntValue from a type and an Integer. intValue :: Integral int => IntType -> int -> IntValue intValueType :: IntValue -> IntType -- | Convert an IntValue to any Integral type. valueIntegral :: Integral int => IntValue -> int -- | Create a FloatValue from a type and a Rational. floatValue :: Real num => FloatType -> num -> FloatValue floatValueType :: FloatValue -> FloatType -- | The type of a basic value. primValueType :: PrimValue -> PrimType -- | A "blank" value of the given primitive type - this is zero, or -- whatever is close to it. Don't depend on this value, but use it for -- e.g. creating arrays to be populated by do-loops. blankPrimValue :: PrimType -> PrimValue -- | A list of all unary operators for all types. allUnOps :: [UnOp] -- | A list of all binary operators for all types. allBinOps :: [BinOp] -- | A list of all comparison operators for all types. allCmpOps :: [CmpOp] -- | A list of all conversion operators for all types. allConvOps :: [ConvOp] doUnOp :: UnOp -> PrimValue -> Maybe PrimValue -- | E.g., ~(~1) = 1. doComplement :: IntValue -> IntValue -- | abs(-2) = 2. doAbs :: IntValue -> IntValue -- | abs(-2.0) = 2.0. doFAbs :: FloatValue -> FloatValue -- | ssignum(-2) = -1. doSSignum :: IntValue -> IntValue -- | usignum(-2) = -1. doUSignum :: IntValue -> IntValue doBinOp :: BinOp -> PrimValue -> PrimValue -> Maybe PrimValue -- | Integer addition. doAdd :: IntValue -> IntValue -> IntValue -- | Integer multiplication. doMul :: IntValue -> IntValue -> IntValue -- | Signed integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. doSDiv :: IntValue -> IntValue -> Maybe IntValue -- | Signed integer modulus; the countepart to SDiv. doSMod :: IntValue -> IntValue -> Maybe IntValue -- | Signed integer exponentatation. doPow :: IntValue -> IntValue -> Maybe IntValue doConvOp :: ConvOp -> PrimValue -> Maybe PrimValue -- | Zero-extend the given integer value to the size of the given type. If -- the type is smaller than the given value, the result is a truncation. doZExt :: IntValue -> IntType -> IntValue -- | Sign-extend the given integer value to the size of the given type. If -- the type is smaller than the given value, the result is a truncation. doSExt :: IntValue -> IntType -> IntValue -- | Convert the former floating-point type to the latter. doFPConv :: FloatValue -> FloatType -> FloatValue -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). doFPToUI :: FloatValue -> IntType -> IntValue -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). doFPToSI :: FloatValue -> IntType -> IntValue -- | Convert an unsigned integer to a floating-point value. doUIToFP :: IntValue -> FloatType -> FloatValue -- | Convert a signed integer to a floating-point value. doSIToFP :: IntValue -> FloatType -> FloatValue doCmpOp :: CmpOp -> PrimValue -> PrimValue -> Maybe Bool -- | Compare any two primtive values for exact equality. doCmpEq :: PrimValue -> PrimValue -> Bool -- | Unsigned less than. doCmpUlt :: IntValue -> IntValue -> Bool -- | Unsigned less than or equal. doCmpUle :: IntValue -> IntValue -> Bool -- | Signed less than. doCmpSlt :: IntValue -> IntValue -> Bool -- | Signed less than or equal. doCmpSle :: IntValue -> IntValue -> Bool -- | Floating-point less than. doFCmpLt :: FloatValue -> FloatValue -> Bool -- | Floating-point less than or equal. doFCmpLe :: FloatValue -> FloatValue -> Bool -- | Translate an IntValue to Word64. This is guaranteed to -- fit. intToWord64 :: IntValue -> Word64 -- | Translate an IntValue to IntType. This is guaranteed to -- fit. intToInt64 :: IntValue -> Int64 -- | The result type of a binary operator. binOpType :: BinOp -> PrimType -- | The operand types of a comparison operator. cmpOpType :: CmpOp -> PrimType -- | The operand and result type of a unary operator. unOpType :: UnOp -> PrimType -- | The input and output types of a conversion operator. convOpType :: ConvOp -> (PrimType, PrimType) -- | A mapping from names of primitive functions to their parameter types, -- their result type, and a function for evaluating them. primFuns :: Map String ([PrimType], PrimType, [PrimValue] -> Maybe PrimValue) -- | Is the given value kind of zero? zeroIsh :: PrimValue -> Bool -- | Is the given value kind of one? oneIsh :: PrimValue -> Bool -- | Is the given value kind of negative? negativeIsh :: PrimValue -> Bool -- | The size of a value of a given primitive type in bites. primBitSize :: PrimType -> Int -- | The size of a value of a given primitive type in eight-bit bytes. primByteSize :: Num a => PrimType -> a -- | True if the given binary operator is commutative. commutativeBinOp :: BinOp -> Bool convOpFun :: ConvOp -> String -- | True if signed. Only makes a difference for integer types. prettySigned :: Bool -> PrimType -> String instance GHC.Show.Show Futhark.Analysis.ScalExp.ScalExp instance GHC.Classes.Ord Futhark.Analysis.ScalExp.ScalExp instance GHC.Classes.Eq Futhark.Analysis.ScalExp.ScalExp instance GHC.Show.Show Futhark.Analysis.ScalExp.RelOp0 instance GHC.Enum.Bounded Futhark.Analysis.ScalExp.RelOp0 instance GHC.Enum.Enum Futhark.Analysis.ScalExp.RelOp0 instance GHC.Classes.Ord Futhark.Analysis.ScalExp.RelOp0 instance GHC.Classes.Eq Futhark.Analysis.ScalExp.RelOp0 instance GHC.Num.Num Futhark.Analysis.ScalExp.ScalExp instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Analysis.ScalExp.ScalExp instance Futhark.Transform.Substitute.Substitute Futhark.Analysis.ScalExp.ScalExp instance Futhark.Transform.Rename.Rename Futhark.Analysis.ScalExp.ScalExp instance Futhark.Representation.AST.Attributes.Names.FreeIn Futhark.Analysis.ScalExp.ScalExp module Futhark.Analysis.AlgSimplify -- | Representation of a scalar expression, which is: -- -- (i) an algebraic expression, e.g., min(a+b, a*b), -- -- (ii) a relational expression: a+b < 5, -- -- (iii) a logical expression: e1 and (not (a+b>5) data ScalExp data Error -- | Applies Simplification at Expression level: simplify :: ScalExp -> RangesRep -> ScalExp -- | Extracts sufficient conditions for a LTH0 relation to hold mkSuffConds :: ScalExp -> RangesRep -> Either Error [[ScalExp]] -- | Ranges are inclusive. type RangesRep = Map VName (Int, Maybe ScalExp, Maybe ScalExp) -- | Prettyprint a RangesRep. Do not rely on the format of this -- string. Does not include the loop nesting depth information. ppRangesRep :: RangesRep -> String -- | Given a symbol i and a scalar expression e, it decomposes e = a*i + b -- and returns (a,b) if possible, otherwise Nothing. linFormScalE :: VName -> ScalExp -> RangesRep -> Either Error (Maybe (ScalExp, ScalExp)) pickSymToElim :: RangesRep -> Set VName -> ScalExp -> Maybe VName instance GHC.Show.Show Futhark.Analysis.AlgSimplify.BTerm instance GHC.Classes.Ord Futhark.Analysis.AlgSimplify.BTerm instance GHC.Classes.Eq Futhark.Analysis.AlgSimplify.BTerm instance GHC.Show.Show Futhark.Analysis.AlgSimplify.NNumExp instance GHC.Classes.Ord Futhark.Analysis.AlgSimplify.NNumExp instance GHC.Classes.Eq Futhark.Analysis.AlgSimplify.NNumExp -- | Utility declarations for performing range analysis. module Futhark.Representation.AST.Attributes.Ranges -- | A possibly undefined bound on a value. type Bound = Maybe KnownBound -- | A known bound on a value. data KnownBound -- | Has the same bounds as this variable. VERY IMPORTANT: this variable -- may be an array, so it cannot be immediately translated to a -- ScalExp. VarBound :: VName -> KnownBound -- | Bounded by the minimum of these two bounds. MinimumBound :: KnownBound -> KnownBound -> KnownBound -- | Bounded by the maximum of these two bounds. MaximumBound :: KnownBound -> KnownBound -> KnownBound -- | Bounded by this scalar expression. ScalarBound :: ScalExp -> KnownBound -- | Convert the bound to a scalar expression if possible. This is possible -- for all bounds that do not contain VarBounds. boundToScalExp :: KnownBound -> Maybe ScalExp -- | Construct a MinimumBound from two possibly known bounds. The -- resulting bound will be unknown unless both of the given Bounds -- are known. This may seem counterintuitive, but it actually makes sense -- when you consider the task of combining the lower bounds for two -- different flows of execution (like an if expression). If we -- only have knowledge about one of the branches, this means that we have -- no useful information about the combined lower bound, as the other -- branch may take any value. minimumBound :: Bound -> Bound -> Bound -- | Like minimumBound, but constructs a MaximumBound. maximumBound :: Bound -> Bound -> Bound -- | Upper and lower bound, both inclusive. type Range = (Bound, Bound) -- | A range in which both upper and lower bounds are 'Nothing. unknownRange :: Range -- | The range as a pair of scalar expressions. type ScalExpRange = (Maybe ScalExp, Maybe ScalExp) -- | The lore has embedded range information. Note that it may not be up to -- date, unless whatever maintains the syntax tree is careful. type Ranged lore = (Attributes lore, RangedOp (Op lore), RangeOf (LetAttr lore), RangesOf (BodyAttr lore)) -- | Something that contains range information. class RangeOf a -- | The range of the argument element. rangeOf :: RangeOf a => a -> Range -- | Something that contains range information for several things, most -- notably BodyT or PatternT. class RangesOf a -- | The ranges of the argument. rangesOf :: RangesOf a => a -> [Range] -- | Ranges of the value parts of the expression. expRanges :: Ranged lore => Exp lore -> [Range] class IsOp op => RangedOp op opRanges :: RangedOp op => op -> [Range] class RangedOp (OpWithRanges op) => CanBeRanged op where { type family OpWithRanges op :: *; } removeOpRanges :: CanBeRanged op => OpWithRanges op -> op addOpRanges :: CanBeRanged op => op -> OpWithRanges op instance GHC.Show.Show Futhark.Representation.AST.Attributes.Ranges.KnownBound instance GHC.Classes.Ord Futhark.Representation.AST.Attributes.Ranges.KnownBound instance GHC.Classes.Eq Futhark.Representation.AST.Attributes.Ranges.KnownBound instance Futhark.Representation.AST.Attributes.Ranges.CanBeRanged () instance Futhark.Representation.AST.Attributes.Ranges.Ranged lore => Futhark.Representation.AST.Attributes.Ranges.RangesOf (Futhark.Representation.AST.Syntax.Body lore) instance Futhark.Representation.AST.Attributes.Ranges.RangedOp () instance Futhark.Representation.AST.Attributes.Ranges.RangeOf a => Futhark.Representation.AST.Attributes.Ranges.RangesOf [a] instance Futhark.Representation.AST.Attributes.Ranges.RangeOf attr => Futhark.Representation.AST.Attributes.Ranges.RangesOf (Futhark.Representation.AST.Syntax.PatternT attr) instance Futhark.Representation.AST.Attributes.Ranges.RangeOf Futhark.Representation.AST.Attributes.Ranges.Range instance Futhark.Representation.AST.Attributes.Ranges.RangeOf attr => Futhark.Representation.AST.Attributes.Ranges.RangeOf (Futhark.Representation.AST.Syntax.Core.PatElemT attr) instance Futhark.Representation.AST.Attributes.Ranges.RangeOf Futhark.Representation.AST.Syntax.Core.SubExp instance Futhark.Transform.Substitute.Substitute Futhark.Representation.AST.Attributes.Ranges.KnownBound instance Futhark.Transform.Rename.Rename Futhark.Representation.AST.Attributes.Ranges.KnownBound instance Futhark.Representation.AST.Attributes.Names.FreeIn Futhark.Representation.AST.Attributes.Ranges.KnownBound instance Futhark.Representation.AST.Attributes.Names.FreeAttr Futhark.Representation.AST.Attributes.Ranges.KnownBound instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Representation.AST.Attributes.Ranges.KnownBound -- | A representation where all bindings are annotated with range -- information. module Futhark.Representation.Ranges -- | The lore for the basic representation. data Ranges lore addRangesToPattern :: (Attributes lore, CanBeRanged (Op lore)) => Pattern lore -> Exp (Ranges lore) -> Pattern (Ranges lore) mkRangedLetStm :: (Attributes lore, CanBeRanged (Op lore)) => Pattern lore -> ExpAttr lore -> Exp (Ranges lore) -> Stm (Ranges lore) mkRangedBody :: BodyAttr lore -> Stms (Ranges lore) -> Result -> Body (Ranges lore) mkPatternRanges :: (Attributes lore, CanBeRanged (Op lore)) => Pattern lore -> Exp (Ranges lore) -> ([PatElemT (Range, LetAttr lore)], [PatElemT (Range, LetAttr lore)]) mkBodyRanges :: Stms lore -> Result -> [Range] removeProgRanges :: CanBeRanged (Op lore) => Prog (Ranges lore) -> Prog lore removeFunDefRanges :: CanBeRanged (Op lore) => FunDef (Ranges lore) -> FunDef lore removeExpRanges :: CanBeRanged (Op lore) => Exp (Ranges lore) -> Exp lore removeBodyRanges :: CanBeRanged (Op lore) => Body (Ranges lore) -> Body lore removeStmRanges :: CanBeRanged (Op lore) => Stm (Ranges lore) -> Stm lore removeLambdaRanges :: CanBeRanged (Op lore) => Lambda (Ranges lore) -> Lambda lore removePatternRanges :: PatternT (Range, a) -> PatternT a instance (Futhark.Representation.AST.Annotations.Annotations lore, Futhark.Representation.AST.Attributes.Ranges.CanBeRanged (Futhark.Representation.AST.Annotations.Op lore)) => Futhark.Representation.AST.Annotations.Annotations (Futhark.Representation.Ranges.Ranges lore) instance (Futhark.Representation.AST.Attributes.Attributes lore, Futhark.Representation.AST.Attributes.Ranges.CanBeRanged (Futhark.Representation.AST.Annotations.Op lore)) => Futhark.Representation.AST.Attributes.Attributes (Futhark.Representation.Ranges.Ranges lore) instance (Futhark.Representation.AST.Pretty.PrettyLore lore, Futhark.Representation.AST.Attributes.Ranges.CanBeRanged (Futhark.Representation.AST.Annotations.Op lore)) => Futhark.Representation.AST.Pretty.PrettyLore (Futhark.Representation.Ranges.Ranges lore) instance Futhark.Representation.AST.Attributes.Ranges.RangeOf (Futhark.Representation.AST.Attributes.Ranges.Range, attr) instance Futhark.Representation.AST.Attributes.Ranges.RangesOf ([Futhark.Representation.AST.Attributes.Ranges.Range], attr) instance Futhark.Representation.AST.Pretty.PrettyAnnot (Futhark.Representation.AST.Syntax.Core.PatElemT attr) => Futhark.Representation.AST.Pretty.PrettyAnnot (Futhark.Representation.AST.Syntax.Core.PatElemT (Futhark.Representation.AST.Attributes.Ranges.Range, attr)) module Futhark.Analysis.Range -- | Perform variable range analysis on the given program, returning a -- program with embedded range annotations. rangeAnalysis :: (Attributes lore, CanBeRanged (Op lore)) => Prog lore -> Prog (Ranges lore) runRangeM :: RangeM a -> a type RangeM = Reader RangeEnv analyseExp :: (Attributes lore, CanBeRanged (Op lore)) => Exp lore -> RangeM (Exp (Ranges lore)) analyseLambda :: (Attributes lore, CanBeRanged (Op lore)) => Lambda lore -> RangeM (Lambda (Ranges lore)) analyseBody :: (Attributes lore, CanBeRanged (Op lore)) => Body lore -> RangeM (Body (Ranges lore)) analyseStms :: (Attributes lore, CanBeRanged (Op lore)) => Stms lore -> (Stms (Ranges lore) -> RangeM a) -> RangeM a -- | Definition of a polymorphic (generic) pass that can work with programs -- of any lore. module Futhark.Pass -- | The monad in which passes execute. data PassM a -- | Execute a PassM action, yielding logging information and either -- an error text or a result. runPassM :: MonadFreshNames m => PassM a -> m (Either InternalError a, Log) -- | Turn an Either computation into a PassM. If the -- Either is Left, the result is a CompilerBug. liftEither :: Show err => Either err a -> PassM a -- | Turn an Either monadic computation into a PassM. If the -- Either is Left, the result is an exception. liftEitherM :: Show err => PassM (Either err a) -> PassM a -- | A compiler pass transforming a ProgT of a given lore to a -- ProgT of another lore. data Pass fromlore tolore Pass :: String -> String -> (Prog fromlore -> PassM (Prog tolore)) -> Pass fromlore tolore -- | Name of the pass. Keep this short and simple. It will be used to -- automatically generate a command-line option name via -- passLongOption. [passName] :: Pass fromlore tolore -> String -- | A slightly longer description, which will show up in the command-line -- help text. [passDescription] :: Pass fromlore tolore -> String [passFunction] :: Pass fromlore tolore -> Prog fromlore -> PassM (Prog tolore) -- | Take the name of the pass, turn spaces into dashes, and make all -- characters lowercase. passLongOption :: Pass fromlore tolore -> String intraproceduralTransformation :: (FunDef fromlore -> PassM (FunDef tolore)) -> Prog fromlore -> PassM (Prog tolore) instance Control.Monad.Error.Class.MonadError Futhark.Error.InternalError Futhark.Pass.PassM instance GHC.Base.Monad Futhark.Pass.PassM instance GHC.Base.Applicative Futhark.Pass.PassM instance GHC.Base.Functor Futhark.Pass.PassM instance Futhark.Util.Log.MonadLogger Futhark.Pass.PassM instance Futhark.MonadFreshNames.MonadFreshNames Futhark.Pass.PassM -- | This module defines a convenience typeclass for creating normalised -- programs. module Futhark.Binder.Class -- | The class of lores that can be constructed solely from an expression, -- within some monad. Very important: the methods should not have any -- significant side effects! They may be called more often than you -- think, and the results thrown away. If used exclusively within a -- MonadBinder instance, it is acceptable for them to create new -- bindings, however. class (Attributes lore, FParamAttr lore ~ DeclType, LParamAttr lore ~ Type, RetType lore ~ DeclExtType, BranchType lore ~ ExtType, SetType (LetAttr lore)) => Bindable lore mkExpPat :: Bindable lore => [Ident] -> [Ident] -> Exp lore -> Pattern lore mkExpAttr :: Bindable lore => Pattern lore -> Exp lore -> ExpAttr lore mkBody :: Bindable lore => Stms lore -> Result -> Body lore mkLetNames :: (Bindable lore, MonadFreshNames m, HasScope lore m) => [VName] -> Exp lore -> m (Stm lore) mkLet :: Bindable lore => [Ident] -> [Ident] -> Exp lore -> Stm lore -- | A monad that supports the creation of bindings from expressions and -- bodies from bindings, with a specific lore. This is the main typeclass -- that a monad must implement in order for it to be useful for -- generating or modifying Futhark code. -- -- Very important: the methods should not have any significant side -- effects! They may be called more often than you think, and the results -- thrown away. It is acceptable for them to create new bindings, -- however. class (Attributes (Lore m), MonadFreshNames m, Applicative m, Monad m, LocalScope (Lore m) m, MonadFail m) => MonadBinder m where { type family Lore m :: *; } mkExpAttrM :: MonadBinder m => Pattern (Lore m) -> Exp (Lore m) -> m (ExpAttr (Lore m)) mkBodyM :: MonadBinder m => Stms (Lore m) -> Result -> m (Body (Lore m)) mkLetNamesM :: MonadBinder m => [VName] -> Exp (Lore m) -> m (Stm (Lore m)) addStm :: MonadBinder m => Stm (Lore m) -> m () addStms :: MonadBinder m => Stms (Lore m) -> m () collectStms :: MonadBinder m => m a -> m (a, Stms (Lore m)) certifying :: MonadBinder m => Certificates -> m a -> m a mkLetM :: MonadBinder m => Pattern (Lore m) -> Exp (Lore m) -> m (Stm (Lore m)) bodyStms :: BodyT lore -> Stms lore -- | Add several bindings at the outermost level of a BodyT. insertStms :: Bindable lore => Stms lore -> Body lore -> Body lore -- | Add a single binding at the outermost level of a BodyT. insertStm :: Bindable lore => Stm lore -> Body lore -> Body lore letBind :: MonadBinder m => Pattern (Lore m) -> Exp (Lore m) -> m [Ident] letBind_ :: MonadBinder m => Pattern (Lore m) -> Exp (Lore m) -> m () letBindNames :: MonadBinder m => [VName] -> Exp (Lore m) -> m [Ident] letBindNames_ :: MonadBinder m => [VName] -> Exp (Lore m) -> m () collectStms_ :: MonadBinder m => m a -> m (Stms (Lore m)) bodyBind :: MonadBinder m => Body (Lore m) -> m [SubExp] -- | This module defines a convenience monad/typeclass for creating -- normalised programs. module Futhark.Binder data BinderT lore m a runBinderT :: MonadFreshNames m => BinderT lore m a -> Scope lore -> m (a, Stms lore) class Attributes lore => BinderOps lore mkExpAttrB :: (BinderOps lore, MonadBinder m, Lore m ~ lore) => Pattern lore -> Exp lore -> m (ExpAttr lore) mkBodyB :: (BinderOps lore, MonadBinder m, Lore m ~ lore) => Stms lore -> Result -> m (Body lore) mkLetNamesB :: (BinderOps lore, MonadBinder m, Lore m ~ lore) => [VName] -> Exp lore -> m (Stm lore) bindableMkExpAttrB :: (MonadBinder m, Bindable (Lore m)) => Pattern (Lore m) -> Exp (Lore m) -> m (ExpAttr (Lore m)) bindableMkBodyB :: (MonadBinder m, Bindable (Lore m)) => Stms (Lore m) -> Result -> m (Body (Lore m)) bindableMkLetNamesB :: (MonadBinder m, Bindable (Lore m)) => [VName] -> Exp (Lore m) -> m (Stm (Lore m)) type Binder lore = BinderT lore (State VNameSource) runBinder :: (MonadFreshNames m, HasScope somelore m, SameScope somelore lore) => Binder lore a -> m (a, Stms lore) -- | Like runBinder, but throw away the result and just return the -- added bindings. runBinder_ :: (MonadFreshNames m, HasScope somelore m, SameScope somelore lore) => Binder lore a -> m (Stms lore) -- | As runBinder, but uses addStm to add the returned -- bindings to the surrounding monad. joinBinder :: MonadBinder m => Binder (Lore m) a -> m a runBodyBinder :: (Bindable lore, MonadFreshNames m, HasScope somelore m, SameScope somelore lore) => Binder lore (Body lore) -> m (Body lore) addBinderStms :: Monad m => Stms lore -> BinderT lore m () collectBinderStms :: Monad m => BinderT lore m a -> BinderT lore m (a, Stms lore) certifyingBinder :: (MonadFreshNames m, BinderOps lore) => Certificates -> BinderT lore m a -> BinderT lore m a instance GHC.Base.Monad m => GHC.Base.Applicative (Futhark.Binder.BinderT lore m) instance GHC.Base.Monad m => GHC.Base.Monad (Futhark.Binder.BinderT lore m) instance GHC.Base.Functor m => GHC.Base.Functor (Futhark.Binder.BinderT lore m) instance Control.Monad.Trans.Class.MonadTrans (Futhark.Binder.BinderT lore) instance GHC.Base.Monad m => Control.Monad.Fail.MonadFail (Futhark.Binder.BinderT lore m) instance Futhark.MonadFreshNames.MonadFreshNames m => Futhark.MonadFreshNames.MonadFreshNames (Futhark.Binder.BinderT lore m) instance (Futhark.Representation.AST.Attributes.Attributes lore, GHC.Base.Monad m) => Futhark.Representation.AST.Attributes.Scope.HasScope lore (Futhark.Binder.BinderT lore m) instance (Futhark.Representation.AST.Attributes.Attributes lore, GHC.Base.Monad m) => Futhark.Representation.AST.Attributes.Scope.LocalScope lore (Futhark.Binder.BinderT lore m) instance (Futhark.Representation.AST.Attributes.Attributes lore, Futhark.MonadFreshNames.MonadFreshNames m, Futhark.Binder.BinderOps lore) => Futhark.Binder.Class.MonadBinder (Futhark.Binder.BinderT lore m) instance Control.Monad.Reader.Class.MonadReader r m => Control.Monad.Reader.Class.MonadReader r (Futhark.Binder.BinderT lore m) instance Control.Monad.State.Class.MonadState s m => Control.Monad.State.Class.MonadState s (Futhark.Binder.BinderT lore m) instance Control.Monad.Writer.Class.MonadWriter w m => Control.Monad.Writer.Class.MonadWriter w (Futhark.Binder.BinderT lore m) instance Control.Monad.Error.Class.MonadError e m => Control.Monad.Error.Class.MonadError e (Futhark.Binder.BinderT lore m) -- | A representation where all bindings are annotated with aliasing -- information. module Futhark.Representation.Aliases -- | The lore for the basic representation. data Aliases lore -- | A wrapper around Names to get around the fact that we need an -- Ord instance, which Names does not have. newtype Names' Names' :: Names -> Names' [unNames] :: Names' -> Names -- | The aliases of the let-bound variable. type VarAliases = Names' -- | Everything consumed in the expression. type ConsumedInExp = Names' -- | The aliases of what is returned by the BodyT, and what is -- consumed inside of it. type BodyAliasing = ([VarAliases], ConsumedInExp) addAliasesToPattern :: (Attributes lore, CanBeAliased (Op lore), Typed attr) => PatternT attr -> Exp (Aliases lore) -> PatternT (VarAliases, attr) mkAliasedLetStm :: (Attributes lore, CanBeAliased (Op lore)) => Pattern lore -> StmAux (ExpAttr lore) -> Exp (Aliases lore) -> Stm (Aliases lore) mkAliasedBody :: (Attributes lore, CanBeAliased (Op lore)) => BodyAttr lore -> Stms (Aliases lore) -> Result -> Body (Aliases lore) mkPatternAliases :: (Attributes lore, Aliased lore, Typed attr) => PatternT attr -> Exp lore -> ([PatElemT (VarAliases, attr)], [PatElemT (VarAliases, attr)]) mkBodyAliases :: Aliased lore => Stms lore -> Result -> BodyAliasing removeProgAliases :: CanBeAliased (Op lore) => Prog (Aliases lore) -> Prog lore removeFunDefAliases :: CanBeAliased (Op lore) => FunDef (Aliases lore) -> FunDef lore removeExpAliases :: CanBeAliased (Op lore) => Exp (Aliases lore) -> Exp lore removeBodyAliases :: CanBeAliased (Op lore) => Body (Aliases lore) -> Body lore removeStmAliases :: CanBeAliased (Op lore) => Stm (Aliases lore) -> Stm lore removeLambdaAliases :: CanBeAliased (Op lore) => Lambda (Aliases lore) -> Lambda lore removePatternAliases :: PatternT (Names', a) -> PatternT a removeScopeAliases :: Scope (Aliases lore) -> Scope lore type AliasesAndConsumed = (Map VName Names, Names) trackAliases :: Aliased lore => AliasesAndConsumed -> Stm lore -> AliasesAndConsumed -- | Everything consumed in the given bindings and result (even -- transitively). consumedInStms :: Aliased lore => Stms lore -> [SubExp] -> Names instance GHC.Show.Show Futhark.Representation.Aliases.Names' instance (Futhark.Representation.AST.Annotations.Annotations lore, Futhark.Representation.AST.Attributes.Aliases.CanBeAliased (Futhark.Representation.AST.Annotations.Op lore)) => Futhark.Representation.AST.Annotations.Annotations (Futhark.Representation.Aliases.Aliases lore) instance Futhark.Representation.AST.Attributes.Aliases.AliasesOf (Futhark.Representation.Aliases.VarAliases, attr) instance Futhark.Representation.AST.Pretty.PrettyAnnot (Futhark.Representation.AST.Syntax.Core.PatElemT attr) => Futhark.Representation.AST.Pretty.PrettyAnnot (Futhark.Representation.AST.Syntax.Core.PatElemT (Futhark.Representation.Aliases.VarAliases, attr)) instance GHC.Base.Semigroup Futhark.Representation.Aliases.Names' instance GHC.Base.Monoid Futhark.Representation.Aliases.Names' instance GHC.Classes.Eq Futhark.Representation.Aliases.Names' instance GHC.Classes.Ord Futhark.Representation.Aliases.Names' instance Futhark.Transform.Rename.Rename Futhark.Representation.Aliases.Names' instance Futhark.Transform.Substitute.Substitute Futhark.Representation.Aliases.Names' instance Futhark.Representation.AST.Attributes.Names.FreeIn Futhark.Representation.Aliases.Names' instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Representation.Aliases.Names' instance Futhark.Representation.AST.Attributes.Names.FreeAttr Futhark.Representation.Aliases.Names' instance (Futhark.Representation.AST.Attributes.Attributes lore, Futhark.Representation.AST.Attributes.Aliases.CanBeAliased (Futhark.Representation.AST.Annotations.Op lore)) => Futhark.Representation.AST.Attributes.Aliases.Aliased (Futhark.Representation.Aliases.Aliases lore) instance (Futhark.Representation.AST.Attributes.Attributes lore, Futhark.Representation.AST.Attributes.Aliases.CanBeAliased (Futhark.Representation.AST.Annotations.Op lore)) => Futhark.Representation.AST.Pretty.PrettyLore (Futhark.Representation.Aliases.Aliases lore) instance (Futhark.Binder.Class.Bindable lore, Futhark.Representation.AST.Attributes.Aliases.CanBeAliased (Futhark.Representation.AST.Annotations.Op lore)) => Futhark.Binder.Class.Bindable (Futhark.Representation.Aliases.Aliases lore) instance (Futhark.Representation.AST.Attributes.Attributes lore, Futhark.Representation.AST.Attributes.Aliases.CanBeAliased (Futhark.Representation.AST.Annotations.Op lore)) => Futhark.Representation.AST.Attributes.Attributes (Futhark.Representation.Aliases.Aliases lore) instance (Futhark.Representation.AST.Attributes.Attributes (Futhark.Representation.Aliases.Aliases lore), Futhark.Binder.Class.Bindable (Futhark.Representation.Aliases.Aliases lore)) => Futhark.Binder.BinderOps (Futhark.Representation.Aliases.Aliases lore) -- | Alias analysis of a full Futhark program. Takes as input a program -- with an arbitrary lore and produces one with aliases. This module does -- not implement the aliasing logic itself, and derives its information -- from definitions in -- Futhark.Representation.AST.Attributes.Aliases and -- Futhark.Representation.Aliases. module Futhark.Analysis.Alias -- | Perform alias analysis on a Futhark program. aliasAnalysis :: (Attributes lore, CanBeAliased (Op lore)) => Prog lore -> Prog (Aliases lore) analyseFun :: (Attributes lore, CanBeAliased (Op lore)) => FunDef lore -> FunDef (Aliases lore) analyseStm :: (Attributes lore, CanBeAliased (Op lore)) => Stm lore -> Stm (Aliases lore) analyseExp :: (Attributes lore, CanBeAliased (Op lore)) => Exp lore -> Exp (Aliases lore) analyseBody :: (Attributes lore, CanBeAliased (Op lore)) => Body lore -> Body (Aliases lore) analyseLambda :: (Attributes lore, CanBeAliased (Op lore)) => Lambda lore -> Lambda (Aliases lore) -- | Definition of the lore used by the simplification engine. module Futhark.Optimise.Simplify.Lore data Wise lore -- | The wisdom of the let-bound variable. data VarWisdom VarWisdom :: VarAliases -> Range -> VarWisdom [varWisdomAliases] :: VarWisdom -> VarAliases [varWisdomRange] :: VarWisdom -> Range -- | Wisdom about an expression. data ExpWisdom removeStmWisdom :: CanBeWise (Op lore) => Stm (Wise lore) -> Stm lore removeLambdaWisdom :: CanBeWise (Op lore) => Lambda (Wise lore) -> Lambda lore removeProgWisdom :: CanBeWise (Op lore) => Prog (Wise lore) -> Prog lore removeFunDefWisdom :: CanBeWise (Op lore) => FunDef (Wise lore) -> FunDef lore removeExpWisdom :: CanBeWise (Op lore) => Exp (Wise lore) -> Exp lore removePatternWisdom :: PatternT (VarWisdom, a) -> PatternT a removePatElemWisdom :: PatElemT (VarWisdom, a) -> PatElemT a removeBodyWisdom :: CanBeWise (Op lore) => Body (Wise lore) -> Body lore removeScopeWisdom :: Scope (Wise lore) -> Scope lore addScopeWisdom :: Scope lore -> Scope (Wise lore) addWisdomToPattern :: (Attributes lore, CanBeWise (Op lore)) => Pattern lore -> Exp (Wise lore) -> Pattern (Wise lore) mkWiseBody :: (Attributes lore, CanBeWise (Op lore)) => BodyAttr lore -> Stms (Wise lore) -> Result -> Body (Wise lore) mkWiseLetStm :: (Attributes lore, CanBeWise (Op lore)) => Pattern lore -> StmAux (ExpAttr lore) -> Exp (Wise lore) -> Stm (Wise lore) mkWiseExpAttr :: (Attributes lore, CanBeWise (Op lore)) => Pattern (Wise lore) -> ExpAttr lore -> Exp (Wise lore) -> ExpAttr (Wise lore) class (AliasedOp (OpWithWisdom op), RangedOp (OpWithWisdom op), IsOp (OpWithWisdom op), UsageInOp (OpWithWisdom op)) => CanBeWise op where { type family OpWithWisdom op :: *; } removeOpWisdom :: CanBeWise op => OpWithWisdom op -> op instance GHC.Show.Show Futhark.Optimise.Simplify.Lore.BodyWisdom instance GHC.Classes.Ord Futhark.Optimise.Simplify.Lore.BodyWisdom instance GHC.Classes.Eq Futhark.Optimise.Simplify.Lore.BodyWisdom instance GHC.Show.Show Futhark.Optimise.Simplify.Lore.ExpWisdom instance GHC.Classes.Ord Futhark.Optimise.Simplify.Lore.ExpWisdom instance GHC.Classes.Eq Futhark.Optimise.Simplify.Lore.ExpWisdom instance GHC.Show.Show Futhark.Optimise.Simplify.Lore.VarWisdom instance GHC.Classes.Ord Futhark.Optimise.Simplify.Lore.VarWisdom instance GHC.Classes.Eq Futhark.Optimise.Simplify.Lore.VarWisdom instance (Futhark.Representation.AST.Annotations.Annotations lore, Futhark.Optimise.Simplify.Lore.CanBeWise (Futhark.Representation.AST.Annotations.Op lore)) => Futhark.Representation.AST.Annotations.Annotations (Futhark.Optimise.Simplify.Lore.Wise lore) instance (Futhark.Representation.AST.Attributes.Attributes lore, Futhark.Optimise.Simplify.Lore.CanBeWise (Futhark.Representation.AST.Annotations.Op lore)) => Futhark.Representation.AST.Attributes.Attributes (Futhark.Optimise.Simplify.Lore.Wise lore) instance (Futhark.Representation.AST.Pretty.PrettyLore lore, Futhark.Optimise.Simplify.Lore.CanBeWise (Futhark.Representation.AST.Annotations.Op lore)) => Futhark.Representation.AST.Pretty.PrettyLore (Futhark.Optimise.Simplify.Lore.Wise lore) instance (Futhark.Representation.AST.Attributes.Attributes lore, Futhark.Optimise.Simplify.Lore.CanBeWise (Futhark.Representation.AST.Annotations.Op lore)) => Futhark.Representation.AST.Attributes.Aliases.Aliased (Futhark.Optimise.Simplify.Lore.Wise lore) instance (Futhark.Binder.Class.Bindable lore, Futhark.Optimise.Simplify.Lore.CanBeWise (Futhark.Representation.AST.Annotations.Op lore)) => Futhark.Binder.Class.Bindable (Futhark.Optimise.Simplify.Lore.Wise lore) instance Futhark.Optimise.Simplify.Lore.CanBeWise () instance Futhark.Transform.Rename.Rename Futhark.Optimise.Simplify.Lore.BodyWisdom instance Futhark.Transform.Substitute.Substitute Futhark.Optimise.Simplify.Lore.BodyWisdom instance Futhark.Representation.AST.Attributes.Names.FreeIn Futhark.Optimise.Simplify.Lore.BodyWisdom instance Futhark.Representation.AST.Attributes.Names.FreeAttr Futhark.Optimise.Simplify.Lore.BodyWisdom instance Futhark.Representation.AST.Attributes.Ranges.RangesOf (Futhark.Optimise.Simplify.Lore.BodyWisdom, attr) instance Futhark.Representation.AST.Attributes.Names.FreeIn Futhark.Optimise.Simplify.Lore.ExpWisdom instance Futhark.Representation.AST.Attributes.Names.FreeAttr Futhark.Optimise.Simplify.Lore.ExpWisdom instance Futhark.Transform.Substitute.Substitute Futhark.Optimise.Simplify.Lore.ExpWisdom instance Futhark.Transform.Rename.Rename Futhark.Optimise.Simplify.Lore.ExpWisdom instance Futhark.Transform.Rename.Rename Futhark.Optimise.Simplify.Lore.VarWisdom instance Futhark.Transform.Substitute.Substitute Futhark.Optimise.Simplify.Lore.VarWisdom instance Futhark.Representation.AST.Attributes.Names.FreeIn Futhark.Optimise.Simplify.Lore.VarWisdom instance Futhark.Representation.AST.Pretty.PrettyAnnot (Futhark.Representation.AST.Syntax.Core.PatElemT attr) => Futhark.Representation.AST.Pretty.PrettyAnnot (Futhark.Representation.AST.Syntax.Core.PatElemT (Futhark.Optimise.Simplify.Lore.VarWisdom, attr)) instance Futhark.Representation.AST.Attributes.Aliases.AliasesOf (Futhark.Optimise.Simplify.Lore.VarWisdom, attr) instance Futhark.Representation.AST.Attributes.Ranges.RangeOf (Futhark.Optimise.Simplify.Lore.VarWisdom, attr) module Futhark.Construct letSubExp :: MonadBinder m => String -> Exp (Lore m) -> m SubExp letSubExps :: MonadBinder m => String -> [Exp (Lore m)] -> m [SubExp] letExp :: MonadBinder m => String -> Exp (Lore m) -> m VName letExps :: MonadBinder m => String -> [Exp (Lore m)] -> m [VName] letTupExp :: MonadBinder m => String -> Exp (Lore m) -> m [VName] letTupExp' :: MonadBinder m => String -> Exp (Lore m) -> m [SubExp] letInPlace :: MonadBinder m => String -> VName -> Slice SubExp -> Exp (Lore m) -> m VName eSubExp :: MonadBinder m => SubExp -> m (Exp (Lore m)) eIf :: (MonadBinder m, BranchType (Lore m) ~ ExtType) => m (Exp (Lore m)) -> m (Body (Lore m)) -> m (Body (Lore m)) -> m (Exp (Lore m)) -- | As eIf, but an IfSort can be given. eIf' :: (MonadBinder m, BranchType (Lore m) ~ ExtType) => m (Exp (Lore m)) -> m (Body (Lore m)) -> m (Body (Lore m)) -> IfSort -> m (Exp (Lore m)) eBinOp :: MonadBinder m => BinOp -> m (Exp (Lore m)) -> m (Exp (Lore m)) -> m (Exp (Lore m)) eCmpOp :: MonadBinder m => CmpOp -> m (Exp (Lore m)) -> m (Exp (Lore m)) -> m (Exp (Lore m)) eConvOp :: MonadBinder m => ConvOp -> m (Exp (Lore m)) -> m (Exp (Lore m)) eNegate :: MonadBinder m => m (Exp (Lore m)) -> m (Exp (Lore m)) eNot :: MonadBinder m => m (Exp (Lore m)) -> m (Exp (Lore m)) eAbs :: MonadBinder m => m (Exp (Lore m)) -> m (Exp (Lore m)) eSignum :: MonadBinder m => m (Exp (Lore m)) -> m (Exp (Lore m)) eCopy :: MonadBinder m => m (Exp (Lore m)) -> m (Exp (Lore m)) eAssert :: MonadBinder m => m (Exp (Lore m)) -> ErrorMsg SubExp -> SrcLoc -> m (Exp (Lore m)) eBody :: MonadBinder m => [m (Exp (Lore m))] -> m (Body (Lore m)) eLambda :: MonadBinder m => Lambda (Lore m) -> [m (Exp (Lore m))] -> m [SubExp] -- | Note: unsigned division. eDivRoundingUp :: MonadBinder m => IntType -> m (Exp (Lore m)) -> m (Exp (Lore m)) -> m (Exp (Lore m)) eRoundToMultipleOf :: MonadBinder m => IntType -> m (Exp (Lore m)) -> m (Exp (Lore m)) -> m (Exp (Lore m)) -- | Construct an Index expressions that slices an array with unit -- stride. eSliceArray :: MonadBinder m => Int -> VName -> m (Exp (Lore m)) -> m (Exp (Lore m)) -> m (Exp (Lore m)) -- | Construct an Index expressions that splits an array in -- different parts along the outer dimension. eSplitArray :: MonadBinder m => VName -> [m (Exp (Lore m))] -> m [Exp (Lore m)] -- | Write to an index of the array, if within bounds. Otherwise, nothing. -- Produces the updated array. eWriteArray :: (MonadBinder m, BranchType (Lore m) ~ ExtType) => VName -> [m (Exp (Lore m))] -> m (Exp (Lore m)) -> m (Exp (Lore m)) -- | Zero-extend to the given integer type. asIntZ :: MonadBinder m => IntType -> SubExp -> m SubExp -- | Sign-extend to the given integer type. asIntS :: MonadBinder m => IntType -> SubExp -> m SubExp -- | Conveniently construct a body that contains no bindings. resultBody :: Bindable lore => [SubExp] -> Body lore -- | Conveniently construct a body that contains no bindings - but this -- time, monadically! resultBodyM :: MonadBinder m => [SubExp] -> m (Body (Lore m)) -- | Evaluate the action, producing a body, then wrap it in all the -- bindings it created using addStm. insertStmsM :: MonadBinder m => m (Body (Lore m)) -> m (Body (Lore m)) -- | Change that result where evaluation of the body would stop. Also -- change type annotations at branches. mapResult :: Bindable lore => (Result -> Body lore) -> Body lore -> Body lore -- | Apply a binary operator to several subexpressions. A left-fold. foldBinOp :: MonadBinder m => BinOp -> SubExp -> [SubExp] -> m (Exp (Lore m)) -- | Create a two-parameter lambda whose body applies the given binary -- operation to its arguments. It is assumed that both argument and -- result types are the same. (This assumption should be fixed at some -- point.) binOpLambda :: (MonadBinder m, Bindable (Lore m)) => BinOp -> PrimType -> m (Lambda (Lore m)) -- | As binOpLambda, but for BasicOps. cmpOpLambda :: (MonadBinder m, Bindable (Lore m)) => CmpOp -> PrimType -> m (Lambda (Lore m)) -- | fullSlice t slice returns slice, but with -- DimSlices of entire dimensions appended to the full -- dimensionality of t. This function is used to turn incomplete -- indexing complete, as required by Index. fullSlice :: Type -> [DimIndex SubExp] -> Slice SubExp -- | Like fullSlice, but the dimensions are simply numeric. fullSliceNum :: Num d => [d] -> [DimIndex d] -> Slice d -- | Does the slice describe the full size of the array? The most obvious -- such slice is one that DimSlices the full span of every -- dimension, but also one that fixes all unit dimensions. isFullSlice :: Shape -> Slice SubExp -> Bool ifCommon :: [Type] -> IfAttr ExtType -- | Instantiate all existential parts dimensions of the given type, using -- a monadic action to create the necessary BasicOps. You should -- call this function within some monad that allows you to collect the -- actions performed (say, Writer). instantiateShapes :: Monad m => (Int -> m SubExp) -> [TypeBase ExtShape u] -> m [TypeBase Shape u] instantiateShapes' :: MonadFreshNames m => [TypeBase ExtShape u] -> m ([TypeBase Shape u], [Ident]) instantiateShapesFromIdentList :: [Ident] -> [ExtType] -> [Type] instantiateExtTypes :: [VName] -> [ExtType] -> [Ident] instantiateIdents :: [VName] -> [ExtType] -> Maybe ([Ident], [Ident]) removeExistentials :: ExtType -> Type -> Type -- | Can be used as the definition of mkLetNames for a -- Bindable instance for simple representations. simpleMkLetNames :: (ExpAttr lore ~ (), LetAttr lore ~ Type, MonadFreshNames m, TypedOp (Op lore), HasScope lore m) => [VName] -> Exp lore -> m (Stm lore) -- | Instances of this class can be converted to Futhark expressions within -- a MonadBinder. class ToExp a toExp :: (ToExp a, MonadBinder m) => a -> m (Exp (Lore m)) instance Futhark.Construct.ToExp Futhark.Representation.AST.Syntax.Core.SubExp instance Futhark.Construct.ToExp Language.Futhark.Core.VName -- | The type checker checks whether the program is type-consistent. module Futhark.TypeCheck -- | Type check a program containing arbitrary type information, yielding -- either a type error or a program with complete type information. checkProg :: Checkable lore => Prog lore -> Either (TypeError lore) () -- | A type error. data TypeError lore Error :: [String] -> ErrorCase lore -> TypeError lore -- | Information about an error during type checking. The Show -- instance for this type produces a human-readable description. data ErrorCase lore TypeError :: String -> ErrorCase lore UnexpectedType :: Exp lore -> Type -> [Type] -> ErrorCase lore ReturnTypeError :: Name -> [ExtType] -> [ExtType] -> ErrorCase lore DupDefinitionError :: Name -> ErrorCase lore DupParamError :: Name -> VName -> ErrorCase lore DupPatternError :: VName -> ErrorCase lore InvalidPatternError :: Pattern (Aliases lore) -> [ExtType] -> Maybe String -> ErrorCase lore UnknownVariableError :: VName -> ErrorCase lore UnknownFunctionError :: Name -> ErrorCase lore ParameterMismatch :: Maybe Name -> [Type] -> [Type] -> ErrorCase lore SlicingError :: Int -> Int -> ErrorCase lore BadAnnotation :: String -> Type -> Type -> ErrorCase lore ReturnAliased :: Name -> VName -> ErrorCase lore UniqueReturnAliased :: Name -> ErrorCase lore NotAnArray :: VName -> Type -> ErrorCase lore PermutationError :: [Int] -> Int -> Maybe VName -> ErrorCase lore -- | The type checker runs in this monad. data TypeM lore a bad :: ErrorCase lore -> TypeM lore a -- | Add information about what is being type-checked to the current -- context. Liberal use of this combinator makes it easier to track type -- errors, as the strings are added to type errors signalled via -- bad. context :: String -> TypeM lore a -> TypeM lore a message :: Pretty a => String -> a -> String -- | The class of lores that can be type-checked. class (Attributes lore, CanBeAliased (Op lore)) => Checkable lore checkExpLore :: Checkable lore => ExpAttr lore -> TypeM lore () checkBodyLore :: Checkable lore => BodyAttr lore -> TypeM lore () checkFParamLore :: Checkable lore => VName -> FParamAttr lore -> TypeM lore () checkLParamLore :: Checkable lore => VName -> LParamAttr lore -> TypeM lore () checkLetBoundLore :: Checkable lore => VName -> LetAttr lore -> TypeM lore () checkRetType :: Checkable lore => [RetType lore] -> TypeM lore () checkOp :: Checkable lore => OpWithAliases (Op lore) -> TypeM lore () matchPattern :: Checkable lore => Pattern (Aliases lore) -> Exp (Aliases lore) -> TypeM lore () primFParam :: Checkable lore => VName -> PrimType -> TypeM lore (FParam (Aliases lore)) primLParam :: Checkable lore => VName -> PrimType -> TypeM lore (LParam (Aliases lore)) matchReturnType :: Checkable lore => [RetType lore] -> Result -> TypeM lore () matchBranchType :: Checkable lore => [BranchType lore] -> Body (Aliases lore) -> TypeM lore () lookupVar :: VName -> TypeM lore (NameInfo (Aliases lore)) lookupAliases :: Checkable lore => VName -> TypeM lore Names type Occurences = [Occurence] type UsageMap = Map VName [Usage] usageMap :: Occurences -> UsageMap collectOccurences :: TypeM lore a -> TypeM lore (a, Occurences) subCheck :: forall lore newlore a. (Checkable newlore, RetType lore ~ RetType newlore, LetAttr lore ~ LetAttr newlore, FParamAttr lore ~ FParamAttr newlore, LParamAttr lore ~ LParamAttr newlore) => TypeM newlore a -> TypeM lore a -- | require ts se causes a '(TypeError vn)' if the type of -- se is not a subtype of one of the types in ts. require :: Checkable lore => [Type] -> SubExp -> TypeM lore () -- | Variant of require working on variable names. requireI :: Checkable lore => [Type] -> VName -> TypeM lore () requirePrimExp :: Checkable lore => PrimType -> PrimExp VName -> TypeM lore () checkSubExp :: Checkable lore => SubExp -> TypeM lore Type checkExp :: Checkable lore => Exp (Aliases lore) -> TypeM lore () checkStms :: Checkable lore => Stms (Aliases lore) -> TypeM lore a -> TypeM lore a checkStm :: Checkable lore => Stm (Aliases lore) -> TypeM lore a -> TypeM lore a checkType :: Checkable lore => TypeBase Shape u -> TypeM lore () checkExtType :: Checkable lore => TypeBase ExtShape u -> TypeM lore () matchExtPattern :: Checkable lore => Pattern (Aliases lore) -> [ExtType] -> TypeM lore () matchExtReturnType :: Checkable lore => [ExtType] -> Result -> TypeM lore () matchExtBranchType :: Checkable lore => [ExtType] -> Body (Aliases lore) -> TypeM lore () argType :: Arg -> Type -- | Remove all aliases from the Arg. argAliases :: Arg -> Names noArgAliases :: Arg -> Arg checkArg :: Checkable lore => SubExp -> TypeM lore Arg checkSOACArrayArgs :: Checkable lore => SubExp -> [VName] -> TypeM lore [Arg] checkLambda :: Checkable lore => Lambda (Aliases lore) -> [Arg] -> TypeM lore () checkFun' :: Checkable lore => (Name, [DeclExtType], [(VName, NameInfo (Aliases lore))], BodyT (Aliases lore)) -> [(VName, Names)] -> TypeM lore () -> TypeM lore () checkLambdaParams :: Checkable lore => [LParam lore] -> TypeM lore () checkBody :: Checkable lore => Body (Aliases lore) -> TypeM lore () checkLambdaBody :: Checkable lore => [Type] -> Body (Aliases lore) -> TypeM lore () -- | Proclaim that we have written to the given variable. consume :: Names -> TypeM lore () -- | Permit consumption of only the specified names. If one of these names -- is consumed, the consumption will be rewritten to be a consumption of -- the corresponding alias set. Consumption of anything else will result -- in a type error. consumeOnlyParams :: [(VName, Names)] -> TypeM lore a -> TypeM lore a binding :: Checkable lore => Scope (Aliases lore) -> TypeM lore a -> TypeM lore a instance Control.Monad.State.Class.MonadState Futhark.Representation.AST.Syntax.Core.Names (Futhark.TypeCheck.TypeM lore) instance Control.Monad.Writer.Class.MonadWriter Futhark.TypeCheck.Consumption (Futhark.TypeCheck.TypeM lore) instance Control.Monad.Reader.Class.MonadReader (Futhark.TypeCheck.Env lore) (Futhark.TypeCheck.TypeM lore) instance GHC.Base.Applicative (Futhark.TypeCheck.TypeM lore) instance GHC.Base.Functor (Futhark.TypeCheck.TypeM lore) instance GHC.Base.Monad (Futhark.TypeCheck.TypeM lore) instance GHC.Show.Show Futhark.TypeCheck.Consumption instance GHC.Show.Show Futhark.TypeCheck.Occurence instance GHC.Classes.Eq Futhark.TypeCheck.Occurence instance GHC.Show.Show Futhark.TypeCheck.Usage instance GHC.Classes.Ord Futhark.TypeCheck.Usage instance GHC.Classes.Eq Futhark.TypeCheck.Usage instance Futhark.TypeCheck.Checkable lore => GHC.Show.Show (Futhark.TypeCheck.ErrorCase lore) instance Futhark.TypeCheck.Checkable lore => GHC.Show.Show (Futhark.TypeCheck.TypeError lore) instance Futhark.TypeCheck.Checkable lore => Futhark.Representation.AST.Attributes.Scope.HasScope (Futhark.Representation.Aliases.Aliases lore) (Futhark.TypeCheck.TypeM lore) instance GHC.Base.Semigroup Futhark.TypeCheck.Consumption instance GHC.Base.Monoid Futhark.TypeCheck.Consumption module Futhark.Pipeline data Pipeline fromlore tolore data PipelineConfig PipelineConfig :: Bool -> Bool -> PipelineConfig [pipelineVerbose] :: PipelineConfig -> Bool [pipelineValidate] :: PipelineConfig -> Bool data Action lore Action :: String -> String -> (Prog lore -> FutharkM ()) -> Action lore [actionName] :: Action lore -> String [actionDescription] :: Action lore -> String [actionProcedure] :: Action lore -> Prog lore -> FutharkM () data FutharkM a runFutharkM :: FutharkM a -> Verbosity -> IO (Either CompilerError a) -- | If Verbose, print log messages to standard error. If VeryVerbose, also -- print logs from individual passes. data Verbosity NotVerbose :: Verbosity Verbose :: Verbosity VeryVerbose :: Verbosity internalErrorS :: Pretty t => String -> t -> FutharkM a onePass :: (Checkable fromlore, Checkable tolore) => Pass fromlore tolore -> Pipeline fromlore tolore passes :: Checkable lore => [Pass lore lore] -> Pipeline lore lore runPasses :: Pipeline fromlore tolore -> PipelineConfig -> Prog fromlore -> FutharkM (Prog tolore) runPipeline :: Pipeline fromlore tolore -> PipelineConfig -> Prog fromlore -> Action tolore -> FutharkM () instance Control.Monad.IO.Class.MonadIO Futhark.Pipeline.FutharkM instance Control.Monad.Reader.Class.MonadReader Futhark.Pipeline.FutharkEnv Futhark.Pipeline.FutharkM instance Control.Monad.State.Class.MonadState Futhark.Pipeline.FutharkState Futhark.Pipeline.FutharkM instance Control.Monad.Error.Class.MonadError Futhark.Error.CompilerError Futhark.Pipeline.FutharkM instance GHC.Base.Monad Futhark.Pipeline.FutharkM instance GHC.Base.Functor Futhark.Pipeline.FutharkM instance GHC.Base.Applicative Futhark.Pipeline.FutharkM instance GHC.Classes.Ord Futhark.Pipeline.Verbosity instance GHC.Classes.Eq Futhark.Pipeline.Verbosity instance Control.Category.Category Futhark.Pipeline.Pipeline instance Futhark.MonadFreshNames.MonadFreshNames Futhark.Pipeline.FutharkM instance Futhark.Util.Log.MonadLogger Futhark.Pipeline.FutharkM module Futhark.Internalise.AccurateSizes shapeBody :: (HasScope lore m, MonadFreshNames m, BinderOps lore, Bindable lore) => [VName] -> [Type] -> Body lore -> m (Body lore) annotateArrayShape :: ArrayShape shape => TypeBase shape u -> [Int] -> TypeBase Shape u argShapes :: [VName] -> [TypeBase Shape u0] -> [TypeBase Shape u1] -> [SubExp] ensureResultShape :: MonadBinder m => (m Certificates -> m Certificates) -> ErrorMsg SubExp -> SrcLoc -> [Type] -> Body (Lore m) -> m (Body (Lore m)) ensureResultExtShape :: MonadBinder m => (m Certificates -> m Certificates) -> ErrorMsg SubExp -> SrcLoc -> [ExtType] -> Body (Lore m) -> m (Body (Lore m)) ensureResultExtShapeNoCtx :: MonadBinder m => (m Certificates -> m Certificates) -> ErrorMsg SubExp -> SrcLoc -> [ExtType] -> Body (Lore m) -> m (Body (Lore m)) ensureExtShape :: MonadBinder m => (m Certificates -> m Certificates) -> ErrorMsg SubExp -> SrcLoc -> ExtType -> String -> SubExp -> m SubExp ensureShape :: MonadBinder m => (m Certificates -> m Certificates) -> ErrorMsg SubExp -> SrcLoc -> Type -> String -> SubExp -> m SubExp -- | Reshape the arguments to a function so that they fit the expected -- shape declarations. Not used to change rank of arguments. Assumes -- everything is otherwise type-correct. ensureArgShapes :: (MonadBinder m, Typed (TypeBase Shape u)) => (m Certificates -> m Certificates) -> ErrorMsg SubExp -> SrcLoc -> [VName] -> [TypeBase Shape u] -> [SubExp] -> m [SubExp] -- | Converting back and forth between PrimExps. module Futhark.Analysis.PrimExp.Convert -- | Convert a PrimExp to a Futhark expression. The provided -- function converts the leaves. primExpToExp :: MonadBinder m => (v -> m (Exp (Lore m))) -> PrimExp v -> m (Exp (Lore m)) -- | Convert an expression to a PrimExp. The provided function is -- used to convert expressions that are not trivially PrimExps. -- This includes constants and variable names, which are passed as -- BasicOps. primExpFromExp :: (MonadFail m, Annotations lore) => (VName -> m (PrimExp v)) -> Exp lore -> m (PrimExp v) -- | Convert BasicOps of a given type. primExpFromSubExp :: PrimType -> SubExp -> PrimExp VName primExpFromSubExpM :: MonadFail m => (VName -> m (PrimExp v)) -> SubExp -> m (PrimExp v) -- | Applying a transformation to the leaves in a PrimExp. replaceInPrimExp :: (v -> PrimType -> PrimExp v) -> PrimExp v -> PrimExp v -- | Substituting names in a PrimExp with other PrimExps substituteInPrimExp :: Ord v => Map v (PrimExp v) -> PrimExp v -> PrimExp v instance Futhark.Construct.ToExp v => Futhark.Construct.ToExp (Futhark.Analysis.PrimExp.PrimExp v) -- | An index function represents a mapping from an array index space to a -- flat byte offset. This implements a representation for the index -- function based on linear-memory accessor descriptors, see Zhu, -- Hoeflinger and David work. Our specific representation is: LMAD = -- overline{s,r,n}^k + o, where o is the offset, and -- s_j, r_j, and n_j are the stride, the -- rotate factor and the number of elements on dimension j. Dimensions -- are ordered in row major fashion. By definition, the LMAD above -- denotes the set of points: { o + Sigma_{j=0}^{k} ((i_j+r_j) mod -- n_j)*s_j, forall i_j such that 0<=i_j<n_j, j=1..k } module Futhark.Representation.ExplicitMemory.Lmad -- | LMAD algebra is closed under composition w.r.t. operators such as -- permute, repeat, index and slice. However, other operations, such as -- reshape, cannot be always represented inside the LMAD algebra. It -- follows that the general representation of an index function is a list -- of LMADS, in which each following LMAD in the list implicitly -- corresponds to an irregular reshaping operation. However, we expect -- that the common case is when the index function is one LMAD -- we call -- this the Nice representation. Finally, the list of LMADs is -- tupled with the shape of the original array, and with contiguous info, -- i.e., if we instantiate all the points of the current index function, -- do we get a contiguous memory interval? data IxFun num IxFun :: [Lmad num] -> Shape num -> Bool -> IxFun num -- | Computing the flat memory index for a complete set inds of -- array indices and a certain element size elem_size. index :: (IntegralExp num, Eq num) => IxFun num -> Indices num -> num -> num -- | iota iota :: IntegralExp num => Shape num -> IxFun num -- | results in the index function corresponding to indexing with -- i on the outermost dimension. offsetIndex :: (Eq num, IntegralExp num) => IxFun num -> num -> IxFun num -- | results in the index function corresponding to making the outermost -- dimension strided by s. strideIndex :: (Eq num, IntegralExp num) => IxFun num -> num -> IxFun num -- | permute dimensions permute :: IntegralExp num => IxFun num -> Permutation -> IxFun num -- | Rotating an index function: rotate :: (Eq num, IntegralExp num) => IxFun num -> Indices num -> IxFun num -- | Reshaping an index function. There are four conditions that all must -- hold for the result of a reshape operation to remain into the one-Lmad -- domain: (1) the permutation of the underlying Lmad must leave -- unchanged the Lmad dimensions that were *not* reshape coercions. (2) -- the repetition of dimensions of the underlying Lmad must refer only to -- the coerced-dimensions of the reshape operation. (3) similarly, the -- rotated dimensions must refer only to dimensions that are coerced by -- the reshape operation. (4) finally, the underlying memory is -- contiguous (and monotonous) -- -- If any of this conditions does not hold then the reshape operation -- will conservatively add a new Lmad to the list, leading to a -- representation that provides less opportunities for further analysis. -- -- Actually there are some special cases that need to be treated, for -- example if everything is a coercion, then it should succeed no matter -- what. reshape :: (Eq num, IntegralExp num) => IxFun num -> ShapeChange num -> IxFun num -- | Slicing an index function. slice :: (Eq num, IntegralExp num) => IxFun num -> Slice num -> IxFun num base :: IxFun num -> Shape num -- | Correctness assumption: the shape of the new base is equal to the base -- of the index function (to be rebased). rebase :: (Eq num, IntegralExp num) => IxFun num -> IxFun num -> IxFun num -- | repeating dimensions repeat :: (Eq num, IntegralExp num) => IxFun num -> [Shape num] -> Shape num -> IxFun num -- | whether an index function has contiguous memory support isContiguous :: (Eq num, IntegralExp num) => IxFun num -> Bool -- | Shape of an index function shape :: (Eq num, IntegralExp num) => IxFun num -> Shape num rank :: IntegralExp num => IxFun num -> Int getMonotonicity :: (Eq num, IntegralExp num) => IxFun num -> DimInfo -- | If the memory support of the index function is contiguous and -- row-major (i.e., no transpositions, repetitions, rotates, etc.), then -- this should return the offset from which the memory-support of this -- index function starts. linearWithOffset :: (Eq num, IntegralExp num) => IxFun num -> num -> Maybe num -- | Similar restrictions to linearWithOffset except for -- transpositions, which are returned together with the offset. rearrangeWithOffset :: (Eq num, IntegralExp num) => IxFun num -> num -> Maybe (num, [(Int, num)]) -- | whether this is a row-major array isDirect :: (Eq num, IntegralExp num) => IxFun num -> Bool isLinear :: (Eq num, IntegralExp num) => IxFun num -> Bool -- | Substituting a name with a PrimExp in an index function. substituteInIxFun :: Map VName (PrimExp VName) -> IxFun (PrimExp VName) -> IxFun (PrimExp VName) instance GHC.Classes.Eq num => GHC.Classes.Eq (Futhark.Representation.ExplicitMemory.Lmad.IxFun num) instance GHC.Show.Show num => GHC.Show.Show (Futhark.Representation.ExplicitMemory.Lmad.IxFun num) instance GHC.Classes.Eq num => GHC.Classes.Eq (Futhark.Representation.ExplicitMemory.Lmad.Lmad num) instance GHC.Show.Show num => GHC.Show.Show (Futhark.Representation.ExplicitMemory.Lmad.Lmad num) instance GHC.Classes.Eq Futhark.Representation.ExplicitMemory.Lmad.DimInfo instance GHC.Show.Show Futhark.Representation.ExplicitMemory.Lmad.DimInfo instance Text.PrettyPrint.Mainland.Class.Pretty num => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.ExplicitMemory.Lmad.IxFun num) instance Futhark.Transform.Substitute.Substitute num => Futhark.Transform.Substitute.Substitute (Futhark.Representation.ExplicitMemory.Lmad.IxFun num) instance Futhark.Transform.Substitute.Substitute num => Futhark.Transform.Rename.Rename (Futhark.Representation.ExplicitMemory.Lmad.IxFun num) instance Futhark.Representation.AST.Attributes.Names.FreeIn num => Futhark.Representation.AST.Attributes.Names.FreeIn (Futhark.Representation.ExplicitMemory.Lmad.IxFun num) instance GHC.Base.Functor Futhark.Representation.ExplicitMemory.Lmad.IxFun instance Data.Foldable.Foldable Futhark.Representation.ExplicitMemory.Lmad.IxFun instance Data.Traversable.Traversable Futhark.Representation.ExplicitMemory.Lmad.IxFun instance Text.PrettyPrint.Mainland.Class.Pretty num => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.ExplicitMemory.Lmad.Lmad num) instance Futhark.Transform.Substitute.Substitute num => Futhark.Transform.Substitute.Substitute (Futhark.Representation.ExplicitMemory.Lmad.Lmad num) instance Futhark.Transform.Substitute.Substitute num => Futhark.Transform.Rename.Rename (Futhark.Representation.ExplicitMemory.Lmad.Lmad num) instance Futhark.Representation.AST.Attributes.Names.FreeIn num => Futhark.Representation.AST.Attributes.Names.FreeIn (Futhark.Representation.ExplicitMemory.Lmad.Lmad num) instance GHC.Base.Functor Futhark.Representation.ExplicitMemory.Lmad.Lmad instance Data.Foldable.Foldable Futhark.Representation.ExplicitMemory.Lmad.Lmad instance Data.Traversable.Traversable Futhark.Representation.ExplicitMemory.Lmad.Lmad instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Representation.ExplicitMemory.Lmad.DimInfo -- | An index function represents a mapping from an array index space to a -- flat byte offset. module Futhark.Representation.ExplicitMemory.IndexFunction data IxFun num index :: (Pretty num, IntegralExp num) => IxFun num -> Indices num -> num -> num iota :: Shape num -> IxFun num offsetIndex :: (Eq num, IntegralExp num) => IxFun num -> num -> IxFun num strideIndex :: (Eq num, IntegralExp num) => IxFun num -> num -> IxFun num permute :: IntegralExp num => IxFun num -> Permutation -> IxFun num rotate :: IntegralExp num => IxFun num -> Indices num -> IxFun num reshape :: (Eq num, IntegralExp num) => IxFun num -> ShapeChange num -> IxFun num slice :: (Eq num, IntegralExp num) => IxFun num -> Slice num -> IxFun num base :: IxFun num -> Shape num rebase :: (Eq num, IntegralExp num) => IxFun num -> IxFun num -> IxFun num repeat :: IxFun num -> [Shape num] -> Shape num -> IxFun num shape :: IntegralExp num => IxFun num -> Shape num rank :: IntegralExp num => IxFun num -> Int linearWithOffset :: (Eq num, IntegralExp num) => IxFun num -> num -> Maybe num rearrangeWithOffset :: (Eq num, IntegralExp num) => IxFun num -> num -> Maybe (num, [(Int, num)]) isLinear :: (Eq num, IntegralExp num) => IxFun num -> Bool isDirect :: IxFun num -> Bool -- | Substituting a name with a PrimExp in an index function. substituteInIxFun :: Ord a => Map a (PrimExp a) -> IxFun (PrimExp a) -> IxFun (PrimExp a) getInfoMaxUnification :: IxFn -> Maybe (IxFn, Slice (PrimExp VName), VName) subsInIndexIxFun :: IxFn -> VName -> VName -> IxFn ixFunsCompatibleRaw :: Eq num => IxFun num -> IxFun num -> Bool ixFunHasIndex :: IxFun num -> Bool offsetIndexDWIM :: Int -> IxFn -> PrimExp VName -> IxFn instance GHC.Show.Show num => GHC.Show.Show (Futhark.Representation.ExplicitMemory.IndexFunction.IxFun num) instance GHC.Classes.Eq num => GHC.Classes.Eq (Futhark.Representation.ExplicitMemory.IndexFunction.IxFun num) instance Text.PrettyPrint.Mainland.Class.Pretty num => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.ExplicitMemory.IndexFunction.IxFun num) instance Futhark.Transform.Substitute.Substitute num => Futhark.Transform.Substitute.Substitute (Futhark.Representation.ExplicitMemory.IndexFunction.IxFun num) instance Futhark.Representation.AST.Attributes.Names.FreeIn num => Futhark.Representation.AST.Attributes.Names.FreeIn (Futhark.Representation.ExplicitMemory.IndexFunction.IxFun num) instance GHC.Base.Functor Futhark.Representation.ExplicitMemory.IndexFunction.IxFun instance Data.Foldable.Foldable Futhark.Representation.ExplicitMemory.IndexFunction.IxFun instance Data.Traversable.Traversable Futhark.Representation.ExplicitMemory.IndexFunction.IxFun instance Futhark.Transform.Substitute.Substitute num => Futhark.Transform.Rename.Rename (Futhark.Representation.ExplicitMemory.IndexFunction.IxFun num) module Futhark.Analysis.SymbolTable data SymbolTable lore empty :: SymbolTable lore fromScope :: Attributes lore => Scope lore -> SymbolTable lore toScope :: SymbolTable lore -> Scope lore -- | Try to convert a symbol table for one representation into a symbol -- table for another. The two symbol tables will have the same keys, but -- some entries may be diferent (i.e. some expression entries will have -- been turned into free variable entries). castSymbolTable :: (SameScope from to, ExpAttr from ~ ExpAttr to, BodyAttr from ~ BodyAttr to, RetType from ~ RetType to, BranchType from ~ BranchType to) => SymbolTable from -> SymbolTable to data Entry lore deepen :: SymbolTable lore -> SymbolTable lore bindingDepth :: Entry lore -> Int valueRange :: Entry lore -> ScalExpRange loopVariable :: Entry lore -> Bool entryStm :: Entry lore -> Maybe (Stm lore) entryLetBoundAttr :: Entry lore -> Maybe (LetAttr lore) entryFParamLore :: Entry lore -> Maybe (FParamAttr lore) entryType :: Attributes lore => Entry lore -> Type asScalExp :: Entry lore -> Maybe ScalExp elem :: VName -> SymbolTable lore -> Bool lookup :: VName -> SymbolTable lore -> Maybe (Entry lore) lookupStm :: VName -> SymbolTable lore -> Maybe (Stm lore) lookupExp :: VName -> SymbolTable lore -> Maybe (Exp lore, Certificates) lookupBasicOp :: VName -> SymbolTable lore -> Maybe (BasicOp lore, Certificates) lookupType :: Attributes lore => VName -> SymbolTable lore -> Maybe Type lookupSubExp :: VName -> SymbolTable lore -> Maybe (SubExp, Certificates) lookupScalExp :: Attributes lore => VName -> SymbolTable lore -> Maybe ScalExp lookupValue :: VName -> SymbolTable lore -> Maybe (PrimValue, Certificates) lookupVar :: VName -> SymbolTable lore -> Maybe (VName, Certificates) lookupAliases :: VName -> SymbolTable lore -> Names index :: Attributes lore => VName -> [SubExp] -> SymbolTable lore -> Maybe (PrimExp VName, Certificates) index' :: VName -> [PrimExp VName] -> SymbolTable lore -> Maybe (PrimExp VName, Certificates) class IndexOp op indexOp :: (IndexOp op, Attributes lore, IndexOp (Op lore)) => SymbolTable lore -> Int -> op -> [PrimExp VName] -> Maybe (PrimExp VName, Certificates) insertStm :: (IndexOp (Op lore), Ranged lore, Aliased lore) => Stm lore -> SymbolTable lore -> SymbolTable lore insertFParams :: Attributes lore => [FParam lore] -> SymbolTable lore -> SymbolTable lore insertLParam :: Attributes lore => LParam lore -> SymbolTable lore -> SymbolTable lore insertArrayLParam :: Attributes lore => LParam lore -> Maybe VName -> SymbolTable lore -> SymbolTable lore insertChunkLParam :: Attributes lore => VName -> LParam lore -> VName -> SymbolTable lore -> SymbolTable lore insertLoopVar :: Attributes lore => VName -> IntType -> SubExp -> SymbolTable lore -> SymbolTable lore updateBounds :: Attributes lore => Bool -> SubExp -> SymbolTable lore -> SymbolTable lore setUpperBound :: VName -> ScalExp -> SymbolTable lore -> SymbolTable lore setLowerBound :: VName -> ScalExp -> SymbolTable lore -> SymbolTable lore isAtLeast :: VName -> Int -> SymbolTable lore -> SymbolTable lore enclosingLoopVars :: [VName] -> SymbolTable lore -> [VName] rangesRep :: SymbolTable lore -> RangesRep instance Futhark.Analysis.SymbolTable.IndexOp () instance GHC.Base.Semigroup (Futhark.Analysis.SymbolTable.SymbolTable lore) instance GHC.Base.Monoid (Futhark.Analysis.SymbolTable.SymbolTable lore) module Futhark.Representation.SOACS.SOAC data SOAC lore Stream :: SubExp -> StreamForm lore -> LambdaT lore -> [VName] -> SOAC lore Scatter :: SubExp -> LambdaT lore -> [VName] -> [(SubExp, Int, VName)] -> SOAC lore GenReduce :: SubExp -> [GenReduceOp lore] -> LambdaT lore -> [VName] -> SOAC lore -- | A combination of scan, reduction, and map. The first BasicOp is -- the size of the input arrays. The first 'Lambda'/'SubExp' pair is for -- scan and its neutral elements. The second is for the reduction. The -- final lambda is for the map part, and finally comes the input arrays. Screma :: SubExp -> ScremaForm lore -> [VName] -> SOAC lore CmpThreshold :: SubExp -> String -> SOAC lore data StreamForm lore Parallel :: StreamOrd -> Commutativity -> LambdaT lore -> [SubExp] -> StreamForm lore Sequential :: [SubExp] -> StreamForm lore -- | The essential parts of a Screma factored out (everything except -- the input arrays). data ScremaForm lore ScremaForm :: Scan lore -> Reduce lore -> LambdaT lore -> ScremaForm lore data GenReduceOp lore GenReduceOp :: SubExp -> [VName] -> [SubExp] -> LambdaT lore -> GenReduceOp lore [genReduceWidth] :: GenReduceOp lore -> SubExp [genReduceDest] :: GenReduceOp lore -> [VName] [genReduceNeutral] :: GenReduceOp lore -> [SubExp] [genReduceOp] :: GenReduceOp lore -> LambdaT lore type Scan lore = (LambdaT lore, [SubExp]) type Reduce lore = (Commutativity, LambdaT lore, [SubExp]) typeCheckSOAC :: Checkable lore => SOAC (Aliases lore) -> TypeM lore () getStreamOrder :: StreamForm lore -> StreamOrd -- | Get Stream's accumulators as a sub-expression list getStreamAccums :: StreamForm lore -> [SubExp] scremaType :: SubExp -> ScremaForm lore -> [Type] soacType :: SOAC lore -> [Type] -- | Construct a lambda that takes parameters of the given types and simply -- returns them unchanged. mkIdentityLambda :: (Bindable lore, MonadFreshNames m) => [Type] -> m (Lambda lore) -- | Is the given lambda an identity lambda? isIdentityLambda :: Lambda lore -> Bool composeLambda :: (Bindable lore, BinderOps lore, MonadFreshNames m, HasScope somelore m, SameScope somelore lore) => Lambda lore -> Lambda lore -> Lambda lore -> m (Lambda lore) -- | A lambda with no parameters that returns no values. nilFn :: Bindable lore => LambdaT lore scanomapSOAC :: Bindable lore => Lambda lore -> [SubExp] -> Lambda lore -> ScremaForm lore redomapSOAC :: Bindable lore => Commutativity -> Lambda lore -> [SubExp] -> Lambda lore -> ScremaForm lore scanSOAC :: (Bindable lore, MonadFreshNames m) => Lambda lore -> [SubExp] -> m (ScremaForm lore) reduceSOAC :: (Bindable lore, MonadFreshNames m) => Commutativity -> Lambda lore -> [SubExp] -> m (ScremaForm lore) mapSOAC :: Bindable lore => Lambda lore -> ScremaForm lore isScanomapSOAC :: ScremaForm lore -> Maybe (Lambda lore, [SubExp], Lambda lore) isRedomapSOAC :: ScremaForm lore -> Maybe (Commutativity, Lambda lore, [SubExp], Lambda lore) isScanSOAC :: ScremaForm lore -> Maybe (Lambda lore, [SubExp]) isReduceSOAC :: ScremaForm lore -> Maybe (Commutativity, Lambda lore, [SubExp]) isMapSOAC :: ScremaForm lore -> Maybe (Lambda lore) ppScrema :: (PrettyLore lore, Pretty inp) => SubExp -> ScremaForm lore -> [inp] -> Doc ppGenReduce :: (PrettyLore lore, Pretty inp) => SubExp -> [GenReduceOp lore] -> Lambda lore -> [inp] -> Doc -- | Like Mapper, but just for SOACs. data SOACMapper flore tlore m SOACMapper :: (SubExp -> m SubExp) -> (Lambda flore -> m (Lambda tlore)) -> (VName -> m VName) -> SOACMapper flore tlore m [mapOnSOACSubExp] :: SOACMapper flore tlore m -> SubExp -> m SubExp [mapOnSOACLambda] :: SOACMapper flore tlore m -> Lambda flore -> m (Lambda tlore) [mapOnSOACVName] :: SOACMapper flore tlore m -> VName -> m VName -- | A mapper that simply returns the SOAC verbatim. identitySOACMapper :: Monad m => SOACMapper lore lore m -- | Map a monadic action across the immediate children of a SOAC. The -- mapping does not descend recursively into subexpressions and is done -- left-to-right. mapSOACM :: (Applicative m, Monad m) => SOACMapper flore tlore m -> SOAC flore -> m (SOAC tlore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Show.Show (Futhark.Representation.SOACS.SOAC.SOAC lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Ord (Futhark.Representation.SOACS.SOAC.SOAC lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Eq (Futhark.Representation.SOACS.SOAC.SOAC lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Show.Show (Futhark.Representation.SOACS.SOAC.ScremaForm lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Ord (Futhark.Representation.SOACS.SOAC.ScremaForm lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Eq (Futhark.Representation.SOACS.SOAC.ScremaForm lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Show.Show (Futhark.Representation.SOACS.SOAC.StreamForm lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Ord (Futhark.Representation.SOACS.SOAC.StreamForm lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Eq (Futhark.Representation.SOACS.SOAC.StreamForm lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Show.Show (Futhark.Representation.SOACS.SOAC.GenReduceOp lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Ord (Futhark.Representation.SOACS.SOAC.GenReduceOp lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Eq (Futhark.Representation.SOACS.SOAC.GenReduceOp lore) instance Futhark.Representation.AST.Attributes.Attributes lore => Futhark.Representation.AST.Attributes.Names.FreeIn (Futhark.Representation.SOACS.SOAC.SOAC lore) instance Futhark.Representation.AST.Attributes.Attributes lore => Futhark.Transform.Substitute.Substitute (Futhark.Representation.SOACS.SOAC.SOAC lore) instance Futhark.Representation.AST.Attributes.Attributes lore => Futhark.Transform.Rename.Rename (Futhark.Representation.SOACS.SOAC.SOAC lore) instance (Futhark.Representation.AST.Attributes.Attributes lore, Futhark.Representation.AST.Attributes.Attributes (Futhark.Representation.Aliases.Aliases lore), Futhark.Representation.AST.Attributes.Aliases.CanBeAliased (Futhark.Representation.AST.Annotations.Op lore)) => Futhark.Representation.AST.Attributes.Aliases.CanBeAliased (Futhark.Representation.SOACS.SOAC.SOAC lore) instance (Futhark.Representation.AST.Attributes.Attributes lore, Futhark.Representation.AST.Attributes.Ranges.CanBeRanged (Futhark.Representation.AST.Annotations.Op lore)) => Futhark.Representation.AST.Attributes.Ranges.CanBeRanged (Futhark.Representation.SOACS.SOAC.SOAC lore) instance (Futhark.Representation.AST.Attributes.Attributes lore, Futhark.Optimise.Simplify.Lore.CanBeWise (Futhark.Representation.AST.Annotations.Op lore)) => Futhark.Optimise.Simplify.Lore.CanBeWise (Futhark.Representation.SOACS.SOAC.SOAC lore) instance Futhark.Representation.AST.Attributes.TypeOf.TypedOp (Futhark.Representation.SOACS.SOAC.SOAC lore) instance (Futhark.Representation.AST.Attributes.Attributes lore, Futhark.Representation.AST.Attributes.Aliases.Aliased lore) => Futhark.Representation.AST.Attributes.Aliases.AliasedOp (Futhark.Representation.SOACS.SOAC.SOAC lore) instance Futhark.Representation.AST.Attributes.Attributes lore => Futhark.Representation.AST.Attributes.IsOp (Futhark.Representation.SOACS.SOAC.SOAC lore) instance Futhark.Representation.AST.Attributes.Ranges.Ranged inner => Futhark.Representation.AST.Attributes.Ranges.RangedOp (Futhark.Representation.SOACS.SOAC.SOAC inner) instance Futhark.Representation.AST.Annotations.Annotations lore => Futhark.Analysis.SymbolTable.IndexOp (Futhark.Representation.SOACS.SOAC.SOAC lore) instance Futhark.Representation.AST.Attributes.Aliases.Aliased lore => Futhark.Analysis.Usage.UsageInOp (Futhark.Representation.SOACS.SOAC.SOAC lore) instance Futhark.Analysis.Metrics.OpMetrics (Futhark.Representation.AST.Annotations.Op lore) => Futhark.Analysis.Metrics.OpMetrics (Futhark.Representation.SOACS.SOAC.SOAC lore) instance Futhark.Representation.AST.Pretty.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.SOACS.SOAC.SOAC lore) module Futhark.Tools nonuniqueParams :: (MonadFreshNames m, Bindable lore, HasScope lore m, BinderOps lore) => [LParam lore] -> m ([LParam lore], Stms lore) -- | Turns a binding of a redomap into two seperate bindings, a -- map binding and a reduce binding (returned in that -- order). -- -- Reuses the original pattern for the reduce, and creates a new -- pattern with new Idents for the result of the map. -- -- Only handles a PatternT with an empty -- patternContextElements redomapToMapAndReduce :: (MonadFreshNames m, Bindable lore, ExpAttr lore ~ (), Op lore ~ SOAC lore) => Pattern lore -> (SubExp, Commutativity, LambdaT lore, LambdaT lore, [SubExp], [VName]) -> m (Stm lore, Stm lore) -- | Like redomapToMapAndReduce, but for Scanomap. scanomapToMapAndScan :: (MonadFreshNames m, Bindable lore, ExpAttr lore ~ (), Op lore ~ SOAC lore) => Pattern lore -> (SubExp, LambdaT lore, LambdaT lore, [SubExp], [VName]) -> m (Stm lore, Stm lore) -- | Turn a Screma into simpler Scremas that are all simple scans, reduces, -- and maps. This is used to handle Scremas that are so complicated that -- we cannot directly generate efficient parallel code for them. In -- essense, what happens is the opposite of horisontal fusion. dissectScrema :: (MonadBinder m, Op (Lore m) ~ SOAC (Lore m), Bindable (Lore m)) => Pattern (Lore m) -> SubExp -> ScremaForm (Lore m) -> [VName] -> m () sequentialStreamWholeArray :: (MonadBinder m, Bindable (Lore m)) => Pattern (Lore m) -> SubExp -> [SubExp] -> LambdaT (Lore m) -> [VName] -> m () partitionChunkedFoldParameters :: Int -> [Param attr] -> (Param attr, [Param attr], [Param attr]) partitionChunkedKernelLambdaParameters :: [Param attr] -> (VName, Param attr, [Param attr]) partitionChunkedKernelFoldParameters :: Int -> [Param attr] -> (VName, Param attr, [Param attr], [Param attr]) -- | This module exports facilities for transforming array accesses in a -- list of Stms (intended to be the bindings in a body). The idea -- is that you can state that some variable x is in fact an -- array indexing v[i0,i1,...]. module Futhark.Optimise.InPlaceLowering.SubstituteIndices substituteIndices :: (MonadFreshNames m, BinderOps lore, Bindable lore, Aliased lore, LetAttr lore ~ attr) => IndexSubstitutions attr -> Stms lore -> m (IndexSubstitutions attr, Stms lore) type IndexSubstitution attr = (Certificates, VName, attr, Slice SubExp) type IndexSubstitutions attr = [(VName, IndexSubstitution attr)] -- | A simple representation with SOACs and nested parallelism. module Futhark.Representation.SOACS -- | The lore for the basic representation. data SOACS type Prog = Prog SOACS type Body = Body SOACS type Stm = Stm SOACS type Pattern = Pattern SOACS type BasicOp = BasicOp SOACS type Exp = Exp SOACS type Lambda = Lambda SOACS type FunDef = FunDefT SOACS type FParam = FParam SOACS type LParam = LParam SOACS type RetType = RetType SOACS type PatElem = PatElem SOACS -- | 8-bit signed integer type data Int8 -- | 16-bit signed integer type data Int16 -- | 32-bit signed integer type data Int32 -- | 64-bit signed integer type data Int64 -- | 8-bit unsigned integer type data Word8 -- | 16-bit unsigned integer type data Word16 -- | 32-bit unsigned integer type data Word32 -- | 64-bit unsigned integer type data Word64 -- | Prettyprint a value, wrapped to 80 characters. pretty :: Pretty a => a -> String -- | Conversion operators try to generalise the from t0 x to t1 -- instructions from LLVM. data ConvOp -- | Zero-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. ZExt :: IntType -> IntType -> ConvOp -- | Sign-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. SExt :: IntType -> IntType -> ConvOp -- | Convert value of the former floating-point type to the latter. If the -- new type is smaller, the result is a truncation. FPConv :: FloatType -> FloatType -> ConvOp -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). FPToUI :: FloatType -> IntType -> ConvOp -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). FPToSI :: FloatType -> IntType -> ConvOp -- | Convert an unsigned integer to a floating-point value. UIToFP :: IntType -> FloatType -> ConvOp -- | Convert a signed integer to a floating-point value. SIToFP :: IntType -> FloatType -> ConvOp -- | Convert an integer to a boolean value. Zero becomes false; anything -- else is true. IToB :: IntType -> ConvOp -- | Convert a boolean to an integer. True is converted to 1 and False to -- 0. BToI :: IntType -> ConvOp -- | Comparison operators are like BinOps, but they return -- PrimTypes. The somewhat ugly constructor names are straight out -- of LLVM. data CmpOp -- | All types equality. CmpEq :: PrimType -> CmpOp -- | Unsigned less than. CmpUlt :: IntType -> CmpOp -- | Unsigned less than or equal. CmpUle :: IntType -> CmpOp -- | Signed less than. CmpSlt :: IntType -> CmpOp -- | Signed less than or equal. CmpSle :: IntType -> CmpOp -- | Floating-point less than. FCmpLt :: FloatType -> CmpOp -- | Floating-point less than or equal. FCmpLe :: FloatType -> CmpOp -- | Boolean less than. CmpLlt :: CmpOp -- | Boolean less than or equal. CmpLle :: CmpOp -- | Binary operators. These correspond closely to the binary operators in -- LLVM. Most are parametrised by their expected input and output types. data BinOp -- | Integer addition. Add :: IntType -> BinOp -- | Floating-point addition. FAdd :: FloatType -> BinOp -- | Integer subtraction. Sub :: IntType -> BinOp -- | Floating-point subtraction. FSub :: FloatType -> BinOp -- | Integer multiplication. Mul :: IntType -> BinOp -- | Floating-point multiplication. FMul :: FloatType -> BinOp -- | Unsigned integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. UDiv :: IntType -> BinOp -- | Signed integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. SDiv :: IntType -> BinOp -- | Floating-point division. FDiv :: FloatType -> BinOp -- | Unsigned integer modulus; the countepart to UDiv. UMod :: IntType -> BinOp -- | Signed integer modulus; the countepart to SDiv. SMod :: IntType -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- sdiv instruction in LLVM. SQuot :: IntType -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- srem instruction in LLVM. SRem :: IntType -> BinOp -- | Returns the smallest of two signed integers. SMin :: IntType -> BinOp -- | Returns the smallest of two unsigned integers. UMin :: IntType -> BinOp -- | Returns the smallest of two floating-point numbers. FMin :: FloatType -> BinOp -- | Returns the greatest of two signed integers. SMax :: IntType -> BinOp -- | Returns the greatest of two unsigned integers. UMax :: IntType -> BinOp -- | Returns the greatest of two floating-point numbers. FMax :: FloatType -> BinOp -- | Left-shift. Shl :: IntType -> BinOp -- | Logical right-shift, zero-extended. LShr :: IntType -> BinOp -- | Arithmetic right-shift, sign-extended. AShr :: IntType -> BinOp -- | Bitwise and. And :: IntType -> BinOp -- | Bitwise or. Or :: IntType -> BinOp -- | Bitwise exclusive-or. Xor :: IntType -> BinOp -- | Integer exponentiation. Pow :: IntType -> BinOp -- | Floating-point exponentiation. FPow :: FloatType -> BinOp -- | Boolean and - not short-circuiting. LogAnd :: BinOp -- | Boolean or - not short-circuiting. LogOr :: BinOp -- | Various unary operators. It is a bit ad-hoc what is a unary operator -- and what is a built-in function. Perhaps these should all go away -- eventually. data UnOp -- | E.g., ! True == False. Not :: UnOp -- | E.g., ~(~1) = 1. Complement :: IntType -> UnOp -- | abs(-2) = 2. Abs :: IntType -> UnOp -- | fabs(-2.0) = 2.0. FAbs :: FloatType -> UnOp -- | Signed sign function: ssignum(-2) = -1. SSignum :: IntType -> UnOp -- | Unsigned sign function: usignum(2) = 1. USignum :: IntType -> UnOp -- | Non-array values. data PrimValue IntValue :: !IntValue -> PrimValue FloatValue :: !FloatValue -> PrimValue BoolValue :: !Bool -> PrimValue -- | The only value of type cert. Checked :: PrimValue -- | A floating-point value. data FloatValue Float32Value :: !Float -> FloatValue Float64Value :: !Double -> FloatValue -- | An integer value. data IntValue Int8Value :: !Int8 -> IntValue Int16Value :: !Int16 -> IntValue Int32Value :: !Int32 -> IntValue Int64Value :: !Int64 -> IntValue -- | Low-level primitive types. data PrimType IntType :: IntType -> PrimType FloatType :: FloatType -> PrimType Bool :: PrimType Cert :: PrimType -- | A floating point type. data FloatType Float32 :: FloatType Float64 :: FloatType -- | An integer type, ordered by size. Note that signedness is not a -- property of the type, but a property of the operations performed on -- values of these types. data IntType Int8 :: IntType Int16 :: IntType Int32 :: IntType Int64 :: IntType -- | A list of all integer types. allIntTypes :: [IntType] -- | A list of all floating-point types. allFloatTypes :: [FloatType] -- | A list of all primitive types. allPrimTypes :: [PrimType] -- | Create an IntValue from a type and an Integer. intValue :: Integral int => IntType -> int -> IntValue intValueType :: IntValue -> IntType -- | Convert an IntValue to any Integral type. valueIntegral :: Integral int => IntValue -> int -- | Create a FloatValue from a type and a Rational. floatValue :: Real num => FloatType -> num -> FloatValue floatValueType :: FloatValue -> FloatType -- | The type of a basic value. primValueType :: PrimValue -> PrimType -- | A "blank" value of the given primitive type - this is zero, or -- whatever is close to it. Don't depend on this value, but use it for -- e.g. creating arrays to be populated by do-loops. blankPrimValue :: PrimType -> PrimValue -- | A list of all unary operators for all types. allUnOps :: [UnOp] -- | A list of all binary operators for all types. allBinOps :: [BinOp] -- | A list of all comparison operators for all types. allCmpOps :: [CmpOp] -- | A list of all conversion operators for all types. allConvOps :: [ConvOp] doUnOp :: UnOp -> PrimValue -> Maybe PrimValue -- | E.g., ~(~1) = 1. doComplement :: IntValue -> IntValue -- | abs(-2) = 2. doAbs :: IntValue -> IntValue -- | abs(-2.0) = 2.0. doFAbs :: FloatValue -> FloatValue -- | ssignum(-2) = -1. doSSignum :: IntValue -> IntValue -- | usignum(-2) = -1. doUSignum :: IntValue -> IntValue doBinOp :: BinOp -> PrimValue -> PrimValue -> Maybe PrimValue -- | Integer addition. doAdd :: IntValue -> IntValue -> IntValue -- | Integer multiplication. doMul :: IntValue -> IntValue -> IntValue -- | Signed integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. doSDiv :: IntValue -> IntValue -> Maybe IntValue -- | Signed integer modulus; the countepart to SDiv. doSMod :: IntValue -> IntValue -> Maybe IntValue -- | Signed integer exponentatation. doPow :: IntValue -> IntValue -> Maybe IntValue doConvOp :: ConvOp -> PrimValue -> Maybe PrimValue -- | Zero-extend the given integer value to the size of the given type. If -- the type is smaller than the given value, the result is a truncation. doZExt :: IntValue -> IntType -> IntValue -- | Sign-extend the given integer value to the size of the given type. If -- the type is smaller than the given value, the result is a truncation. doSExt :: IntValue -> IntType -> IntValue -- | Convert the former floating-point type to the latter. doFPConv :: FloatValue -> FloatType -> FloatValue -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). doFPToUI :: FloatValue -> IntType -> IntValue -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). doFPToSI :: FloatValue -> IntType -> IntValue -- | Convert an unsigned integer to a floating-point value. doUIToFP :: IntValue -> FloatType -> FloatValue -- | Convert a signed integer to a floating-point value. doSIToFP :: IntValue -> FloatType -> FloatValue doCmpOp :: CmpOp -> PrimValue -> PrimValue -> Maybe Bool -- | Compare any two primtive values for exact equality. doCmpEq :: PrimValue -> PrimValue -> Bool -- | Unsigned less than. doCmpUlt :: IntValue -> IntValue -> Bool -- | Unsigned less than or equal. doCmpUle :: IntValue -> IntValue -> Bool -- | Signed less than. doCmpSlt :: IntValue -> IntValue -> Bool -- | Signed less than or equal. doCmpSle :: IntValue -> IntValue -> Bool -- | Floating-point less than. doFCmpLt :: FloatValue -> FloatValue -> Bool -- | Floating-point less than or equal. doFCmpLe :: FloatValue -> FloatValue -> Bool -- | Translate an IntValue to Word64. This is guaranteed to -- fit. intToWord64 :: IntValue -> Word64 -- | Translate an IntValue to IntType. This is guaranteed to -- fit. intToInt64 :: IntValue -> Int64 -- | The result type of a binary operator. binOpType :: BinOp -> PrimType -- | The operand types of a comparison operator. cmpOpType :: CmpOp -> PrimType -- | The operand and result type of a unary operator. unOpType :: UnOp -> PrimType -- | The input and output types of a conversion operator. convOpType :: ConvOp -> (PrimType, PrimType) -- | A mapping from names of primitive functions to their parameter types, -- their result type, and a function for evaluating them. primFuns :: Map String ([PrimType], PrimType, [PrimValue] -> Maybe PrimValue) -- | Is the given value kind of zero? zeroIsh :: PrimValue -> Bool -- | Is the given value kind of one? oneIsh :: PrimValue -> Bool -- | Is the given value kind of negative? negativeIsh :: PrimValue -> Bool -- | The size of a value of a given primitive type in bites. primBitSize :: PrimType -> Int -- | The size of a value of a given primitive type in eight-bit bytes. primByteSize :: Num a => PrimType -> a -- | True if the given binary operator is commutative. commutativeBinOp :: BinOp -> Bool convOpFun :: ConvOp -> String -- | True if signed. Only makes a difference for integer types. prettySigned :: Bool -> PrimType -> String -- | A name tagged with some integer. Only the integer is used in -- comparisons, no matter the type of vn. data VName VName :: !Name -> !Int -> VName -- | The abstract (not really) type representing names in the Futhark -- compiler. Strings, being lists of characters, are very slow, -- while Texts are based on byte-arrays. data Name -- | Whether some operator is commutative or not. The Monoid -- instance returns the least commutative of its arguments. data Commutativity Noncommutative :: Commutativity Commutative :: Commutativity data StreamOrd InOrder :: StreamOrd Disorder :: StreamOrd -- | The uniqueness attribute of a type. This essentially indicates whether -- or not in-place modifications are acceptable. With respect to -- ordering, Unique is greater than Nonunique. data Uniqueness -- | May have references outside current function. Nonunique :: Uniqueness -- | No references outside current function. Unique :: Uniqueness -- | The name of the default program entry point (main). defaultEntryPoint :: Name -- | Convert a name to the corresponding list of characters. nameToString :: Name -> String -- | Convert a list of characters to the corresponding name. nameFromString :: String -> Name -- | Convert a name to the corresponding Text. nameToText :: Name -> Text -- | Convert a Text to the corresponding name. nameFromText :: Text -> Name -- | A human-readable location string, of the form -- filename:lineno:columnno. locStr :: SrcLoc -> String -- | Return the tag contained in the VName. baseTag :: VName -> Int -- | Return the name contained in the VName. baseName :: VName -> Name -- | Return the base Name converted to a string. baseString :: VName -> String -- | A part of an error message. data ErrorMsgPart a -- | A literal string. ErrorString :: String -> ErrorMsgPart a -- | A run-time integer value. ErrorInt32 :: a -> ErrorMsgPart a -- | An error message is a list of error parts, which are concatenated to -- form the final message. newtype ErrorMsg a ErrorMsg :: [ErrorMsgPart a] -> ErrorMsg a -- | A set of names. type Names = Set VName -- | An element of a pattern - consisting of an name (essentially a pair of -- the name andtype), a Bindage, and an addditional parametric -- attribute. This attribute is what is expected to contain the type of -- the resulting variable. data PatElemT attr -- | A list of DimFixs, indicating how an array should be sliced. -- Whenever a function accepts a Slice, that slice should be -- total, i.e, cover all dimensions of the array. Deviators should be -- indicated by taking a list of DimIndexes instead. type Slice d = [DimIndex d] -- | How to index a single dimension of an array. data DimIndex d -- | Fix index in this dimension. DimFix :: d -> DimIndex d -- | DimSlice start_offset num_elems stride. DimSlice :: d -> d -> d -> DimIndex d -- | A type alias for namespace control. type Param = ParamT -- | A function parameter. data ParamT attr Param :: VName -> attr -> ParamT attr -- | Name of the parameter. [paramName] :: ParamT attr -> VName -- | Function parameter attribute. [paramAttr] :: ParamT attr -> attr -- | A subexpression is either a scalar constant or a variable. One -- important property is that evaluation of a subexpression is guaranteed -- to complete in constant time. data SubExp Constant :: PrimValue -> SubExp Var :: VName -> SubExp -- | A list of names used for certificates in some expressions. newtype Certificates Certificates :: [VName] -> Certificates [unCertificates] :: Certificates -> [VName] -- | An identifier consists of its name and the type of the value bound to -- the identifier. data Ident Ident :: VName -> Type -> Ident [identName] :: Ident -> VName [identType] :: Ident -> Type -- | Information about which parts of a value/type are consumed. For -- example, we might say that a function taking three arguments of types -- ([int], *[int], [int]) has diet [Observe, Consume, -- Observe]. data Diet -- | Consumes this value. Consume :: Diet -- | Only observes value in this position, does not consume. Observe :: Diet -- | An ExtType with uniqueness information, used for function -- return types. type DeclExtType = TypeBase ExtShape Uniqueness -- | A type with shape and uniqueness information, used declaring return- -- and parameters types. type DeclType = TypeBase Shape Uniqueness -- | A type with existentially quantified shapes - used as part of function -- (and function-like) return types. Generally only makes sense when used -- in a list. type ExtType = TypeBase ExtShape NoUniqueness -- | A type with shape information, used for describing the type of -- variables. type Type = TypeBase Shape NoUniqueness -- | An Futhark type is either an array or an element type. When comparing -- types for equality with ==, shapes must match. data TypeBase shape u Prim :: PrimType -> TypeBase shape u Array :: PrimType -> shape -> u -> TypeBase shape u Mem :: SubExp -> Space -> TypeBase shape u -- | A fancier name for '()' - encodes no uniqueness information. data NoUniqueness NoUniqueness :: NoUniqueness -- | A string representing a specific non-default memory space. type SpaceId = String -- | The memory space of a block. If DefaultSpace, this is the -- "default" space, whatever that is. The exact meaning of the -- SpaceID depends on the backend used. In GPU kernels, for -- example, this is used to distinguish between constant, global and -- shared memory spaces. In GPU-enabled host code, it is used to -- distinguish between host memory (DefaultSpace) and GPU space. data Space DefaultSpace :: Space Space :: SpaceId -> Space -- | A class encompassing types containing array shape information. class (Monoid a, Eq a, Ord a) => ArrayShape a -- | Return the rank of an array with the given size. shapeRank :: ArrayShape a => a -> Int -- | stripDims n shape strips the outer n dimensions from -- shape. stripDims :: ArrayShape a => Int -> a -> a -- | Check whether one shape if a subset of another shape. subShapeOf :: ArrayShape a => a -> a -> Bool -- | The size of an array type as merely the number of dimensions, with no -- further information. newtype Rank Rank :: Int -> Rank -- | Like ShapeBase but some of its elements may be bound in a local -- environment instead. These are denoted with integral indices. type ExtShape = ShapeBase ExtSize -- | The size of this dimension. type ExtSize = Ext SubExp -- | Something that may be existential. data Ext a Ext :: Int -> Ext a Free :: a -> Ext a -- | The size of an array as a list of subexpressions. If a variable, that -- variable must be in scope where this array is used. type Shape = ShapeBase SubExp -- | The size of an array type as a list of its dimension sizes, with the -- type of sizes being parametric. newtype ShapeBase d Shape :: [d] -> ShapeBase d [shapeDims] :: ShapeBase d -> [d] -- | If the argument is a DimFix, return its component. dimFix :: DimIndex d -> Maybe d -- | If the slice is all DimFixs, return the components. sliceIndices :: Slice d -> Maybe [d] -- | The dimensions of the array produced by this slice. sliceDims :: Slice d -> [d] -- | A slice with a stride of one. unitSlice :: Num d => d -> d -> DimIndex d -- | Fix the DimSlices of a slice. The number of indexes must equal -- the length of sliceDims for the slice. fixSlice :: Num d => Slice d -> [d] -> [d] -- | A type representing the return type of a function. In practice, a list -- of these will be used. It should contain at least the information -- contained in an ExtType, but may have more, notably an -- existential context. class (Show rt, Eq rt, Ord rt, DeclExtTyped rt) => IsRetType rt -- | Contruct a return type from a primitive type. primRetType :: IsRetType rt => PrimType -> rt -- | Given a function return type, the parameters of the function, and the -- arguments for a concrete call, return the instantiated return type for -- the concrete call, if valid. applyRetType :: (IsRetType rt, Typed attr) => [rt] -> [Param attr] -> [(SubExp, Type)] -> Maybe [rt] -- | A type representing the return type of a body. It should contain at -- least the information contained in a list of ExtTypes, but may -- have more, notably an existential context. class (Show rt, Eq rt, Ord rt, ExtTyped rt) => IsBodyType rt -- | Construct a body type from a primitive type. primBodyType :: IsBodyType rt => PrimType -> rt bodyTypeValues :: IsBodyType rt => [rt] -> [ExtType] retTypeValues :: IsRetType rt => [rt] -> [DeclExtType] -- | Given shape parameter names and value parameter types, produce the -- types of arguments accepted. expectedTypes :: Typed t => [VName] -> [t] -> [SubExp] -> [Type] class (Show (LetAttr l), Show (ExpAttr l), Show (BodyAttr l), Show (FParamAttr l), Show (LParamAttr l), Show (RetType l), Show (BranchType l), Show (Op l), Eq (LetAttr l), Eq (ExpAttr l), Eq (BodyAttr l), Eq (FParamAttr l), Eq (LParamAttr l), Eq (RetType l), Eq (BranchType l), Eq (Op l), Ord (LetAttr l), Ord (ExpAttr l), Ord (BodyAttr l), Ord (FParamAttr l), Ord (LParamAttr l), Ord (RetType l), Ord (BranchType l), Ord (Op l), IsRetType (RetType l), IsBodyType (BranchType l), Typed (FParamAttr l), Typed (LParamAttr l), Typed (LetAttr l), DeclTyped (FParamAttr l)) => Annotations l where { -- | Annotation for every let-pattern element. type family LetAttr l :: *; -- | Annotation for every expression. type family ExpAttr l :: *; -- | Annotation for every body. type family BodyAttr l :: *; -- | Annotation for every (non-lambda) function parameter. type family FParamAttr l :: *; -- | Annotation for every lambda function parameter. type family LParamAttr l :: *; -- | The return type annotation of branches. type family BranchType l :: *; -- | Extensible operation. type family Op l :: *; type LetAttr l = Type; type ExpAttr l = (); type BodyAttr l = (); type FParamAttr l = DeclType; type LParamAttr l = Type; type RetType l = DeclExtType; type BranchType l = ExtType; type Op l = (); } -- | An entire Futhark program. data ProgT lore -- | Every entry point argument and return value has an annotation -- indicating how it maps to the original source program type. data EntryPointType -- | Is an unsigned integer or array of unsigned integers. TypeUnsigned :: EntryPointType -- | A black box type comprising this many core values. The string is a -- human-readable description with no other semantics. TypeOpaque :: String -> Int -> EntryPointType -- | Maps directly. TypeDirect :: EntryPointType -- | Information about the parameters and return value of an entry point. -- The first element is for parameters, the second for return value. type EntryPoint = ([EntryPointType], [EntryPointType]) -- | Function Declarations data FunDefT lore -- | Anonymous function for use in a SOAC. data LambdaT lore data IfSort -- | An ordinary branch. IfNormal :: IfSort -- | A branch where the "true" case is what we are actually interested in, -- and the "false" case is only present as a fallback for when the true -- case cannot be safely evaluated. the compiler is permitted to optimise -- away the branch if the true case contains only safe statements. IfFallback :: IfSort -- | Data associated with a branch. data IfAttr rt IfAttr :: [rt] -> IfSort -> IfAttr rt [ifReturns] :: IfAttr rt -> [rt] [ifSort] :: IfAttr rt -> IfSort -- | For-loop or while-loop? data LoopForm lore ForLoop :: VName -> IntType -> SubExp -> [(LParam lore, VName)] -> LoopForm lore WhileLoop :: VName -> LoopForm lore -- | Whether something is safe or unsafe (mostly function calls, and in the -- context of whether operations are dynamically checked). When we inline -- an Unsafe function, we remove all safety checks in its body. -- The Ord instance picks Unsafe as being less than -- Safe. data Safety Unsafe :: Safety Safe :: Safety -- | The root Futhark expression type. The ExpT constructor contains -- a lore-specific operation. Do-loops, branches and function calls are -- special. Everything else is a simple BasicOp. data ExpT lore Apply :: Name -> [(SubExp, Diet)] -> [RetType lore] -> (Safety, SrcLoc, [SrcLoc]) -> ExpT lore If :: SubExp -> BodyT lore -> BodyT lore -> IfAttr (BranchType lore) -> ExpT lore -- | loop {a} = {v} (for i < n|while b) do b. The merge -- parameters are divided into context and value part. DoLoop :: [(FParam lore, SubExp)] -> [(FParam lore, SubExp)] -> LoopForm lore -> BodyT lore -> ExpT lore Op :: Op lore -> ExpT lore -- | Semantically and operationally just identity, but is -- invisible/impenetrable to optimisations (hopefully). This is just a -- hack to avoid optimisation (so, to work around compiler limitations). -- | The certificates for bounds-checking are part of the Stm. -- | Unary operation. -- | Binary operation. -- | iota(n, x, s) = [x,x+s,..,x+(n-1)*s]. -- -- The IntType indicates the type of the array returned and the -- offset/stride arguments, but not the length argument. -- | Permute the dimensions of the input array. The list of integers is a -- list of dimensions (0-indexed), which must be a permutation of -- [0,n-1], where n is the number of dimensions in the -- input array. -- | 1st arg is the new shape, 2nd arg is the input array *) -- |
-- replicate([3][2],1) = [[1,1], [1,1], [1,1]] ---- | Copy the given array. The result will not alias anything. -- | A variable or constant. -- | Comparison - result type is always boolean. -- | Conversion "casting". -- | Array literals, e.g., [ [1+x, 3], [2, 1+4] ]. Second arg is -- the element type of the rows of the array. Scalar operations -- | Turn a boolean into a certificate, halting the program with the given -- error message if the boolean is false. -- | An in-place update of the given array at the given position. Consumes -- the array. -- | concat0([1],[2, 3, 4]) = [1, 2, 3, 4]@. -- | Manifest an array with dimensions represented in the given order. The -- result will not alias anything. -- | Repeat each dimension of the input array some number of times, given -- by the corresponding shape. For an array of rank k, the list -- must contain k shapes. A shape may be empty (in which case -- the dimension is not repeated, but it is still present). The last -- shape indicates the amount of extra innermost dimensions. All other -- extra dimensions are added *before* the original dimension. -- | Create array of given type and shape, with undefined elements. -- | Rotate the dimensions of the input array. The list of subexpressions -- specify how much each dimension is rotated. The length of this list -- must be equal to the rank of the array. -- | First variable is the flag array, second is the element arrays. If no -- arrays are given, the returned offsets are zero, and no arrays are -- returned. -- | A list of DimChanges, indicating the new dimensions of an -- array. type ShapeChange d = [DimChange d] -- | The new dimension in a Reshape-like operation. This allows us -- to disambiguate "real" reshapes, that change the actual shape of the -- array, from type coercions that are just present to make the types -- work out. data DimChange d -- | The new dimension is guaranteed to be numerically equal to the old -- one. DimCoercion :: d -> DimChange d -- | The new dimension is not necessarily numerically equal to the old one. DimNew :: d -> DimChange d -- | A body consists of a number of bindings, terminating in a result -- (essentially a tuple literal). data BodyT lore -- | The result of a body is a sequence of subexpressions. type Result = [SubExp] -- | A sequence of statements. type Stms lore = Seq (Stm lore) stmPattern :: Stm lore -> Pattern lore stmAux :: Stm lore -> StmAux (ExpAttr lore) stmExp :: Stm lore -> Exp lore -- | Auxilliary Information associated with a statement. data StmAux attr StmAux :: !Certificates -> attr -> StmAux attr [stmAuxCerts] :: StmAux attr -> !Certificates [stmAuxAttr] :: StmAux attr -> attr -- | A pattern is conceptually just a list of names and their types. data PatternT attr oneStm :: Stm lore -> Stms lore stmsFromList :: [Stm lore] -> Stms lore stmsToList :: Stms lore -> [Stm lore] stmsHead :: Stms lore -> Maybe (Stm lore, Stms lore) -- | Anonymous function for use in a SOAC. data LambdaT lore Lambda :: [LParam lore] -> BodyT lore -> [Type] -> LambdaT lore -- | A body consists of a number of bindings, terminating in a result -- (essentially a tuple literal). data BodyT lore Body :: BodyAttr lore -> Stms lore -> Result -> BodyT lore -- | A pattern is conceptually just a list of names and their types. data PatternT attr Pattern :: [PatElemT attr] -> [PatElemT attr] -> PatternT attr -- | An element of a pattern - consisting of an name (essentially a pair of -- the name andtype), a Bindage, and an addditional parametric -- attribute. This attribute is what is expected to contain the type of -- the resulting variable. data PatElemT attr PatElem :: VName -> attr -> PatElemT attr -- | An entire Futhark program. newtype ProgT lore Prog :: [FunDef lore] -> ProgT lore -- | The root Futhark expression type. The ExpT constructor contains -- a lore-specific operation. Do-loops, branches and function calls are -- special. Everything else is a simple BasicOp. data ExpT lore -- | A simple (non-recursive) operation. BasicOp :: BasicOp lore -> ExpT lore -- | Function Declarations data FunDefT lore FunDef :: Maybe EntryPoint -> Name -> [RetType lore] -> [FParam lore] -> BodyT lore -> FunDefT lore -- | A function parameter. data ParamT attr Param :: VName -> attr -> ParamT attr instance Futhark.Representation.AST.Annotations.Annotations Futhark.Representation.SOACS.SOACS instance Futhark.Representation.AST.Attributes.Attributes Futhark.Representation.SOACS.SOACS instance Futhark.TypeCheck.Checkable Futhark.Representation.SOACS.SOACS instance Futhark.Binder.Class.Bindable Futhark.Representation.SOACS.SOACS instance Futhark.Binder.BinderOps Futhark.Representation.SOACS.SOACS instance Futhark.Representation.AST.Pretty.PrettyLore Futhark.Representation.SOACS.SOACS -- | The code generator cannot handle the array combinators (map -- and friends), so this module was written to transform them into the -- equivalent do-loops. The transformation is currently rather naive, and -- - it's certainly worth considering when we can express such -- transformations in-place. module Futhark.Transform.FirstOrderTransform transformFunDef :: (MonadFreshNames m, Bindable tolore, BinderOps tolore, LetAttr SOACS ~ LetAttr tolore, CanBeAliased (Op tolore)) => FunDef -> m (FunDef tolore) -- | The constraints that a monad must uphold in order to be used for -- first-order transformation. type Transformer m = (MonadBinder m, Bindable (Lore m), BinderOps (Lore m), LocalScope (Lore m) m, LetAttr SOACS ~ LetAttr (Lore m), LParamAttr SOACS ~ LParamAttr (Lore m), CanBeAliased (Op (Lore m))) -- | First transform any nested Body or Lambda elements, then -- apply transformSOAC if the expression is a SOAC. transformStmRecursively :: Transformer m => Stm -> m () -- | Recursively first-order-transform a lambda. transformLambda :: (MonadFreshNames m, Bindable lore, BinderOps lore, LocalScope somelore m, SameScope somelore lore, LetAttr SOACS ~ LetAttr lore, CanBeAliased (Op lore)) => Lambda -> m (Lambda lore) -- | Transform a single SOAC into a do-loop. The body of the lambda -- is untouched, and may or may not contain further SOACs -- depending on the given lore. transformSOAC :: Transformer m => Pattern (Lore m) -> SOAC (Lore m) -> m () transformBody :: Transformer m => Body -> m (Body (Lore m)) -- | Turn a Haskell-style mapAccumL into a sequential do-loop. This is the -- guts of transforming a Redomap. doLoopMapAccumL :: (LocalScope (Lore m) m, MonadBinder m, Bindable (Lore m), BinderOps (Lore m), LetAttr (Lore m) ~ Type, CanBeAliased (Op (Lore m))) => SubExp -> Lambda (Aliases (Lore m)) -> [SubExp] -> [VName] -> [VName] -> m (Exp (Lore m)) doLoopMapAccumL' :: (LocalScope (Lore m) m, MonadBinder m, Bindable (Lore m), BinderOps (Lore m), LetAttr (Lore m) ~ Type, CanBeAliased (Op (Lore m))) => SubExp -> Lambda (Aliases (Lore m)) -> [SubExp] -> [VName] -> [VName] -> m ([(FParam (Lore m), SubExp)], VName, Body (Lore m)) module Futhark.Pass.ExtractKernels.ISRWIM -- | Interchange Scan With Inner Map. Tries to turn a scan(map) -- into a @map(scan) iswim :: (MonadBinder m, Lore m ~ SOACS) => Pattern -> SubExp -> Lambda -> [(SubExp, VName)] -> Maybe (m ()) -- | Interchange Reduce With Inner Map. Tries to turn a -- reduce(map) into a @map(reduce) irwim :: (MonadBinder m, Lore m ~ SOACS) => Pattern -> SubExp -> Commutativity -> Lambda -> [(SubExp, VName)] -> Maybe (m ()) rwimPossible :: Lambda -> Maybe (Pattern, Certificates, SubExp, Lambda) module Futhark.Optimise.Fusion.TryFusion data TryFusion a tryFusion :: MonadFreshNames m => TryFusion a -> Scope SOACS -> m (Maybe a) liftMaybe :: Maybe a -> TryFusion a instance Futhark.Representation.AST.Attributes.Scope.LocalScope Futhark.Representation.SOACS.SOACS Futhark.Optimise.Fusion.TryFusion.TryFusion instance Futhark.Representation.AST.Attributes.Scope.HasScope Futhark.Representation.SOACS.SOACS Futhark.Optimise.Fusion.TryFusion.TryFusion instance Futhark.MonadFreshNames.MonadFreshNames Futhark.Optimise.Fusion.TryFusion.TryFusion instance Control.Monad.Fail.MonadFail Futhark.Optimise.Fusion.TryFusion.TryFusion instance GHC.Base.Monad Futhark.Optimise.Fusion.TryFusion.TryFusion instance GHC.Base.Alternative Futhark.Optimise.Fusion.TryFusion.TryFusion instance GHC.Base.Applicative Futhark.Optimise.Fusion.TryFusion.TryFusion instance GHC.Base.Functor Futhark.Optimise.Fusion.TryFusion.TryFusion module Futhark.Internalise.Monad data InternaliseM a runInternaliseM :: MonadFreshNames m => Bool -> InternaliseM () -> m (Either String [FunDef]) -- | Is used within a monadic computation to begin exception processing. throwError :: MonadError e m => e -> m a -- | A mapping from external variable names to the corresponding -- internalised subexpressions. type VarSubstitutions = Map VName [SubExp] data InternaliseEnv InternaliseEnv :: VarSubstitutions -> Bool -> Bool -> InternaliseEnv [envSubsts] :: InternaliseEnv -> VarSubstitutions [envDoBoundsChecks] :: InternaliseEnv -> Bool [envSafe] :: InternaliseEnv -> Bool type ConstParams = [(Name, VName)] -- | Extra parameters to pass when calling this function. This corresponds -- to the closure of a locally defined function. type Closure = [VName] type FunInfo = (Name, ConstParams, Closure, [VName], [DeclType], [FParam], [(SubExp, Type)] -> Maybe [DeclExtType]) substitutingVars :: VarSubstitutions -> InternaliseM a -> InternaliseM a -- | Add a function definition to the program being constructed. addFunction :: FunDef -> InternaliseM () lookupFunction :: VName -> InternaliseM FunInfo lookupFunction' :: VName -> InternaliseM (Maybe FunInfo) bindFunction :: VName -> FunInfo -> InternaliseM () -- | Execute the given action if envDoBoundsChecks is true, -- otherwise just return an empty list. asserting :: InternaliseM Certificates -> InternaliseM Certificates -- | Execute the given action if envDoBoundsChecks is true, -- otherwise just return an empty list. assertingOne :: InternaliseM VName -> InternaliseM Certificates data InternaliseTypeM a liftInternaliseM :: InternaliseM a -> InternaliseTypeM a runInternaliseTypeM :: InternaliseTypeM a -> InternaliseM (a, ConstParams) lookupDim :: VName -> InternaliseTypeM (Maybe ExtSize) withDims :: DimTable -> InternaliseTypeM a -> InternaliseTypeM a type DimTable = Map VName ExtSize instance Control.Monad.Error.Class.MonadError GHC.Base.String Futhark.Internalise.Monad.InternaliseTypeM instance Control.Monad.State.Class.MonadState Futhark.Internalise.Monad.TypeState Futhark.Internalise.Monad.InternaliseTypeM instance Control.Monad.Reader.Class.MonadReader Futhark.Internalise.Monad.TypeEnv Futhark.Internalise.Monad.InternaliseTypeM instance GHC.Base.Monad Futhark.Internalise.Monad.InternaliseTypeM instance GHC.Base.Applicative Futhark.Internalise.Monad.InternaliseTypeM instance GHC.Base.Functor Futhark.Internalise.Monad.InternaliseTypeM instance Futhark.Representation.AST.Attributes.Scope.LocalScope Futhark.Representation.SOACS.SOACS Futhark.Internalise.Monad.InternaliseM instance Futhark.Representation.AST.Attributes.Scope.HasScope Futhark.Representation.SOACS.SOACS Futhark.Internalise.Monad.InternaliseM instance Control.Monad.Error.Class.MonadError GHC.Base.String Futhark.Internalise.Monad.InternaliseM instance Futhark.MonadFreshNames.MonadFreshNames Futhark.Internalise.Monad.InternaliseM instance Control.Monad.State.Class.MonadState Futhark.Internalise.Monad.InternaliseState Futhark.Internalise.Monad.InternaliseM instance Control.Monad.Reader.Class.MonadReader Futhark.Internalise.Monad.InternaliseEnv Futhark.Internalise.Monad.InternaliseM instance GHC.Base.Monad Futhark.Internalise.Monad.InternaliseM instance GHC.Base.Applicative Futhark.Internalise.Monad.InternaliseM instance GHC.Base.Functor Futhark.Internalise.Monad.InternaliseM instance GHC.Base.Monoid Futhark.Internalise.Monad.InternaliseResult instance GHC.Base.Semigroup Futhark.Internalise.Monad.InternaliseResult instance Control.Monad.Fail.MonadFail Futhark.Internalise.Monad.InternaliseM instance Futhark.Binder.Class.MonadBinder Futhark.Internalise.Monad.InternaliseM instance (GHC.Base.Monoid w, GHC.Base.Monad m) => Futhark.MonadFreshNames.MonadFreshNames (Control.Monad.Trans.RWS.Lazy.RWST r w Futhark.Internalise.Monad.InternaliseState m) -- | This module exports functionality for generating a call graph of an -- Futhark program. module Futhark.Analysis.CallGraph -- | The call graph is just a mapping from a function name, i.e., the -- caller, to a list of the names of functions called by the function. -- The order of this list is not significant. type CallGraph = Map Name (Set Name) -- | buildCallGraph prog build the program's Call Graph. The -- representation is a hashtable that maps function names to a list of -- callee names. buildCallGraph :: Prog -> CallGraph -- | This module implements a compiler pass for inlining functions, then -- removing those that have become dead. module Futhark.Optimise.InliningDeadFun -- | A composition of inlineAggressively and -- removeDeadFunctions, to avoid the cost of type-checking the -- intermediate stage. inlineAndRemoveDeadFunctions :: Pass SOACS SOACS -- | removeDeadFunctions prog removes the functions that are -- unreachable from the main function from the program. removeDeadFunctions :: Pass SOACS SOACS -- | A representation of nested-parallel in-kernel per-workgroup -- expressions. module Futhark.Representation.Kernels.KernelExp data KernelExp lore -- | SplitSpace o w i elems_per_thread. -- -- Computes how to divide array elements to threads in a kernel. Returns -- the number of elements in the chunk that the current thread should -- take. -- -- w is the length of the outer dimension in the array. -- i is the current thread index. Each thread takes at most -- elems_per_thread elements. -- -- If the order o is SplitContiguous, thread with index -- i should receive elements i*elems_per_tread, -- i*elems_per_thread + 1, ..., i*elems_per_thread + -- (elems_per_thread-1). -- -- If the order o is SplitStrided stride, the -- thread will receive elements i, i+stride, i+2*stride, ..., -- i+(elems_per_thread-1)*stride. SplitSpace :: SplitOrdering -> SubExp -> SubExp -> SubExp -> KernelExp lore -- | Combine cspace ts aspace body will combine values from -- threads to a single (multidimensional) array. If we define (is, -- ws) = unzip cspace, then ws is defined the same accross -- all threads. The cspace defines the shape of the resulting -- array, and the identifiers used to identify each individual element. -- Only threads for which all ((i,w) -> i < w) aspace is -- true will provide a value (of type ts), which is generated by -- body. -- -- The result of a combine is always stored in local memory (OpenCL -- terminology) -- -- The same thread may be assigned to multiple elements of -- Combine, if the size of the CombineSpace exceeds the -- group size. Combine :: CombineSpace -> [Type] -> [(VName, SubExp)] -> Body lore -> KernelExp lore -- | GroupReduce w lam input (with (nes, arrs) = unzip -- input), will perform a reduction of the arrays arrs -- using the associative reduction operator lam and the neutral -- elements nes. -- -- The arrays arrs must all have outer dimension w, -- which must not be larger than the group size. -- -- Currently a GroupReduce consumes the input arrays, as it uses them for -- scratch space to store temporary results -- -- All threads in a group must participate in a GroupReduce (due to -- barriers) -- -- The length of the arrays w can be smaller than the number of -- elements in a group (neutral element will be filled in), but -- w can never be larger than the group size. GroupReduce :: SubExp -> Lambda lore -> [(SubExp, VName)] -> KernelExp lore -- | Same restrictions as with GroupReduce. GroupScan :: SubExp -> Lambda lore -> [(SubExp, VName)] -> KernelExp lore GroupStream :: SubExp -> SubExp -> GroupStreamLambda lore -> [SubExp] -> [VName] -> KernelExp lore -- | GroupGenReduce length destarrays op bucket -- values arrays GroupGenReduce :: [SubExp] -> [VName] -> LambdaT lore -> [SubExp] -> [SubExp] -> VName -> KernelExp lore -- | HACK: Semantically identity, but inserts a barrier afterwards. This -- reflects a weakness in our kernel representation. Barrier :: [SubExp] -> KernelExp lore data GroupStreamLambda lore GroupStreamLambda :: VName -> VName -> [LParam lore] -> [LParam lore] -> Body lore -> GroupStreamLambda lore [groupStreamChunkSize] :: GroupStreamLambda lore -> VName [groupStreamChunkOffset] :: GroupStreamLambda lore -> VName [groupStreamAccParams] :: GroupStreamLambda lore -> [LParam lore] [groupStreamArrParams] :: GroupStreamLambda lore -> [LParam lore] [groupStreamLambdaBody] :: GroupStreamLambda lore -> Body lore -- | How an array is split into chunks. data SplitOrdering SplitContiguous :: SplitOrdering SplitStrided :: SubExp -> SplitOrdering -- | A combine can be fully or partially in-place. The initial arrays here -- work like the ones from the Scatter SOAC. data CombineSpace CombineSpace :: [(SubExp, Int, VName)] -> [(VName, SubExp)] -> CombineSpace [cspaceScatter] :: CombineSpace -> [(SubExp, Int, VName)] [cspaceDims] :: CombineSpace -> [(VName, SubExp)] combineSpace :: [(VName, SubExp)] -> CombineSpace scopeOfCombineSpace :: CombineSpace -> Scope lore typeCheckKernelExp :: Checkable lore => KernelExp (Aliases lore) -> TypeM lore () instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Show.Show (Futhark.Representation.Kernels.KernelExp.KernelExp lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Ord (Futhark.Representation.Kernels.KernelExp.KernelExp lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Eq (Futhark.Representation.Kernels.KernelExp.KernelExp lore) instance GHC.Show.Show Futhark.Representation.Kernels.KernelExp.CombineSpace instance GHC.Classes.Ord Futhark.Representation.Kernels.KernelExp.CombineSpace instance GHC.Classes.Eq Futhark.Representation.Kernels.KernelExp.CombineSpace instance GHC.Show.Show Futhark.Representation.Kernels.KernelExp.SplitOrdering instance GHC.Classes.Ord Futhark.Representation.Kernels.KernelExp.SplitOrdering instance GHC.Classes.Eq Futhark.Representation.Kernels.KernelExp.SplitOrdering instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Eq (Futhark.Representation.Kernels.KernelExp.GroupStreamLambda lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Show.Show (Futhark.Representation.Kernels.KernelExp.GroupStreamLambda lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Ord (Futhark.Representation.Kernels.KernelExp.GroupStreamLambda lore) instance Futhark.Representation.AST.Attributes.Attributes lore => Futhark.Representation.AST.Attributes.IsOp (Futhark.Representation.Kernels.KernelExp.KernelExp lore) instance Futhark.Representation.AST.Attributes.Attributes lore => Futhark.Representation.AST.Attributes.TypeOf.TypedOp (Futhark.Representation.Kernels.KernelExp.KernelExp lore) instance Futhark.Representation.AST.Attributes.Attributes lore => Futhark.Representation.AST.Attributes.Names.FreeIn (Futhark.Representation.Kernels.KernelExp.KernelExp lore) instance Futhark.Representation.AST.Attributes.Ranges.Ranged inner => Futhark.Representation.AST.Attributes.Ranges.RangedOp (Futhark.Representation.Kernels.KernelExp.KernelExp inner) instance (Futhark.Representation.AST.Attributes.Attributes lore, Futhark.Representation.AST.Attributes.Aliases.Aliased lore) => Futhark.Representation.AST.Attributes.Aliases.AliasedOp (Futhark.Representation.Kernels.KernelExp.KernelExp lore) instance Futhark.Representation.AST.Attributes.Attributes lore => Futhark.Transform.Substitute.Substitute (Futhark.Representation.Kernels.KernelExp.KernelExp lore) instance Futhark.Transform.Rename.Renameable lore => Futhark.Transform.Rename.Rename (Futhark.Representation.Kernels.KernelExp.KernelExp lore) instance (Futhark.Representation.AST.Attributes.Attributes lore, Futhark.Representation.AST.Attributes.Attributes (Futhark.Representation.Aliases.Aliases lore), Futhark.Representation.AST.Attributes.Aliases.CanBeAliased (Futhark.Representation.AST.Annotations.Op lore)) => Futhark.Representation.AST.Attributes.Aliases.CanBeAliased (Futhark.Representation.Kernels.KernelExp.KernelExp lore) instance (Futhark.Representation.AST.Attributes.Attributes lore, Futhark.Representation.AST.Attributes.Attributes (Futhark.Representation.Ranges.Ranges lore), Futhark.Representation.AST.Attributes.Ranges.CanBeRanged (Futhark.Representation.AST.Annotations.Op lore)) => Futhark.Representation.AST.Attributes.Ranges.CanBeRanged (Futhark.Representation.Kernels.KernelExp.KernelExp lore) instance (Futhark.Representation.AST.Attributes.Attributes lore, Futhark.Optimise.Simplify.Lore.CanBeWise (Futhark.Representation.AST.Annotations.Op lore)) => Futhark.Optimise.Simplify.Lore.CanBeWise (Futhark.Representation.Kernels.KernelExp.KernelExp lore) instance Futhark.Analysis.SymbolTable.IndexOp (Futhark.Representation.Kernels.KernelExp.KernelExp lore) instance Futhark.Representation.AST.Attributes.Aliases.Aliased lore => Futhark.Analysis.Usage.UsageInOp (Futhark.Representation.Kernels.KernelExp.KernelExp lore) instance Futhark.Analysis.Metrics.OpMetrics (Futhark.Representation.AST.Annotations.Op lore) => Futhark.Analysis.Metrics.OpMetrics (Futhark.Representation.Kernels.KernelExp.KernelExp lore) instance Futhark.Representation.AST.Pretty.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.Kernels.KernelExp.KernelExp lore) instance Futhark.Representation.AST.Attributes.Attributes lore => Futhark.Representation.AST.Attributes.Names.FreeIn (Futhark.Representation.Kernels.KernelExp.GroupStreamLambda lore) instance Futhark.Representation.AST.Attributes.Attributes lore => Futhark.Transform.Substitute.Substitute (Futhark.Representation.Kernels.KernelExp.GroupStreamLambda lore) instance Futhark.Transform.Rename.Renameable lore => Futhark.Transform.Rename.Rename (Futhark.Representation.Kernels.KernelExp.GroupStreamLambda lore) instance Futhark.Representation.AST.Attributes.Scope.Scoped lore (Futhark.Representation.Kernels.KernelExp.GroupStreamLambda lore) instance Futhark.Representation.AST.Pretty.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.Kernels.KernelExp.GroupStreamLambda lore) instance Futhark.Transform.Substitute.Substitute Futhark.Representation.Kernels.KernelExp.CombineSpace instance Futhark.Transform.Rename.Rename Futhark.Representation.Kernels.KernelExp.CombineSpace instance Futhark.Representation.AST.Attributes.Names.FreeIn Futhark.Representation.Kernels.KernelExp.SplitOrdering instance Futhark.Transform.Substitute.Substitute Futhark.Representation.Kernels.KernelExp.SplitOrdering instance Futhark.Transform.Rename.Rename Futhark.Representation.Kernels.KernelExp.SplitOrdering module Futhark.Representation.Kernels.Kernel data Kernel lore -- | Produce some runtime-configurable size. GetSize :: VName -> SizeClass -> Kernel lore -- | The maximum size of some class. GetSizeMax :: SizeClass -> Kernel lore -- | Compare size (likely a threshold) with some Int32 value. CmpSizeLe :: VName -> SizeClass -> SubExp -> Kernel lore Kernel :: KernelDebugHints -> KernelSpace -> [Type] -> KernelBody lore -> Kernel lore kernelType :: Kernel lore -> [Type] -- | Some information about what goes into a kernel, and where it came -- from. Has no semantic meaning; only used for debugging generated code. data KernelDebugHints KernelDebugHints :: String -> [(String, SubExp)] -> KernelDebugHints [kernelName] :: KernelDebugHints -> String -- | A mapping from a description to some PrimType value. [kernelHints] :: KernelDebugHints -> [(String, SubExp)] -- | The body of a Kernel. data KernelBody lore KernelBody :: BodyAttr lore -> Stms lore -> [KernelResult] -> KernelBody lore [kernelBodyLore] :: KernelBody lore -> BodyAttr lore [kernelBodyStms] :: KernelBody lore -> Stms lore [kernelBodyResult] :: KernelBody lore -> [KernelResult] -- | first three bound in the kernel, the rest are params to kernel data KernelSpace KernelSpace :: VName -> VName -> VName -> SubExp -> SubExp -> SubExp -> SpaceStructure -> KernelSpace [spaceGlobalId] :: KernelSpace -> VName [spaceLocalId] :: KernelSpace -> VName [spaceGroupId] :: KernelSpace -> VName [spaceNumThreads] :: KernelSpace -> SubExp [spaceNumGroups] :: KernelSpace -> SubExp [spaceGroupSize] :: KernelSpace -> SubExp [spaceStructure] :: KernelSpace -> SpaceStructure -- | Global thread IDs and their upper bound. spaceDimensions :: KernelSpace -> [(VName, SubExp)] -- | Indices computed for each thread (or group) inside the kernel. This is -- an arbitrary-dimensional space that is generated from the flat GPU -- thread space. data SpaceStructure FlatThreadSpace :: [(VName, SubExp)] -> SpaceStructure NestedThreadSpace :: [(VName, SubExp, VName, SubExp)] -> SpaceStructure scopeOfKernelSpace :: KernelSpace -> Scope lore data WhichThreads AllThreads :: WhichThreads OneResultPerGroup :: WhichThreads ThreadsPerGroup :: [(VName, SubExp)] -> WhichThreads ThreadsInSpace :: WhichThreads data KernelResult ThreadsReturn :: WhichThreads -> SubExp -> KernelResult WriteReturn :: [SubExp] -> VName -> [([SubExp], SubExp)] -> KernelResult ConcatReturns :: SplitOrdering -> SubExp -> SubExp -> Maybe SubExp -> VName -> KernelResult KernelInPlaceReturn :: VName -> KernelResult kernelResultSubExp :: KernelResult -> SubExp -- | An indication of which comparisons have been performed to get to this -- point, as well as the result of each comparison. type KernelPath = [(VName, Bool)] chunkedKernelNonconcatOutputs :: Lambda lore -> Int typeCheckKernel :: Checkable lore => Kernel (Aliases lore) -> TypeM lore () -- | Like Mapper, but just for Kernels. data KernelMapper flore tlore m KernelMapper :: (SubExp -> m SubExp) -> (Lambda flore -> m (Lambda tlore)) -> (Body flore -> m (Body tlore)) -> (VName -> m VName) -> (LParam flore -> m (LParam tlore)) -> (KernelBody flore -> m (KernelBody tlore)) -> KernelMapper flore tlore m [mapOnKernelSubExp] :: KernelMapper flore tlore m -> SubExp -> m SubExp [mapOnKernelLambda] :: KernelMapper flore tlore m -> Lambda flore -> m (Lambda tlore) [mapOnKernelBody] :: KernelMapper flore tlore m -> Body flore -> m (Body tlore) [mapOnKernelVName] :: KernelMapper flore tlore m -> VName -> m VName [mapOnKernelLParam] :: KernelMapper flore tlore m -> LParam flore -> m (LParam tlore) [mapOnKernelKernelBody] :: KernelMapper flore tlore m -> KernelBody flore -> m (KernelBody tlore) -- | A mapper that simply returns the Kernel verbatim. identityKernelMapper :: Monad m => KernelMapper lore lore m -- | Map a monadic action across the immediate children of a Kernel. The -- mapping does not descend recursively into subexpressions and is done -- left-to-right. mapKernelM :: (Applicative m, Monad m) => KernelMapper flore tlore m -> Kernel flore -> m (Kernel tlore) -- | Like Walker, but just for Kernels. data KernelWalker lore m KernelWalker :: (SubExp -> m ()) -> (Lambda lore -> m ()) -> (Body lore -> m ()) -> (VName -> m ()) -> (LParam lore -> m ()) -> (KernelBody lore -> m ()) -> KernelWalker lore m [walkOnKernelSubExp] :: KernelWalker lore m -> SubExp -> m () [walkOnKernelLambda] :: KernelWalker lore m -> Lambda lore -> m () [walkOnKernelBody] :: KernelWalker lore m -> Body lore -> m () [walkOnKernelVName] :: KernelWalker lore m -> VName -> m () [walkOnKernelLParam] :: KernelWalker lore m -> LParam lore -> m () [walkOnKernelKernelBody] :: KernelWalker lore m -> KernelBody lore -> m () -- | A no-op traversal. identityKernelWalker :: Monad m => KernelWalker lore m -- | As mapKernelM, but ignoring the results. walkKernelM :: Monad m => KernelWalker lore m -> Kernel lore -> m () instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Ord (Futhark.Representation.Kernels.Kernel.Kernel lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Show.Show (Futhark.Representation.Kernels.Kernel.Kernel lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Eq (Futhark.Representation.Kernels.Kernel.Kernel lore) instance GHC.Classes.Ord Futhark.Representation.Kernels.Kernel.KernelResult instance GHC.Show.Show Futhark.Representation.Kernels.Kernel.KernelResult instance GHC.Classes.Eq Futhark.Representation.Kernels.Kernel.KernelResult instance GHC.Classes.Ord Futhark.Representation.Kernels.Kernel.WhichThreads instance GHC.Show.Show Futhark.Representation.Kernels.Kernel.WhichThreads instance GHC.Classes.Eq Futhark.Representation.Kernels.Kernel.WhichThreads instance GHC.Classes.Ord Futhark.Representation.Kernels.Kernel.KernelSpace instance GHC.Show.Show Futhark.Representation.Kernels.Kernel.KernelSpace instance GHC.Classes.Eq Futhark.Representation.Kernels.Kernel.KernelSpace instance GHC.Classes.Ord Futhark.Representation.Kernels.Kernel.SpaceStructure instance GHC.Show.Show Futhark.Representation.Kernels.Kernel.SpaceStructure instance GHC.Classes.Eq Futhark.Representation.Kernels.Kernel.SpaceStructure instance GHC.Classes.Ord Futhark.Representation.Kernels.Kernel.KernelDebugHints instance GHC.Show.Show Futhark.Representation.Kernels.Kernel.KernelDebugHints instance GHC.Classes.Eq Futhark.Representation.Kernels.Kernel.KernelDebugHints instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Ord (Futhark.Representation.Kernels.Kernel.KernelBody lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Show.Show (Futhark.Representation.Kernels.Kernel.KernelBody lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Eq (Futhark.Representation.Kernels.Kernel.KernelBody lore) instance (Futhark.Representation.AST.Attributes.Attributes lore, Futhark.Representation.AST.Attributes.Names.FreeIn (Futhark.Representation.AST.Annotations.LParamAttr lore)) => Futhark.Representation.AST.Attributes.Names.FreeIn (Futhark.Representation.Kernels.Kernel.Kernel lore) instance Futhark.Representation.AST.Attributes.Attributes lore => Futhark.Transform.Substitute.Substitute (Futhark.Representation.Kernels.Kernel.Kernel lore) instance Futhark.Representation.AST.Attributes.Attributes lore => Futhark.Transform.Rename.Rename (Futhark.Representation.Kernels.Kernel.Kernel lore) instance (Futhark.Representation.AST.Attributes.Attributes lore, Futhark.Representation.AST.Attributes.Attributes (Futhark.Representation.Aliases.Aliases lore), Futhark.Representation.AST.Attributes.Aliases.CanBeAliased (Futhark.Representation.AST.Annotations.Op lore)) => Futhark.Representation.AST.Attributes.Aliases.CanBeAliased (Futhark.Representation.Kernels.Kernel.Kernel lore) instance (Futhark.Representation.AST.Attributes.Attributes lore, Futhark.Representation.AST.Attributes.Ranges.CanBeRanged (Futhark.Representation.AST.Annotations.Op lore)) => Futhark.Representation.AST.Attributes.Ranges.CanBeRanged (Futhark.Representation.Kernels.Kernel.Kernel lore) instance (Futhark.Representation.AST.Attributes.Attributes lore, Futhark.Optimise.Simplify.Lore.CanBeWise (Futhark.Representation.AST.Annotations.Op lore)) => Futhark.Optimise.Simplify.Lore.CanBeWise (Futhark.Representation.Kernels.Kernel.Kernel lore) instance Futhark.Representation.AST.Attributes.TypeOf.TypedOp (Futhark.Representation.Kernels.Kernel.Kernel lore) instance (Futhark.Representation.AST.Attributes.Attributes lore, Futhark.Representation.AST.Attributes.Aliases.Aliased lore) => Futhark.Representation.AST.Attributes.Aliases.AliasedOp (Futhark.Representation.Kernels.Kernel.Kernel lore) instance Futhark.Representation.AST.Attributes.Attributes lore => Futhark.Representation.AST.Attributes.IsOp (Futhark.Representation.Kernels.Kernel.Kernel lore) instance Futhark.Representation.AST.Attributes.Ranges.Ranged inner => Futhark.Representation.AST.Attributes.Ranges.RangedOp (Futhark.Representation.Kernels.Kernel.Kernel inner) instance Futhark.Representation.AST.Attributes.Attributes lore => Futhark.Analysis.SymbolTable.IndexOp (Futhark.Representation.Kernels.Kernel.Kernel lore) instance Futhark.Representation.AST.Attributes.Aliases.Aliased lore => Futhark.Analysis.Usage.UsageInOp (Futhark.Representation.Kernels.Kernel.Kernel lore) instance Futhark.Analysis.Metrics.OpMetrics (Futhark.Representation.AST.Annotations.Op lore) => Futhark.Analysis.Metrics.OpMetrics (Futhark.Representation.Kernels.Kernel.Kernel lore) instance Futhark.Representation.AST.Pretty.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.Kernels.Kernel.Kernel lore) instance Futhark.Representation.AST.Attributes.Attributes lore => Futhark.Representation.AST.Attributes.Names.FreeIn (Futhark.Representation.Kernels.Kernel.KernelBody lore) instance Futhark.Representation.AST.Attributes.Attributes lore => Futhark.Transform.Substitute.Substitute (Futhark.Representation.Kernels.Kernel.KernelBody lore) instance Futhark.Representation.AST.Attributes.Attributes lore => Futhark.Transform.Rename.Rename (Futhark.Representation.Kernels.Kernel.KernelBody lore) instance Futhark.Representation.AST.Pretty.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.Kernels.Kernel.KernelBody lore) instance Futhark.Representation.AST.Attributes.Names.FreeIn Futhark.Representation.Kernels.Kernel.KernelResult instance Futhark.Transform.Substitute.Substitute Futhark.Representation.Kernels.Kernel.KernelResult instance Futhark.Transform.Rename.Rename Futhark.Representation.Kernels.Kernel.KernelResult instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Representation.Kernels.Kernel.KernelResult instance Futhark.Representation.AST.Attributes.Names.FreeIn Futhark.Representation.Kernels.Kernel.WhichThreads instance Futhark.Transform.Substitute.Substitute Futhark.Representation.Kernels.Kernel.WhichThreads instance Futhark.Transform.Rename.Rename Futhark.Representation.Kernels.Kernel.WhichThreads instance Futhark.Transform.Substitute.Substitute Futhark.Representation.Kernels.Kernel.KernelSpace instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Representation.Kernels.Kernel.KernelSpace instance Futhark.Transform.Substitute.Substitute Futhark.Representation.Kernels.Kernel.SpaceStructure -- | A representation with flat parallelism via GPU-oriented kernels. module Futhark.Representation.Kernels data Kernels data InKernel instance Futhark.Representation.AST.Annotations.Annotations Futhark.Representation.Kernels.Kernels instance Futhark.Representation.AST.Annotations.Annotations Futhark.Representation.Kernels.InKernel instance Futhark.Representation.AST.Attributes.Attributes Futhark.Representation.Kernels.InKernel instance Futhark.Representation.AST.Pretty.PrettyLore Futhark.Representation.Kernels.InKernel instance Futhark.TypeCheck.Checkable Futhark.Representation.Kernels.InKernel instance Futhark.Binder.Class.Bindable Futhark.Representation.Kernels.InKernel instance Futhark.Binder.BinderOps Futhark.Representation.Kernels.InKernel instance Futhark.Representation.AST.Attributes.Attributes Futhark.Representation.Kernels.Kernels instance Futhark.TypeCheck.Checkable Futhark.Representation.Kernels.Kernels instance Futhark.Binder.Class.Bindable Futhark.Representation.Kernels.Kernels instance Futhark.Binder.BinderOps Futhark.Representation.Kernels.Kernels instance Futhark.Representation.AST.Pretty.PrettyLore Futhark.Representation.Kernels.Kernels -- | Do various kernel optimisations - mostly related to coalescing. module Futhark.Pass.KernelBabysitting babysitKernels :: Pass Kernels Kernels nonlinearInMemory :: VName -> ExpMap -> Maybe (Maybe [Int]) module Futhark.Pass.FirstOrderTransform firstOrderTransform :: Pass SOACS Kernels -- | Sequentialise to kernel statements. module Futhark.Pass.ExtractKernels.Kernelise transformStm :: Transformer m => Stm -> m () transformStms :: Transformer m => Stms SOACS -> m () transformBody :: Transformer m => Body -> m (Body InKernel) transformLambda :: (MonadFreshNames m, HasScope lore m, SameScope lore InKernel) => Lambda -> m (Lambda InKernel) mapIsh :: Transformer m => Pattern -> Certificates -> SubExp -> [LParam] -> Body InKernel -> [VName] -> m () groupStreamMapAccumL :: Transformer m => [PatElem InKernel] -> SubExp -> Lambda InKernel -> [SubExp] -> [VName] -> m () module Futhark.Pass.ExtractKernels.BlockedKernel blockedReduction :: (MonadFreshNames m, HasScope Kernels m) => Pattern Kernels -> SubExp -> Commutativity -> Lambda InKernel -> Lambda InKernel -> [(VName, SubExp)] -> [SubExp] -> [VName] -> m (Stms Kernels) blockedReductionStream :: (MonadFreshNames m, HasScope Kernels m) => Pattern Kernels -> SubExp -> Commutativity -> Lambda InKernel -> Lambda InKernel -> [(VName, SubExp)] -> [SubExp] -> [VName] -> m (Stms Kernels) blockedGenReduce :: (MonadFreshNames m, HasScope Kernels m) => SubExp -> [(VName, SubExp)] -> [KernelInput] -> [GenReduceOp InKernel] -> Lambda InKernel -> [VName] -> m ([VName], Stms Kernels) blockedMap :: (MonadFreshNames m, HasScope Kernels m) => Pattern Kernels -> SubExp -> StreamOrd -> Lambda InKernel -> [SubExp] -> [VName] -> m (Stm Kernels, Stms Kernels) -- | The VNames returned are the names of variables bound to the -- carry-out of the last thread. You can ignore them if you don't need -- them. blockedScan :: (MonadBinder m, Lore m ~ Kernels) => Pattern Kernels -> SubExp -> Scan InKernel -> Reduce InKernel -> Lambda InKernel -> SubExp -> [(VName, SubExp)] -> [KernelInput] -> [VName] -> m [VName] mapKernel :: (HasScope Kernels m, MonadFreshNames m) => SubExp -> SpaceStructure -> [KernelInput] -> [Type] -> KernelBody InKernel -> m (Stms Kernels, Kernel InKernel) mapKernelFromBody :: (HasScope Kernels m, MonadFreshNames m) => SubExp -> SpaceStructure -> [KernelInput] -> [Type] -> Body InKernel -> m (Stms Kernels, Kernel InKernel) data KernelInput KernelInput :: VName -> Type -> VName -> [SubExp] -> KernelInput [kernelInputName] :: KernelInput -> VName [kernelInputType] :: KernelInput -> Type [kernelInputArray] :: KernelInput -> VName [kernelInputIndices] :: KernelInput -> [SubExp] readKernelInput :: (HasScope scope m, Monad m) => KernelInput -> m (Stm InKernel) -- | Given a chunked fold lambda that takes its initial accumulator value -- as parameters, bind those parameters to the neutral element instead. kerneliseLambda :: MonadFreshNames m => [SubExp] -> Lambda InKernel -> m (Lambda InKernel) newKernelSpace :: MonadFreshNames m => (SubExp, SubExp, SubExp) -> SpaceStructure -> m KernelSpace -- | Requires a fold lambda that includes accumulator parameters. chunkLambda :: (MonadFreshNames m, HasScope Kernels m) => Pattern Kernels -> [SubExp] -> Lambda InKernel -> m (Lambda InKernel) splitArrays :: (MonadBinder m, Lore m ~ InKernel) => VName -> [VName] -> SplitOrdering -> SubExp -> SubExp -> SubExp -> [VName] -> m () getSize :: (MonadBinder m, Op (Lore m) ~ Kernel innerlore) => String -> SizeClass -> m SubExp cmpSizeLe :: (MonadBinder m, Op (Lore m) ~ Kernel innerlore) => String -> SizeClass -> SubExp -> m (SubExp, VName) instance GHC.Show.Show Futhark.Pass.ExtractKernels.BlockedKernel.KernelInput instance GHC.Show.Show Futhark.Pass.ExtractKernels.BlockedKernel.KernelSize instance GHC.Classes.Ord Futhark.Pass.ExtractKernels.BlockedKernel.KernelSize instance GHC.Classes.Eq Futhark.Pass.ExtractKernels.BlockedKernel.KernelSize -- | Multiversion segmented reduction. module Futhark.Pass.ExtractKernels.Segmented -- | regularSegmentedRedomap will generate code for a segmented -- redomap using two different strategies, and dynamically deciding which -- one to use based on the number of segments and segment size. We use -- the (static) group_size to decide which of the following two -- strategies to choose: -- --
-- loop (r = r0) = for i < n do -- let a = r[i] in -- let r[i] = a * i in -- r -- in -- ... -- let x = y with [k] <- r in -- ... ---- -- We want to turn this into the following: -- --
-- let x0 = y with [k] <- r0 -- loop (x = x0) = for i < n do -- let a = a[k,i] in -- let x[k,i] = a * i in -- x -- in -- let r = x[y] in -- ... ---- -- The intent is that we are also going to optimise the new data movement -- (in the x0-binding), possibly by changing how r0 is -- defined. For the above transformation to be valid, a number of -- conditions must be fulfilled: -- --
-- f(i,j) = i * m + j ---- -- When we want to know the location of element a[2,3], we -- simply call the index function as f(2,3) and obtain -- 2*m+3. We could also have chosen another index function, one -- that represents the array in column-major (or "transposed") format: -- --
-- f(i,j) = j * n + i ---- -- Index functions are not Futhark-level functions, but a special -- construct that the final code generator will eventually use to -- generate concrete access code. By modifying the index functions we can -- change how an array is represented in memory, which can permit memory -- access pattern optimisations. -- -- Every time we bind an array, whether in a let-binding, -- loop merge parameter, or lambda parameter, we have -- an annotation specifying a memory block and an index function. In some -- cases, such as let-bindings for many expressions, we are free -- to specify an arbitrary index function and memory block - for example, -- we get to decide where Copy stores its result - but in other -- cases the type rules of the expression chooses for us. For example, -- Index always produces an array in the same memory block as its -- input, and with the same index function, except with some indices -- fixed. module Futhark.Representation.ExplicitMemory -- | A lore containing explicit memory information. data ExplicitMemory data InKernel data MemOp inner -- | Allocate a memory block. This really should not be an expression, but -- what are you gonna do... Alloc :: SubExp -> Space -> MemOp inner Inner :: inner -> MemOp inner -- | A summary of the memory information for every let-bound identifier, -- function parameter, and return value. Parameterisered over uniqueness, -- dimension, and auxiliary array information. data MemInfo d u ret -- | A primitive value. MemPrim :: PrimType -> MemInfo d u ret -- | A memory block. MemMem :: d -> Space -> MemInfo d u ret -- | The array is stored in the named memory block, and with the given -- index function. The index function maps indices in the array to -- element offset, not byte offsets! To translate to byte -- offsets, multiply the offset with the size of the array element type. MemArray :: PrimType -> ShapeBase d -> u -> ret -> MemInfo d u ret type MemBound u = MemInfo SubExp u MemBind -- | Memory information for an array bound somewhere in the program. data MemBind -- | Located in this memory block with this index function. ArrayIn :: VName -> IxFun -> MemBind -- | A description of the memory properties of an array being returned by -- an operation. data MemReturn -- | The array is located in a memory block that is already in scope. ReturnsInBlock :: VName -> ExtIxFun -> MemReturn -- | The operation returns a new (existential) block, with an existential -- or known size. ReturnsNewBlock :: Space -> Int -> ExtSize -> ExtIxFun -> MemReturn -- | The index function representation used for memory annotations. type IxFun = IxFun (PrimExp VName) -- | An index function that may contain existential variables. type ExtIxFun = IxFun (PrimExp (Ext VName)) isStaticIxFun :: ExtIxFun -> Maybe IxFun -- | The memory return of an expression. An array is annotated with -- Maybe MemReturn, which can be interpreted as the expression -- either dictating exactly where the array is located when it is -- returned (if Just), or able to put it whereever the binding -- prefers (if Nothing). -- -- This is necessary to capture the difference between an expression that -- is just an array-typed variable, in which the array being "returned" -- is located where it already is, and a copy expression, whose -- entire purpose is to store an existing array in some arbitrary -- location. This is a consequence of the design decision never to have -- implicit memory copies. type ExpReturns = MemInfo ExtSize NoUniqueness (Maybe MemReturn) -- | The return of a body, which must always indicate where returned arrays -- are located. type BodyReturns = MemInfo ExtSize NoUniqueness MemReturn -- | The memory return of a function, which must always indicate where -- returned arrays are located. type FunReturns = MemInfo ExtSize Uniqueness MemReturn noUniquenessReturns :: MemInfo d u r -> MemInfo d NoUniqueness r bodyReturnsToExpReturns :: BodyReturns -> ExpReturns type ExplicitMemorish lore = (SameScope lore ExplicitMemory, RetType lore ~ FunReturns, BranchType lore ~ BodyReturns, CanBeAliased (Op lore), Attributes lore, Annotations lore, Checkable lore, OpReturns lore) -- | The return information of an expression. This can be seen as the -- "return type with memory annotations" of the expression. expReturns :: (Monad m, HasScope lore m, ExplicitMemorish lore) => Exp lore -> m [ExpReturns] extReturns :: [ExtType] -> [ExpReturns] sliceInfo :: (Monad m, HasScope lore m, ExplicitMemorish lore) => VName -> Slice SubExp -> m (MemInfo SubExp NoUniqueness MemBind) lookupMemInfo :: (HasScope lore m, ExplicitMemorish lore) => VName -> m (MemInfo SubExp NoUniqueness MemBind) subExpMemInfo :: (HasScope lore m, Monad m, ExplicitMemorish lore) => SubExp -> m (MemInfo SubExp NoUniqueness MemBind) lookupMemSize :: (HasScope lore m, Monad m) => VName -> m SubExp lookupArraySummary :: (ExplicitMemorish lore, HasScope lore m, Monad m) => VName -> m (VName, IxFun (PrimExp VName)) -- | Is an array of the given shape stored fully flat row-major with the -- given index function? fullyLinear :: (Eq num, IntegralExp num) => ShapeBase num -> IxFun num -> Bool ixFunMatchesInnerShape :: (Eq num, IntegralExp num) => ShapeBase num -> IxFun num -> Bool existentialiseIxFun :: [VName] -> IxFun -> ExtIxFun instance GHC.Show.Show Futhark.Representation.ExplicitMemory.MemReturn instance GHC.Show.Show Futhark.Representation.ExplicitMemory.MemBind instance (GHC.Classes.Ord d, GHC.Classes.Ord u, GHC.Classes.Ord ret) => GHC.Classes.Ord (Futhark.Representation.ExplicitMemory.MemInfo d u ret) instance (GHC.Show.Show d, GHC.Show.Show u, GHC.Show.Show ret) => GHC.Show.Show (Futhark.Representation.ExplicitMemory.MemInfo d u ret) instance (GHC.Classes.Eq d, GHC.Classes.Eq u, GHC.Classes.Eq ret) => GHC.Classes.Eq (Futhark.Representation.ExplicitMemory.MemInfo d u ret) instance GHC.Show.Show inner => GHC.Show.Show (Futhark.Representation.ExplicitMemory.MemOp inner) instance GHC.Classes.Ord inner => GHC.Classes.Ord (Futhark.Representation.ExplicitMemory.MemOp inner) instance GHC.Classes.Eq inner => GHC.Classes.Eq (Futhark.Representation.ExplicitMemory.MemOp inner) instance Futhark.Representation.ExplicitMemory.OpReturns Futhark.Representation.ExplicitMemory.ExplicitMemory instance Futhark.Representation.ExplicitMemory.OpReturns Futhark.Representation.ExplicitMemory.InKernel instance Futhark.Representation.AST.RetType.IsRetType Futhark.Representation.ExplicitMemory.FunReturns instance Futhark.Representation.AST.Annotations.Annotations Futhark.Representation.ExplicitMemory.ExplicitMemory instance Futhark.Representation.AST.Annotations.Annotations Futhark.Representation.ExplicitMemory.InKernel instance Futhark.Optimise.Simplify.Engine.Simplifiable [Futhark.Representation.ExplicitMemory.FunReturns] instance Futhark.Representation.AST.RetType.IsBodyType Futhark.Representation.ExplicitMemory.BodyReturns instance GHC.Classes.Eq Futhark.Representation.ExplicitMemory.MemReturn instance GHC.Classes.Ord Futhark.Representation.ExplicitMemory.MemReturn instance Futhark.Transform.Rename.Rename Futhark.Representation.ExplicitMemory.MemReturn instance Futhark.Transform.Substitute.Substitute Futhark.Representation.ExplicitMemory.MemReturn instance Futhark.Representation.AST.Attributes.Types.FixExt Futhark.Representation.ExplicitMemory.MemReturn instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Representation.ExplicitMemory.MemReturn instance Futhark.Representation.AST.Attributes.Names.FreeIn Futhark.Representation.ExplicitMemory.MemReturn instance Futhark.Optimise.Simplify.Engine.Simplifiable Futhark.Representation.ExplicitMemory.MemReturn instance GHC.Classes.Eq Futhark.Representation.ExplicitMemory.MemBind instance GHC.Classes.Ord Futhark.Representation.ExplicitMemory.MemBind instance Futhark.Transform.Rename.Rename Futhark.Representation.ExplicitMemory.MemBind instance Futhark.Transform.Substitute.Substitute Futhark.Representation.ExplicitMemory.MemBind instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Representation.ExplicitMemory.MemBind instance Futhark.Representation.AST.Attributes.Names.FreeIn Futhark.Representation.ExplicitMemory.MemBind instance Futhark.Optimise.Simplify.Engine.Simplifiable Futhark.Representation.ExplicitMemory.MemBind instance Futhark.Representation.AST.Attributes.Types.FixExt ret => Futhark.Representation.AST.Attributes.Types.DeclExtTyped (Futhark.Representation.ExplicitMemory.MemInfo Futhark.Representation.AST.Syntax.Core.ExtSize Language.Futhark.Core.Uniqueness ret) instance Futhark.Representation.AST.Attributes.Types.FixExt ret => Futhark.Representation.AST.Attributes.Types.ExtTyped (Futhark.Representation.ExplicitMemory.MemInfo Futhark.Representation.AST.Syntax.Core.ExtSize Futhark.Representation.AST.Syntax.Core.NoUniqueness ret) instance Futhark.Representation.AST.Attributes.Types.FixExt ret => Futhark.Representation.AST.Attributes.Types.FixExt (Futhark.Representation.ExplicitMemory.MemInfo Futhark.Representation.AST.Syntax.Core.ExtSize u ret) instance Futhark.Representation.AST.Attributes.Types.Typed (Futhark.Representation.ExplicitMemory.MemInfo Futhark.Representation.AST.Syntax.Core.SubExp Language.Futhark.Core.Uniqueness ret) instance Futhark.Representation.AST.Attributes.Types.Typed (Futhark.Representation.ExplicitMemory.MemInfo Futhark.Representation.AST.Syntax.Core.SubExp Futhark.Representation.AST.Syntax.Core.NoUniqueness ret) instance Futhark.Representation.AST.Attributes.Types.DeclTyped (Futhark.Representation.ExplicitMemory.MemInfo Futhark.Representation.AST.Syntax.Core.SubExp Language.Futhark.Core.Uniqueness ret) instance (Futhark.Representation.AST.Attributes.Names.FreeIn d, Futhark.Representation.AST.Attributes.Names.FreeIn ret) => Futhark.Representation.AST.Attributes.Names.FreeIn (Futhark.Representation.ExplicitMemory.MemInfo d u ret) instance (Futhark.Transform.Substitute.Substitute d, Futhark.Transform.Substitute.Substitute ret) => Futhark.Transform.Substitute.Substitute (Futhark.Representation.ExplicitMemory.MemInfo d u ret) instance (Futhark.Transform.Substitute.Substitute d, Futhark.Transform.Substitute.Substitute ret) => Futhark.Transform.Rename.Rename (Futhark.Representation.ExplicitMemory.MemInfo d u ret) instance (Futhark.Optimise.Simplify.Engine.Simplifiable d, Futhark.Optimise.Simplify.Engine.Simplifiable ret) => Futhark.Optimise.Simplify.Engine.Simplifiable (Futhark.Representation.ExplicitMemory.MemInfo d u ret) instance (Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.Core.TypeBase (Futhark.Representation.AST.Syntax.Core.ShapeBase d) u), Text.PrettyPrint.Mainland.Class.Pretty d, Text.PrettyPrint.Mainland.Class.Pretty u, Text.PrettyPrint.Mainland.Class.Pretty ret) => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.ExplicitMemory.MemInfo d u ret) instance Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.Core.Param (Futhark.Representation.ExplicitMemory.MemInfo Futhark.Representation.AST.Syntax.Core.SubExp Language.Futhark.Core.Uniqueness ret)) instance Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.Core.Param (Futhark.Representation.ExplicitMemory.MemInfo Futhark.Representation.AST.Syntax.Core.SubExp Futhark.Representation.AST.Syntax.Core.NoUniqueness ret)) instance Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.AST.Syntax.Core.PatElemT (Futhark.Representation.ExplicitMemory.MemInfo Futhark.Representation.AST.Syntax.Core.SubExp Futhark.Representation.AST.Syntax.Core.NoUniqueness ret)) instance Futhark.TypeCheck.Checkable Futhark.Representation.ExplicitMemory.ExplicitMemory instance Futhark.TypeCheck.Checkable Futhark.Representation.ExplicitMemory.InKernel instance (Text.PrettyPrint.Mainland.Class.Pretty u, Text.PrettyPrint.Mainland.Class.Pretty r) => Futhark.Representation.AST.Pretty.PrettyAnnot (Futhark.Representation.AST.Syntax.Core.PatElemT (Futhark.Representation.ExplicitMemory.MemInfo Futhark.Representation.AST.Syntax.Core.SubExp u r)) instance (Text.PrettyPrint.Mainland.Class.Pretty u, Text.PrettyPrint.Mainland.Class.Pretty r) => Futhark.Representation.AST.Pretty.PrettyAnnot (Futhark.Representation.AST.Syntax.Core.ParamT (Futhark.Representation.ExplicitMemory.MemInfo Futhark.Representation.AST.Syntax.Core.SubExp u r)) instance Futhark.Representation.AST.Attributes.Names.FreeIn inner => Futhark.Representation.AST.Attributes.Names.FreeIn (Futhark.Representation.ExplicitMemory.MemOp inner) instance Futhark.Representation.AST.Attributes.TypeOf.TypedOp inner => Futhark.Representation.AST.Attributes.TypeOf.TypedOp (Futhark.Representation.ExplicitMemory.MemOp inner) instance Futhark.Representation.AST.Attributes.Aliases.AliasedOp inner => Futhark.Representation.AST.Attributes.Aliases.AliasedOp (Futhark.Representation.ExplicitMemory.MemOp inner) instance Futhark.Representation.AST.Attributes.Aliases.CanBeAliased inner => Futhark.Representation.AST.Attributes.Aliases.CanBeAliased (Futhark.Representation.ExplicitMemory.MemOp inner) instance Futhark.Representation.AST.Attributes.Ranges.RangedOp inner => Futhark.Representation.AST.Attributes.Ranges.RangedOp (Futhark.Representation.ExplicitMemory.MemOp inner) instance Futhark.Representation.AST.Attributes.Ranges.CanBeRanged inner => Futhark.Representation.AST.Attributes.Ranges.CanBeRanged (Futhark.Representation.ExplicitMemory.MemOp inner) instance Futhark.Transform.Rename.Rename inner => Futhark.Transform.Rename.Rename (Futhark.Representation.ExplicitMemory.MemOp inner) instance Futhark.Transform.Substitute.Substitute inner => Futhark.Transform.Substitute.Substitute (Futhark.Representation.ExplicitMemory.MemOp inner) instance Text.PrettyPrint.Mainland.Class.Pretty inner => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Representation.ExplicitMemory.MemOp inner) instance Futhark.Analysis.Metrics.OpMetrics inner => Futhark.Analysis.Metrics.OpMetrics (Futhark.Representation.ExplicitMemory.MemOp inner) instance Futhark.Representation.AST.Attributes.IsOp inner => Futhark.Representation.AST.Attributes.IsOp (Futhark.Representation.ExplicitMemory.MemOp inner) instance Futhark.Analysis.Usage.UsageInOp inner => Futhark.Analysis.Usage.UsageInOp (Futhark.Representation.ExplicitMemory.MemOp inner) instance Futhark.Optimise.Simplify.Lore.CanBeWise inner => Futhark.Optimise.Simplify.Lore.CanBeWise (Futhark.Representation.ExplicitMemory.MemOp inner) instance Futhark.Analysis.SymbolTable.IndexOp inner => Futhark.Analysis.SymbolTable.IndexOp (Futhark.Representation.ExplicitMemory.MemOp inner) instance Futhark.Representation.AST.Attributes.Attributes Futhark.Representation.ExplicitMemory.InKernel instance Futhark.Representation.AST.Pretty.PrettyLore Futhark.Representation.ExplicitMemory.InKernel instance Futhark.Representation.AST.Attributes.Attributes Futhark.Representation.ExplicitMemory.ExplicitMemory instance Futhark.Representation.AST.Pretty.PrettyLore Futhark.Representation.ExplicitMemory.ExplicitMemory module Futhark.Pass.ExplicitAllocations explicitAllocations :: Pass Kernels ExplicitMemory explicitAllocationsInStms :: (MonadFreshNames m, HasScope ExplicitMemory m) => Stms Kernels -> m (Stms ExplicitMemory) simplifiable :: (SimplifiableLore lore, ExpAttr lore ~ (), BodyAttr lore ~ (), Op lore ~ MemOp inner, Allocator lore (PatAllocM lore)) => (inner -> SimpleM lore (OpWithWisdom inner, Stms (Wise lore))) -> SimpleOps lore arraySizeInBytesExp :: Type -> PrimExp VName instance Futhark.MonadFreshNames.MonadFreshNames (Futhark.Pass.ExplicitAllocations.PatAllocM lore) instance Control.Monad.Writer.Class.MonadWriter [Futhark.Pass.ExplicitAllocations.AllocStm] (Futhark.Pass.ExplicitAllocations.PatAllocM lore) instance Futhark.Representation.AST.Annotations.Annotations lore => Futhark.Representation.AST.Attributes.Scope.HasScope lore (Futhark.Pass.ExplicitAllocations.PatAllocM lore) instance GHC.Base.Monad (Futhark.Pass.ExplicitAllocations.PatAllocM lore) instance GHC.Base.Functor (Futhark.Pass.ExplicitAllocations.PatAllocM lore) instance GHC.Base.Applicative (Futhark.Pass.ExplicitAllocations.PatAllocM lore) instance Control.Monad.Reader.Class.MonadReader (Futhark.Pass.ExplicitAllocations.AllocEnv fromlore tolore) (Futhark.Pass.ExplicitAllocations.AllocM fromlore tolore) instance Futhark.Representation.AST.Attributes.Attributes tolore => Futhark.Representation.AST.Attributes.Scope.LocalScope tolore (Futhark.Pass.ExplicitAllocations.AllocM fromlore tolore) instance Futhark.Representation.AST.Attributes.Attributes tolore => Futhark.Representation.AST.Attributes.Scope.HasScope tolore (Futhark.Pass.ExplicitAllocations.AllocM fromlore tolore) instance Futhark.MonadFreshNames.MonadFreshNames (Futhark.Pass.ExplicitAllocations.AllocM fromlore tolore) instance GHC.Base.Monad (Futhark.Pass.ExplicitAllocations.AllocM fromlore tolore) instance GHC.Base.Functor (Futhark.Pass.ExplicitAllocations.AllocM fromlore tolore) instance GHC.Base.Applicative (Futhark.Pass.ExplicitAllocations.AllocM fromlore tolore) instance GHC.Show.Show Futhark.Pass.ExplicitAllocations.AllocStm instance GHC.Classes.Ord Futhark.Pass.ExplicitAllocations.AllocStm instance GHC.Classes.Eq Futhark.Pass.ExplicitAllocations.AllocStm instance (Futhark.Pass.ExplicitAllocations.Allocable fromlore tolore, Futhark.Pass.ExplicitAllocations.Allocator tolore (Futhark.Pass.ExplicitAllocations.AllocM fromlore tolore)) => Futhark.Binder.Class.MonadBinder (Futhark.Pass.ExplicitAllocations.AllocM fromlore tolore) instance Futhark.Pass.ExplicitAllocations.Allocable fromlore Futhark.Pass.ExplicitAllocations.OutInKernel => Futhark.Pass.ExplicitAllocations.Allocator Futhark.Representation.ExplicitMemory.ExplicitMemory (Futhark.Pass.ExplicitAllocations.AllocM fromlore Futhark.Representation.ExplicitMemory.ExplicitMemory) instance Futhark.Pass.ExplicitAllocations.Allocable fromlore Futhark.Pass.ExplicitAllocations.OutInKernel => Futhark.Pass.ExplicitAllocations.Allocator Futhark.Pass.ExplicitAllocations.OutInKernel (Futhark.Pass.ExplicitAllocations.AllocM fromlore Futhark.Pass.ExplicitAllocations.OutInKernel) instance Futhark.Pass.ExplicitAllocations.Allocator Futhark.Representation.ExplicitMemory.ExplicitMemory (Futhark.Pass.ExplicitAllocations.PatAllocM Futhark.Representation.ExplicitMemory.ExplicitMemory) instance Futhark.Pass.ExplicitAllocations.Allocator Futhark.Pass.ExplicitAllocations.OutInKernel (Futhark.Pass.ExplicitAllocations.PatAllocM Futhark.Pass.ExplicitAllocations.OutInKernel) instance Futhark.Pass.ExplicitAllocations.SizeSubst (Futhark.Representation.Kernels.Kernel.Kernel lore) instance Futhark.Pass.ExplicitAllocations.SizeSubst op => Futhark.Pass.ExplicitAllocations.SizeSubst (Futhark.Representation.ExplicitMemory.MemOp op) instance Futhark.Pass.ExplicitAllocations.SizeSubst (Futhark.Representation.Kernels.KernelExp.KernelExp lore) instance Control.Monad.Fail.MonadFail (Futhark.Pass.ExplicitAllocations.AllocM fromlore tolore) instance Futhark.Binder.BinderOps Futhark.Pass.ExplicitAllocations.OutInKernel instance Futhark.Binder.BinderOps (Futhark.Optimise.Simplify.Lore.Wise Futhark.Pass.ExplicitAllocations.OutInKernel) instance Futhark.Binder.BinderOps Futhark.Representation.ExplicitMemory.ExplicitMemory instance Futhark.Binder.BinderOps (Futhark.Optimise.Simplify.Lore.Wise Futhark.Representation.ExplicitMemory.ExplicitMemory) module Futhark.Optimise.MemoryBlockMerging.Types -- | Memory block VName. type MName = VName -- | Memory block names. type MNames = Names data MemorySrc MemorySrc :: MName -> IxFun -> Shape -> MemorySrc -- | the memory block name [memSrcName] :: MemorySrc -> MName -- | the index function into the memory [memSrcIxFun] :: MemorySrc -> IxFun -- | the shape of the original array [memSrcShape] :: MemorySrc -> Shape data MemoryLoc MemoryLoc :: MName -> IxFun -> MemoryLoc -- | the memory block name [memLocName] :: MemoryLoc -> MName -- | the index function into the memory [memLocIxFun] :: MemoryLoc -> IxFun type VarMemMappings t = Map VName t type MemAliases = Map MName MNames type VarAliases = Map VName Names type FirstUses = Map VName MNames data StmOrRes FromStm :: VName -> StmOrRes FromRes :: VName -> StmOrRes type LastUses = Map StmOrRes MNames type Interferences = Map MName MNames type ActualVariables = Map VName Names type PotentialKernelDataRaceInterferences = [PotentialKernelDataRaceInterferenceGroup] type PotentialKernelDataRaceInterferenceGroup = [KernelFirstUse] type KernelFirstUse = (MName, VName, PrimType, IxFun) instance GHC.Classes.Ord Futhark.Optimise.MemoryBlockMerging.Types.Log instance GHC.Classes.Eq Futhark.Optimise.MemoryBlockMerging.Types.Log instance GHC.Show.Show Futhark.Optimise.MemoryBlockMerging.Types.Log instance GHC.Classes.Ord Futhark.Optimise.MemoryBlockMerging.Types.StmOrRes instance GHC.Classes.Eq Futhark.Optimise.MemoryBlockMerging.Types.StmOrRes instance GHC.Show.Show Futhark.Optimise.MemoryBlockMerging.Types.StmOrRes instance GHC.Classes.Eq Futhark.Optimise.MemoryBlockMerging.Types.MemoryLoc instance GHC.Show.Show Futhark.Optimise.MemoryBlockMerging.Types.MemoryLoc instance GHC.Classes.Eq Futhark.Optimise.MemoryBlockMerging.Types.MemorySrc instance GHC.Show.Show Futhark.Optimise.MemoryBlockMerging.Types.MemorySrc instance GHC.Base.Semigroup Futhark.Optimise.MemoryBlockMerging.Types.Log instance GHC.Base.Monoid Futhark.Optimise.MemoryBlockMerging.Types.Log -- | Miscellaneous helper functions. Perpetually in need of a cleanup. module Futhark.Optimise.MemoryBlockMerging.Miscellaneous makeCommutativeMap :: Ord v => Map v (Set v) -> Map v (Set v) insertOrUpdate :: (Ord k, Ord v) => k -> v -> Map k (Set v) -> Map k (Set v) insertOrUpdateMany :: (Ord k, Ord v) => k -> Set v -> Map k (Set v) -> Map k (Set v) insertOrNew :: Ord a => Set a -> Maybe (Set a) -> Maybe (Set a) removeEmptyMaps :: Map k (Set v) -> Map k (Set v) removeKeyFromMapElems :: Ord k => Map k (Set k) -> Map k (Set k) newDeclarationsStm :: Stm lore -> [VName] lookupEmptyable :: (Ord a, Monoid b) => a -> Map a b -> b fromJust :: String -> Maybe a -> a maybeFromBoolM :: Monad m => (a -> m Bool) -> a -> m (Maybe a) sortByKeyM :: (Ord t, Monad m) => (a -> m t) -> [a] -> m [a] mapMaybeM :: Monad m => (a -> m (Maybe b)) -> [a] -> m [b] anyM :: Monad m => (a -> m Bool) -> [a] -> m Bool whenM :: Monad m => m Bool -> m () -> m () expandPrimExp :: Map VName (PrimExp VName) -> PrimExp VName -> PrimExp VName expandIxFun :: Map VName (PrimExp VName) -> IxFun -> IxFun mapFromListSetUnion :: (Ord k, Ord v) => [(k, Set v)] -> Map k (Set v) fixpointIterateMay :: (a -> Maybe a) -> a -> a filterSetM :: (Ord a, Monad m) => (a -> m Bool) -> Set a -> m (Set a) (<&&>) :: Monad m => m Bool -> m Bool -> m Bool (<||>) :: Monad m => m Bool -> m Bool -> m Bool expandWithAliases :: forall v. Ord v => MemAliases -> Map v Names -> Map v Names class FullWalk lore fullWalkExpM :: (FullWalk lore, Monad m) => Walker lore m -> KernelWalker InKernel m -> Exp lore -> m () fullWalkAliasesExpM :: (FullWalkAliases lore, Monad m) => Walker (Aliases lore) m -> KernelWalker (Aliases InKernel) m -> Exp (Aliases lore) -> m () class FullWalkAliases lore class FullMap lore fullMapExpM :: (FullMap lore, Monad m) => Mapper lore lore m -> KernelMapper InKernel InKernel m -> Exp lore -> m (Exp lore) instance Futhark.Optimise.MemoryBlockMerging.Miscellaneous.FullWalkAliases Futhark.Representation.ExplicitMemory.ExplicitMemory instance Futhark.Optimise.MemoryBlockMerging.Miscellaneous.FullWalkAliases Futhark.Representation.ExplicitMemory.InKernel instance Futhark.Optimise.MemoryBlockMerging.Miscellaneous.FullWalk Futhark.Representation.ExplicitMemory.ExplicitMemory instance Futhark.Optimise.MemoryBlockMerging.Miscellaneous.FullWalk Futhark.Representation.ExplicitMemory.InKernel instance Futhark.Optimise.MemoryBlockMerging.Miscellaneous.FullMap Futhark.Representation.ExplicitMemory.ExplicitMemory instance Futhark.Optimise.MemoryBlockMerging.Miscellaneous.FullMap Futhark.Representation.ExplicitMemory.InKernel -- | Find all variable-to-memory mappings, so that other modules can lookup -- the relation. Maps array names to memory blocks. module Futhark.Optimise.MemoryBlockMerging.VariableMemory -- | Find all variable-memory block mappings in a function definition. findVarMemMappings :: FunDef ExplicitMemory -> VarMemMappings MemorySrc instance Control.Monad.Writer.Class.MonadWriter (Futhark.Optimise.MemoryBlockMerging.Types.VarMemMappings Futhark.Optimise.MemoryBlockMerging.Types.MemorySrc) (Futhark.Optimise.MemoryBlockMerging.VariableMemory.FindM lore) instance GHC.Base.Applicative (Futhark.Optimise.MemoryBlockMerging.VariableMemory.FindM lore) instance GHC.Base.Functor (Futhark.Optimise.MemoryBlockMerging.VariableMemory.FindM lore) instance GHC.Base.Monad (Futhark.Optimise.MemoryBlockMerging.VariableMemory.FindM lore) -- | Find all variable aliases. Avoids having to use the Aliases -- representation in other modules. -- -- FIXME: This module is silly. It should be able to go away, with the -- other modules getting variable aliases by using the Aliases -- representation directly. module Futhark.Optimise.MemoryBlockMerging.VariableAliases -- | Find all variable aliases in a function definition. findVarAliases :: FunDef ExplicitMemory -> VarAliases instance Control.Monad.Writer.Class.MonadWriter [Futhark.Optimise.MemoryBlockMerging.Types.VarAliases] (Futhark.Optimise.MemoryBlockMerging.VariableAliases.FindM lore) instance GHC.Base.Applicative (Futhark.Optimise.MemoryBlockMerging.VariableAliases.FindM lore) instance GHC.Base.Functor (Futhark.Optimise.MemoryBlockMerging.VariableAliases.FindM lore) instance GHC.Base.Monad (Futhark.Optimise.MemoryBlockMerging.VariableAliases.FindM lore) -- | Find all Alloc statements and associate their memory blocks with the -- allocation size. module Futhark.Optimise.MemoryBlockMerging.Reuse.AllocationSizes memBlockSizesFunDef :: LoreConstraints lore => FunDef lore -> Sizes memBlockSizesParamsBodyNonRec :: LoreConstraints lore => [FParam lore] -> Body lore -> Sizes -- | maps memory blocks to its size and space/type type Sizes = Map MName (SubExp, Space) instance Control.Monad.Writer.Class.MonadWriter Futhark.Optimise.MemoryBlockMerging.Reuse.AllocationSizes.Sizes (Futhark.Optimise.MemoryBlockMerging.Reuse.AllocationSizes.FindM lore) instance GHC.Base.Applicative (Futhark.Optimise.MemoryBlockMerging.Reuse.AllocationSizes.FindM lore) instance GHC.Base.Functor (Futhark.Optimise.MemoryBlockMerging.Reuse.AllocationSizes.FindM lore) instance GHC.Base.Monad (Futhark.Optimise.MemoryBlockMerging.Reuse.AllocationSizes.FindM lore) instance Futhark.Optimise.MemoryBlockMerging.Reuse.AllocationSizes.AllocSizeUtils Futhark.Representation.ExplicitMemory.ExplicitMemory instance Futhark.Optimise.MemoryBlockMerging.Reuse.AllocationSizes.AllocSizeUtils Futhark.Representation.ExplicitMemory.InKernel -- | Get a mapping from statement name to PrimExp (if the statement has a -- primitive expression) for all statements. module Futhark.Optimise.MemoryBlockMerging.PrimExps findPrimExpsFunDef :: FunDef ExplicitMemory -> PrimExps instance Control.Monad.State.Class.MonadState Futhark.Optimise.MemoryBlockMerging.PrimExps.CurrentTypes (Futhark.Optimise.MemoryBlockMerging.PrimExps.FindM lore) instance Control.Monad.Writer.Class.MonadWriter Futhark.Optimise.MemoryBlockMerging.PrimExps.PrimExps (Futhark.Optimise.MemoryBlockMerging.PrimExps.FindM lore) instance GHC.Base.Applicative (Futhark.Optimise.MemoryBlockMerging.PrimExps.FindM lore) instance GHC.Base.Functor (Futhark.Optimise.MemoryBlockMerging.PrimExps.FindM lore) instance GHC.Base.Monad (Futhark.Optimise.MemoryBlockMerging.PrimExps.FindM lore) -- | Find out where allocation sizes are used. For each statement, which -- sizes are in scope? module Futhark.Optimise.MemoryBlockMerging.Reuse.AllocationSizeUses findSizeUsesFunDef :: FunDef ExplicitMemory -> UsesBefore instance Control.Monad.State.Class.MonadState Futhark.Optimise.MemoryBlockMerging.Reuse.AllocationSizeUses.DeclarationsSoFar (Futhark.Optimise.MemoryBlockMerging.Reuse.AllocationSizeUses.FindM lore) instance Control.Monad.Writer.Class.MonadWriter Futhark.Optimise.MemoryBlockMerging.Reuse.AllocationSizeUses.UsesBefore (Futhark.Optimise.MemoryBlockMerging.Reuse.AllocationSizeUses.FindM lore) instance Control.Monad.Reader.Class.MonadReader Futhark.Optimise.MemoryBlockMerging.Reuse.AllocationSizeUses.SizeVars (Futhark.Optimise.MemoryBlockMerging.Reuse.AllocationSizeUses.FindM lore) instance GHC.Base.Applicative (Futhark.Optimise.MemoryBlockMerging.Reuse.AllocationSizeUses.FindM lore) instance GHC.Base.Functor (Futhark.Optimise.MemoryBlockMerging.Reuse.AllocationSizeUses.FindM lore) instance GHC.Base.Monad (Futhark.Optimise.MemoryBlockMerging.Reuse.AllocationSizeUses.FindM lore) -- | Transform a function based on a mapping from variable to memory and -- index function: Change every variable in the mapping to its possibly -- new memory block. module Futhark.Optimise.MemoryBlockMerging.MemoryUpdater -- | Transform a function to use new memory blocks. transformFromVarMemMappings :: MonadFreshNames m => VarMemMappings MemoryLoc -> VarMemMappings MName -> Map MName SubExp -> Map MName SubExp -> Bool -> FunDef ExplicitMemory -> m (FunDef ExplicitMemory) instance Control.Monad.State.Class.MonadState (Futhark.FreshNames.VNameSource, [(Futhark.Optimise.MemoryBlockMerging.Types.MName, Language.Futhark.Core.VName)]) (Futhark.Optimise.MemoryBlockMerging.MemoryUpdater.FindM lore) instance Control.Monad.Reader.Class.MonadReader Futhark.Optimise.MemoryBlockMerging.MemoryUpdater.Context (Futhark.Optimise.MemoryBlockMerging.MemoryUpdater.FindM lore) instance GHC.Base.Applicative (Futhark.Optimise.MemoryBlockMerging.MemoryUpdater.FindM lore) instance GHC.Base.Functor (Futhark.Optimise.MemoryBlockMerging.MemoryUpdater.FindM lore) instance GHC.Base.Monad (Futhark.Optimise.MemoryBlockMerging.MemoryUpdater.FindM lore) instance GHC.Show.Show Futhark.Optimise.MemoryBlockMerging.MemoryUpdater.Context instance Futhark.MonadFreshNames.MonadFreshNames (Futhark.Optimise.MemoryBlockMerging.MemoryUpdater.FindM lore) -- | Find array creations that can be set to use existing memory blocks -- instead of new allocations. module Futhark.Optimise.MemoryBlockMerging.Reuse.Core coreReuseFunDef :: MonadFreshNames m => FunDef ExplicitMemory -> FirstUses -> Interferences -> PotentialKernelDataRaceInterferences -> VarMemMappings MemorySrc -> ActualVariables -> Names -> m (FunDef ExplicitMemory) instance GHC.Show.Show Futhark.Optimise.MemoryBlockMerging.Reuse.Core.Replacement instance GHC.Show.Show Futhark.Optimise.MemoryBlockMerging.Reuse.Core.VarWithLooseEquality instance Control.Monad.State.Class.MonadState Futhark.Optimise.MemoryBlockMerging.Reuse.Core.Current (Futhark.Optimise.MemoryBlockMerging.Reuse.Core.FindM lore) instance Control.Monad.Reader.Class.MonadReader Futhark.Optimise.MemoryBlockMerging.Reuse.Core.Context (Futhark.Optimise.MemoryBlockMerging.Reuse.Core.FindM lore) instance GHC.Base.Applicative (Futhark.Optimise.MemoryBlockMerging.Reuse.Core.FindM lore) instance GHC.Base.Functor (Futhark.Optimise.MemoryBlockMerging.Reuse.Core.FindM lore) instance GHC.Base.Monad (Futhark.Optimise.MemoryBlockMerging.Reuse.Core.FindM lore) instance GHC.Show.Show Futhark.Optimise.MemoryBlockMerging.Reuse.Core.Current instance GHC.Show.Show Futhark.Optimise.MemoryBlockMerging.Reuse.Core.Context instance GHC.Classes.Eq Futhark.Optimise.MemoryBlockMerging.Reuse.Core.VarWithLooseEquality -- | Find memory block aliases. The conceptual difference from variable -- aliases is that if a variable x has an alias y, it means that x and y -- use the same memory block, but if a memory block xmem has an alias -- ymem, it means that xmem and ymem refer to the same *memory*. This is -- not commutative. module Futhark.Optimise.MemoryBlockMerging.MemoryAliases -- | Find all memory aliases in a function definition. findMemAliases :: FunDef ExplicitMemory -> VarMemMappings MemorySrc -> MemAliases instance Control.Monad.Writer.Class.MonadWriter [Futhark.Optimise.MemoryBlockMerging.Types.MemAliases] (Futhark.Optimise.MemoryBlockMerging.MemoryAliases.FindM lore) instance Control.Monad.Reader.Class.MonadReader (Futhark.Optimise.MemoryBlockMerging.Types.VarMemMappings Futhark.Optimise.MemoryBlockMerging.Types.MemorySrc) (Futhark.Optimise.MemoryBlockMerging.MemoryAliases.FindM lore) instance GHC.Base.Applicative (Futhark.Optimise.MemoryBlockMerging.MemoryAliases.FindM lore) instance GHC.Base.Functor (Futhark.Optimise.MemoryBlockMerging.MemoryAliases.FindM lore) instance GHC.Base.Monad (Futhark.Optimise.MemoryBlockMerging.MemoryAliases.FindM lore) -- | Find last uses for all memory blocks. -- -- A memory block can have more than one last use. module Futhark.Optimise.MemoryBlockMerging.Liveness.LastUse -- | Find all last uses of *memory blocks* in a function definition. findLastUses :: VarMemMappings MemorySrc -> MemAliases -> FirstUses -> Names -> FunDef ExplicitMemory -> LastUses instance Control.Monad.State.Class.MonadState Futhark.Optimise.MemoryBlockMerging.Liveness.LastUse.Current (Futhark.Optimise.MemoryBlockMerging.Liveness.LastUse.FindM lore) instance Control.Monad.Writer.Class.MonadWriter Futhark.Optimise.MemoryBlockMerging.Liveness.LastUse.LastUsesList (Futhark.Optimise.MemoryBlockMerging.Liveness.LastUse.FindM lore) instance Control.Monad.Reader.Class.MonadReader Futhark.Optimise.MemoryBlockMerging.Liveness.LastUse.Context (Futhark.Optimise.MemoryBlockMerging.Liveness.LastUse.FindM lore) instance GHC.Base.Applicative (Futhark.Optimise.MemoryBlockMerging.Liveness.LastUse.FindM lore) instance GHC.Base.Functor (Futhark.Optimise.MemoryBlockMerging.Liveness.LastUse.FindM lore) instance GHC.Base.Monad (Futhark.Optimise.MemoryBlockMerging.Liveness.LastUse.FindM lore) instance GHC.Show.Show Futhark.Optimise.MemoryBlockMerging.Liveness.LastUse.Current instance GHC.Show.Show Futhark.Optimise.MemoryBlockMerging.Liveness.LastUse.Context -- | Find memory block interferences. Maps a memory block to its -- interference set. module Futhark.Optimise.MemoryBlockMerging.Liveness.Interference -- | Find all memory block interferences in a function definition. findInterferences :: VarMemMappings MemorySrc -> MemAliases -> FirstUses -> LastUses -> Names -> FunDef ExplicitMemory -> (Interferences, PotentialKernelDataRaceInterferences) instance Control.Monad.State.Class.MonadState Futhark.Optimise.MemoryBlockMerging.Liveness.Interference.Current (Futhark.Optimise.MemoryBlockMerging.Liveness.Interference.FindM lore) instance Control.Monad.Writer.Class.MonadWriter Futhark.Optimise.MemoryBlockMerging.Liveness.Interference.InterferencesList (Futhark.Optimise.MemoryBlockMerging.Liveness.Interference.FindM lore) instance Control.Monad.Reader.Class.MonadReader Futhark.Optimise.MemoryBlockMerging.Liveness.Interference.Context (Futhark.Optimise.MemoryBlockMerging.Liveness.Interference.FindM lore) instance GHC.Base.Applicative (Futhark.Optimise.MemoryBlockMerging.Liveness.Interference.FindM lore) instance GHC.Base.Functor (Futhark.Optimise.MemoryBlockMerging.Liveness.Interference.FindM lore) instance GHC.Base.Monad (Futhark.Optimise.MemoryBlockMerging.Liveness.Interference.FindM lore) instance GHC.Show.Show Futhark.Optimise.MemoryBlockMerging.Liveness.Interference.Current instance GHC.Show.Show Futhark.Optimise.MemoryBlockMerging.Liveness.Interference.Context instance Futhark.Optimise.MemoryBlockMerging.Liveness.Interference.SpecialBodyExceptions Futhark.Representation.ExplicitMemory.ExplicitMemory instance Futhark.Optimise.MemoryBlockMerging.Liveness.Interference.SpecialBodyExceptions Futhark.Representation.ExplicitMemory.InKernel instance Futhark.Optimise.MemoryBlockMerging.Liveness.Interference.KernelInterferences Futhark.Representation.ExplicitMemory.ExplicitMemory instance Futhark.Optimise.MemoryBlockMerging.Liveness.Interference.KernelInterferences Futhark.Representation.ExplicitMemory.InKernel -- | Find first uses for all memory blocks. -- -- Array creation points. Maps statements to memory block names. -- -- A memory block can have more than one first use. module Futhark.Optimise.MemoryBlockMerging.Liveness.FirstUse -- | Find all first uses of *memory blocks* in a function definition. findFirstUses :: VarMemMappings MemorySrc -> MemAliases -> FunDef ExplicitMemory -> FirstUses createsNewArrayBase :: Exp lore -> Bool instance Control.Monad.State.Class.MonadState Futhark.Optimise.MemoryBlockMerging.Types.FirstUses (Futhark.Optimise.MemoryBlockMerging.Liveness.FirstUse.FindM lore) instance Control.Monad.Writer.Class.MonadWriter () (Futhark.Optimise.MemoryBlockMerging.Liveness.FirstUse.FindM lore) instance Control.Monad.Reader.Class.MonadReader Futhark.Optimise.MemoryBlockMerging.Liveness.FirstUse.Context (Futhark.Optimise.MemoryBlockMerging.Liveness.FirstUse.FindM lore) instance GHC.Base.Applicative (Futhark.Optimise.MemoryBlockMerging.Liveness.FirstUse.FindM lore) instance GHC.Base.Functor (Futhark.Optimise.MemoryBlockMerging.Liveness.FirstUse.FindM lore) instance GHC.Base.Monad (Futhark.Optimise.MemoryBlockMerging.Liveness.FirstUse.FindM lore) instance GHC.Show.Show Futhark.Optimise.MemoryBlockMerging.Liveness.FirstUse.Context instance Futhark.Optimise.MemoryBlockMerging.Liveness.FirstUse.ArrayUtils Futhark.Representation.ExplicitMemory.ExplicitMemory instance Futhark.Optimise.MemoryBlockMerging.Liveness.FirstUse.ArrayUtils Futhark.Representation.ExplicitMemory.InKernel -- | Find all existential variables. module Futhark.Optimise.MemoryBlockMerging.Existentials findExistentials :: LoreConstraints lore => FunDef lore -> Names instance Control.Monad.Writer.Class.MonadWriter Futhark.Representation.AST.Syntax.Core.Names (Futhark.Optimise.MemoryBlockMerging.Existentials.FindM lore) instance GHC.Base.Applicative (Futhark.Optimise.MemoryBlockMerging.Existentials.FindM lore) instance GHC.Base.Functor (Futhark.Optimise.MemoryBlockMerging.Existentials.FindM lore) instance GHC.Base.Monad (Futhark.Optimise.MemoryBlockMerging.Existentials.FindM lore) -- | Move variables as much as possible upwards in a program. module Futhark.Optimise.MemoryBlockMerging.CrudeMovingUp -- | Call findHoistees for every body, and then hoist every one of -- the found hoistees (variables). moveUpInFunDef :: FunDef ExplicitMemory -> (Body ExplicitMemory -> Maybe [FParam ExplicitMemory] -> [VName]) -> FunDef ExplicitMemory instance GHC.Show.Show Futhark.Optimise.MemoryBlockMerging.CrudeMovingUp.PrimBinding instance GHC.Show.Show Futhark.Optimise.MemoryBlockMerging.CrudeMovingUp.Origin instance GHC.Classes.Ord Futhark.Optimise.MemoryBlockMerging.CrudeMovingUp.Origin instance GHC.Classes.Eq Futhark.Optimise.MemoryBlockMerging.CrudeMovingUp.Origin -- | Move size variables used in allocation statements upwards in the -- bodies of a program to enable more memory block reuses. -- -- This should be run *before* the reuse pass, as it enables more -- optimisations. Specifically, it helps with reusing memory whose size -- needs to be changed to be the maximum of itself and another size -- -- and so, that other size needs to have been hoisted so that is in scope -- at that point. This module hoists all sizes as much as possible. module Futhark.Optimise.MemoryBlockMerging.Reuse.AllocationSizeMovingUp moveUpAllocSizesFunDef :: FunDef ExplicitMemory -> FunDef ExplicitMemory -- | Find safety condition 5 for all statements. module Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition5 findSafetyCondition5FunDef :: FunDef ExplicitMemory -> FirstUses -> VarsInUseBeforeMem instance Control.Monad.State.Class.MonadState Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition5.DeclarationsSoFar (Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition5.FindM lore) instance Control.Monad.Writer.Class.MonadWriter Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition5.VarsInUseBeforeMem (Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition5.FindM lore) instance Control.Monad.Reader.Class.MonadReader Futhark.Optimise.MemoryBlockMerging.Types.FirstUses (Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition5.FindM lore) instance GHC.Base.Applicative (Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition5.FindM lore) instance GHC.Base.Functor (Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition5.FindM lore) instance GHC.Base.Monad (Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition5.FindM lore) instance Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition5.ExtractKernelDefVars Futhark.Representation.ExplicitMemory.ExplicitMemory instance Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition5.ExtractKernelDefVars Futhark.Representation.ExplicitMemory.InKernel -- | Safety condition 3 verification. module Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition3 getVarUsesBetween :: FunDef ExplicitMemory -> VName -> VName -> Names instance Control.Monad.State.Class.MonadState Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition3.Current (Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition3.FindM lore) instance Control.Monad.Reader.Class.MonadReader Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition3.Context (Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition3.FindM lore) instance GHC.Base.Applicative (Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition3.FindM lore) instance GHC.Base.Functor (Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition3.FindM lore) instance GHC.Base.Monad (Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition3.FindM lore) instance GHC.Show.Show Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition3.Current instance GHC.Show.Show Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition3.Context -- | Find safety condition 2 for all statements. module Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition2 findSafetyCondition2FunDef :: FunDef ExplicitMemory -> AllocatedBlocksBeforeCreation instance Control.Monad.State.Class.MonadState Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition2.CurrentAllocatedBlocks (Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition2.FindM lore) instance Control.Monad.Writer.Class.MonadWriter Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition2.AllocatedBlocksBeforeCreation (Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition2.FindM lore) instance GHC.Base.Applicative (Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition2.FindM lore) instance GHC.Base.Functor (Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition2.FindM lore) instance GHC.Base.Monad (Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition2.FindM lore) instance Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition2.IsAlloc Futhark.Representation.ExplicitMemory.ExplicitMemory instance Futhark.Optimise.MemoryBlockMerging.Coalescing.SafetyCondition2.IsAlloc Futhark.Representation.ExplicitMemory.InKernel -- | Get a mapping from statement patterns to statement expression for all -- statements. module Futhark.Optimise.MemoryBlockMerging.Coalescing.Exps -- | Describes the nth pattern and the statement expression. data Exp' Exp :: Int -> Int -> Exp lore -> Exp' findExpsFunDef :: LoreConstraints lore => FunDef lore -> Exps instance Control.Monad.Writer.Class.MonadWriter Futhark.Optimise.MemoryBlockMerging.Coalescing.Exps.Exps (Futhark.Optimise.MemoryBlockMerging.Coalescing.Exps.FindM lore) instance GHC.Base.Applicative (Futhark.Optimise.MemoryBlockMerging.Coalescing.Exps.FindM lore) instance GHC.Base.Functor (Futhark.Optimise.MemoryBlockMerging.Coalescing.Exps.FindM lore) instance GHC.Base.Monad (Futhark.Optimise.MemoryBlockMerging.Coalescing.Exps.FindM lore) instance GHC.Show.Show Futhark.Optimise.MemoryBlockMerging.Coalescing.Exps.Exp' module Futhark.Optimise.MemoryBlockMerging.Coalescing.Core coreCoalesceFunDef :: MonadFreshNames m => FunDef ExplicitMemory -> VarMemMappings MemorySrc -> MemAliases -> VarAliases -> FirstUses -> LastUses -> ActualVariables -> Names -> m (FunDef ExplicitMemory) instance Control.Monad.State.Class.MonadState Futhark.Optimise.MemoryBlockMerging.Coalescing.Core.Current (Futhark.Optimise.MemoryBlockMerging.Coalescing.Core.FindM lore) instance Control.Monad.Reader.Class.MonadReader Futhark.Optimise.MemoryBlockMerging.Coalescing.Core.Context (Futhark.Optimise.MemoryBlockMerging.Coalescing.Core.FindM lore) instance GHC.Base.Applicative (Futhark.Optimise.MemoryBlockMerging.Coalescing.Core.FindM lore) instance GHC.Base.Functor (Futhark.Optimise.MemoryBlockMerging.Coalescing.Core.FindM lore) instance GHC.Base.Monad (Futhark.Optimise.MemoryBlockMerging.Coalescing.Core.FindM lore) instance GHC.Show.Show Futhark.Optimise.MemoryBlockMerging.Coalescing.Core.Context instance GHC.Show.Show Futhark.Optimise.MemoryBlockMerging.Coalescing.Core.Current -- | Move allocation statements upwards in the bodies of a program to -- enable more memory block coalescings. -- -- This should be run *before* the coalescing pass, as it enables more -- optimisations. module Futhark.Optimise.MemoryBlockMerging.Coalescing.AllocationMovingUp moveUpAllocsFunDef :: FunDef ExplicitMemory -> FunDef ExplicitMemory -- | Find all variables in a statement. module Futhark.Optimise.MemoryBlockMerging.AllExpVars findAllExpVars :: LoreConstraints lore => Exp lore -> Names instance Control.Monad.Writer.Class.MonadWriter Futhark.Representation.AST.Syntax.Core.Names (Futhark.Optimise.MemoryBlockMerging.AllExpVars.FindM lore) instance GHC.Base.Applicative (Futhark.Optimise.MemoryBlockMerging.AllExpVars.FindM lore) instance GHC.Base.Functor (Futhark.Optimise.MemoryBlockMerging.AllExpVars.FindM lore) instance GHC.Base.Monad (Futhark.Optimise.MemoryBlockMerging.AllExpVars.FindM lore) -- | Find the actual variables that need updating when a variable attribute -- needs updating. This is different than variable aliasing: Variable -- aliasing is a theoretical concept, while this module has the practical -- purpose of finding any extra variables that also need a change when a -- variable has a change of memory block. -- -- If and DoLoop statements have special requirements, as do some -- aliasing expressions. We don't want to (just) use the obvious -- statement variable; sometimes updating the memory block of one -- variable actually means updating the memory block of other variables -- as well. module Futhark.Optimise.MemoryBlockMerging.ActualVariables findActualVariables :: VarMemMappings MemorySrc -> FirstUses -> FunDef ExplicitMemory -> ActualVariables instance Control.Monad.State.Class.MonadState Futhark.Optimise.MemoryBlockMerging.Types.ActualVariables (Futhark.Optimise.MemoryBlockMerging.ActualVariables.FindM lore) instance Control.Monad.Reader.Class.MonadReader Futhark.Optimise.MemoryBlockMerging.ActualVariables.Context (Futhark.Optimise.MemoryBlockMerging.ActualVariables.FindM lore) instance GHC.Base.Applicative (Futhark.Optimise.MemoryBlockMerging.ActualVariables.FindM lore) instance GHC.Base.Functor (Futhark.Optimise.MemoryBlockMerging.ActualVariables.FindM lore) instance GHC.Base.Monad (Futhark.Optimise.MemoryBlockMerging.ActualVariables.FindM lore) instance GHC.Show.Show Futhark.Optimise.MemoryBlockMerging.ActualVariables.Context instance Futhark.Optimise.MemoryBlockMerging.ActualVariables.LookInKernelExp Futhark.Representation.ExplicitMemory.ExplicitMemory instance Futhark.Optimise.MemoryBlockMerging.ActualVariables.LookInKernelExp Futhark.Representation.ExplicitMemory.InKernel -- | Helper information for the main optimisation passes. module Futhark.Optimise.MemoryBlockMerging.AuxiliaryInfo data AuxiliaryInfo AuxiliaryInfo :: Name -> VarMemMappings MemorySrc -> MemAliases -> VarAliases -> FirstUses -> LastUses -> Interferences -> PotentialKernelDataRaceInterferences -> ActualVariables -> Names -> AuxiliaryInfo [auxName] :: AuxiliaryInfo -> Name [auxVarMemMappings] :: AuxiliaryInfo -> VarMemMappings MemorySrc [auxMemAliases] :: AuxiliaryInfo -> MemAliases [auxVarAliases] :: AuxiliaryInfo -> VarAliases [auxFirstUses] :: AuxiliaryInfo -> FirstUses [auxLastUses] :: AuxiliaryInfo -> LastUses [auxInterferences] :: AuxiliaryInfo -> Interferences [auxPotentialKernelDataRaceInterferences] :: AuxiliaryInfo -> PotentialKernelDataRaceInterferences [auxActualVariables] :: AuxiliaryInfo -> ActualVariables [auxExistentials] :: AuxiliaryInfo -> Names getAuxiliaryInfo :: FunDef ExplicitMemory -> AuxiliaryInfo instance GHC.Show.Show Futhark.Optimise.MemoryBlockMerging.AuxiliaryInfo.AuxiliaryInfo -- | Reuse the memory blocks of arrays. -- -- Enable by setting the environment variable -- MEMORY_BLOCK_MERGING_REUSE=1. module Futhark.Optimise.MemoryBlockMerging.Reuse reuseInProg :: Prog ExplicitMemory -> PassM (Prog ExplicitMemory) -- | Coalesce the memory blocks of arrays. -- -- Enable by setting the environment variable -- MEMORY_BLOCK_MERGING_COALESCING=1. module Futhark.Optimise.MemoryBlockMerging.Coalescing coalesceInProg :: Prog ExplicitMemory -> PassM (Prog ExplicitMemory) -- | Merge memory blocks. module Futhark.Optimise.MemoryBlockMerging -- | Apply the coalescing part of the memory block merging optimisation. memoryBlockMergingCoalescing :: Pass ExplicitMemory ExplicitMemory -- | Apply the reuse part of the memory block merging optimisation. memoryBlockMergingReuse :: Pass ExplicitMemory ExplicitMemory -- | The simplification engine is only willing to hoist allocations out of -- loops if the memory block resulting from the allocation is dead at the -- end of the loop. If it is not, we may cause data hazards. -- -- This module rewrites loops with memory block merge parameters such -- that each memory block is copied at the end of the iteration, thus -- ensuring that any allocation inside the loop is dead at the end of the -- loop. This is only possible for allocations whose size is -- loop-invariant, although the initial size may differ from the size -- produced by the loop result. -- -- Additionally, inside parallel kernels we also copy the initial value. -- This has the effect of making the memory block returned by the array -- non-existential, which is important for later memory expansion to -- work. module Futhark.Optimise.DoubleBuffer doubleBuffer :: Pass ExplicitMemory ExplicitMemory instance GHC.Show.Show (Futhark.Optimise.DoubleBuffer.DoubleBuffer lore) instance Futhark.MonadFreshNames.MonadFreshNames (Futhark.Optimise.DoubleBuffer.DoubleBufferM lore) instance Control.Monad.Reader.Class.MonadReader (Futhark.Optimise.DoubleBuffer.Env lore) (Futhark.Optimise.DoubleBuffer.DoubleBufferM lore) instance GHC.Base.Monad (Futhark.Optimise.DoubleBuffer.DoubleBufferM lore) instance GHC.Base.Applicative (Futhark.Optimise.DoubleBuffer.DoubleBufferM lore) instance GHC.Base.Functor (Futhark.Optimise.DoubleBuffer.DoubleBufferM lore) instance Futhark.Representation.AST.Annotations.Annotations lore => Futhark.Representation.AST.Attributes.Scope.HasScope lore (Futhark.Optimise.DoubleBuffer.DoubleBufferM lore) instance Futhark.Representation.AST.Annotations.Annotations lore => Futhark.Representation.AST.Attributes.Scope.LocalScope lore (Futhark.Optimise.DoubleBuffer.DoubleBufferM lore) -- | This module implements common-subexpression elimination. This module -- does not actually remove the duplicate, but only replaces one with a -- diference to the other. E.g: -- --
-- let a = x + y -- let b = x + y ---- -- becomes: -- --
-- let a = x + y -- let b = a ---- -- After which copy propagation in the simplifier will actually remove -- the definition of b. -- -- Our CSE is still rather stupid. No normalisation is performed, so the -- expressions x+y and y+x will be considered distinct. -- Furthermore, no expression with its own binding will be considered -- equal to any other, since the variable names will be distinct. This -- affects SOACs in particular. module Futhark.Optimise.CSE -- | Perform CSE on every functioon in a program. performCSE :: (Attributes lore, CanBeAliased (Op lore), CSEInOp (OpWithAliases (Op lore))) => Bool -> Pass lore lore -- | The operations that permit CSE. class CSEInOp op instance Futhark.Optimise.CSE.CSEInOp () instance (Futhark.Representation.AST.Attributes.Attributes lore, Futhark.Representation.AST.Attributes.Aliases.Aliased lore, Futhark.Optimise.CSE.CSEInOp (Futhark.Representation.AST.Annotations.Op lore)) => Futhark.Optimise.CSE.CSEInOp (Futhark.Representation.Kernels.Kernel.Kernel lore) instance (Futhark.Representation.AST.Attributes.Attributes lore, Futhark.Representation.AST.Attributes.Aliases.Aliased lore, Futhark.Optimise.CSE.CSEInOp (Futhark.Representation.AST.Annotations.Op lore)) => Futhark.Optimise.CSE.CSEInOp (Futhark.Representation.Kernels.KernelExp.KernelExp lore) instance Futhark.Optimise.CSE.CSEInOp op => Futhark.Optimise.CSE.CSEInOp (Futhark.Representation.ExplicitMemory.MemOp op) instance (Futhark.Representation.AST.Attributes.Attributes lore, Futhark.Representation.AST.Attributes.Aliases.CanBeAliased (Futhark.Representation.AST.Annotations.Op lore), Futhark.Optimise.CSE.CSEInOp (Futhark.Representation.AST.Attributes.Aliases.OpWithAliases (Futhark.Representation.AST.Annotations.Op lore))) => Futhark.Optimise.CSE.CSEInOp (Futhark.Representation.SOACS.SOAC.SOAC (Futhark.Representation.Aliases.Aliases lore)) module Futhark.Optimise.Simplify -- | Simplify the given program. Even if the output differs from the -- output, meaningful simplification may not have taken place - the order -- of bindings may simply have been rearranged. simplifyProg :: SimplifiableLore lore => SimpleOps lore -> RuleBook (Wise lore) -> HoistBlockers lore -> Prog lore -> PassM (Prog lore) -- | Run a simplification operation to convergence. simplifySomething :: (MonadFreshNames m, HasScope lore m, SimplifiableLore lore) => (a -> SimpleM lore b) -> (b -> a) -> SimpleOps lore -> RuleBook (Wise lore) -> HoistBlockers lore -> a -> m a -- | Simplify the given function. Even if the output differs from the -- output, meaningful simplification may not have taken place - the order -- of bindings may simply have been rearranged. Runs in a loop until -- convergence. simplifyFun :: (MonadFreshNames m, SimplifiableLore lore) => SimpleOps lore -> RuleBook (Wise lore) -> HoistBlockers lore -> FunDef lore -> m (FunDef lore) -- | Simplify just a single LambdaT. simplifyLambda :: (MonadFreshNames m, HasScope lore m, SimplifiableLore lore) => SimpleOps lore -> RuleBook (Wise lore) -> HoistBlockers lore -> Lambda lore -> [Maybe VName] -> m (Lambda lore) -- | Simplify a list of Stms. simplifyStms :: (MonadFreshNames m, HasScope lore m, SimplifiableLore lore) => SimpleOps lore -> RuleBook (Wise lore) -> HoistBlockers lore -> Stms lore -> m (Stms lore) data SimpleOps lore SimpleOps :: (SymbolTable (Wise lore) -> Pattern (Wise lore) -> Exp (Wise lore) -> SimpleM lore (ExpAttr (Wise lore))) -> (SymbolTable (Wise lore) -> Stms (Wise lore) -> Result -> SimpleM lore (Body (Wise lore))) -> (SymbolTable (Wise lore) -> [VName] -> Exp (Wise lore) -> SimpleM lore (Stm (Wise lore), Stms (Wise lore))) -> SimplifyOp lore -> SimpleOps lore [mkExpAttrS] :: SimpleOps lore -> SymbolTable (Wise lore) -> Pattern (Wise lore) -> Exp (Wise lore) -> SimpleM lore (ExpAttr (Wise lore)) [mkBodyS] :: SimpleOps lore -> SymbolTable (Wise lore) -> Stms (Wise lore) -> Result -> SimpleM lore (Body (Wise lore)) [mkLetNamesS] :: SimpleOps lore -> SymbolTable (Wise lore) -> [VName] -> Exp (Wise lore) -> SimpleM lore (Stm (Wise lore), Stms (Wise lore)) [simplifyOpS] :: SimpleOps lore -> SimplifyOp lore data SimpleM lore a type SimplifyOp lore = Op lore -> SimpleM lore (OpWithWisdom (Op lore), Stms (Wise lore)) bindableSimpleOps :: (SimplifiableLore lore, Bindable lore) => SimplifyOp lore -> SimpleOps lore noExtraHoistBlockers :: HoistBlockers lore type SimplifiableLore lore = (Attributes lore, Simplifiable (LetAttr lore), Simplifiable (FParamAttr lore), Simplifiable (LParamAttr lore), Simplifiable (RetType lore), Simplifiable (BranchType lore), CanBeWise (Op lore), IndexOp (OpWithWisdom (Op lore)), BinderOps (Wise lore), IsOp (Op lore)) data HoistBlockers lore -- | A collection of both top-down and bottom-up rules. data RuleBook lore -- | Perform copy propagation. This is done by invoking the simplifier with -- no rules, so hoisting and dead-code elimination may also take place. module Futhark.Transform.CopyPropagate -- | Run copy propagation. copyPropagateInStms :: (MonadFreshNames m, SimplifiableLore lore, HasScope lore m) => SimpleOps lore -> Stms lore -> m (Stms lore) module Futhark.Representation.SOACS.Simplify simplifySOACS :: Prog -> PassM Prog simplifyLambda :: (HasScope SOACS m, MonadFreshNames m) => Lambda -> [Maybe VName] -> m Lambda simplifyStms :: (HasScope SOACS m, MonadFreshNames m) => Stms SOACS -> m (Stms SOACS) simpleSOACS :: SimpleOps SOACS instance Futhark.Binder.BinderOps (Futhark.Optimise.Simplify.Lore.Wise Futhark.Representation.SOACS.SOACS) -- | Kernel extraction. -- -- In the following, I will use the term "width" to denote the amount of -- immediate parallelism in a map - that is, the outer size of the -- array(s) being used as input. -- --
-- map -- map(f) -- bnds_a... -- map(g) ---- -- Then we want to distribute to: -- --
-- map -- map(f) -- map -- bnds_a -- map -- map(g) ---- -- But for now only if -- --
-- map -- loop -- map -- map ---- -- If we distribute the loop and interchange the outer map into the loop, -- we get this: -- --
-- loop -- map -- map -- map -- map ---- -- Now more parallelism may be available. -- --
-- map -- map(f) -- map(g) -- map ---- -- Presume that map(f) is unbalanced. By the simple rule above, -- we would then fully sequentialise it, resulting in this: -- --
-- map -- loop -- map -- map ---- --
-- loop(f) -- map -- map(g) -- map -- map ---- -- After flattening the two nests we can obtain more parallelism. -- -- When distributing a map, we also need to distribute everything that -- the map depends on - possibly as its own map. When distributing a set -- of scalar bindings, we will need to know which of the binding results -- are used afterwards. Hence, we will need to compute usage information. -- --
-- redomap(op, -- fn (v) => -- map(f) -- map(g), -- e,a) ---- -- distributes to -- --
-- let b = map(fn v => -- let acc = e -- map(f), -- a) -- redomap(op, -- fn (v,dist) => -- map(g), -- e,a,b) ---- -- Note that there may be further kernel extraction opportunities inside -- the map(f). The downside of this approach is that the -- intermediate array (b above) must be written to main memory. -- An often better approach is to just turn the entire redomap -- into a single kernel. module Futhark.Pass.ExtractKernels -- | Transform a program using SOACs to a program using explicit kernels, -- using the kernel extraction transformation. extractKernels :: Pass SOACS Kernels instance Futhark.MonadFreshNames.MonadFreshNames Futhark.Pass.ExtractKernels.KernelM instance Control.Monad.Writer.Class.MonadWriter Futhark.Pass.ExtractKernels.KernelRes Futhark.Pass.ExtractKernels.KernelM instance Control.Monad.Reader.Class.MonadReader Futhark.Pass.ExtractKernels.KernelEnv Futhark.Pass.ExtractKernels.KernelM instance GHC.Base.Monad Futhark.Pass.ExtractKernels.KernelM instance GHC.Base.Applicative Futhark.Pass.ExtractKernels.KernelM instance GHC.Base.Functor Futhark.Pass.ExtractKernels.KernelM instance Futhark.Util.Log.MonadLogger Futhark.Pass.ExtractKernels.DistribM instance Futhark.MonadFreshNames.MonadFreshNames Futhark.Pass.ExtractKernels.DistribM instance Futhark.Representation.AST.Attributes.Scope.LocalScope Futhark.Representation.Kernels.Kernels Futhark.Pass.ExtractKernels.DistribM instance Futhark.Representation.AST.Attributes.Scope.HasScope Futhark.Representation.Kernels.Kernels Futhark.Pass.ExtractKernels.DistribM instance GHC.Base.Monad Futhark.Pass.ExtractKernels.DistribM instance GHC.Base.Applicative Futhark.Pass.ExtractKernels.DistribM instance GHC.Base.Functor Futhark.Pass.ExtractKernels.DistribM instance Futhark.Representation.AST.Attributes.Scope.HasScope Futhark.Representation.Kernels.Kernels Futhark.Pass.ExtractKernels.KernelM instance Futhark.Representation.AST.Attributes.Scope.LocalScope Futhark.Representation.Kernels.Kernels Futhark.Pass.ExtractKernels.KernelM instance Futhark.Util.Log.MonadLogger Futhark.Pass.ExtractKernels.KernelM instance GHC.Base.Semigroup Futhark.Pass.ExtractKernels.KernelRes instance GHC.Base.Monoid Futhark.Pass.ExtractKernels.KernelRes instance GHC.Base.Semigroup Futhark.Pass.ExtractKernels.PostKernels instance GHC.Base.Monoid Futhark.Pass.ExtractKernels.PostKernels module Futhark.Representation.Kernels.Simplify simplifyKernels :: Prog Kernels -> PassM (Prog Kernels) simplifyLambda :: (HasScope InKernel m, MonadFreshNames m) => KernelSpace -> Lambda InKernel -> [Maybe VName] -> m (Lambda InKernel) simplifyKernelOp :: (SimplifiableLore lore, SimplifiableLore outerlore, BodyAttr outerlore ~ (), BodyAttr lore ~ (), ExpAttr lore ~ ExpAttr outerlore, SameScope lore outerlore, RetType lore ~ RetType outerlore, BranchType lore ~ BranchType outerlore) => (KernelSpace -> SimpleOps lore) -> Env lore -> Kernel lore -> SimpleM outerlore (Kernel (Wise lore), Stms (Wise outerlore)) simplifyKernelExp :: SimplifiableLore lore => KernelSpace -> KernelExp lore -> SimpleM lore (KernelExp (Wise lore), Stms (Wise lore)) instance Futhark.Optimise.Simplify.Engine.Simplifiable Futhark.Representation.Kernels.KernelExp.SplitOrdering instance Futhark.Optimise.Simplify.Engine.Simplifiable Futhark.Representation.Kernels.KernelExp.CombineSpace instance Futhark.Optimise.Simplify.Engine.Simplifiable Futhark.Representation.Kernels.Kernel.KernelSpace instance Futhark.Optimise.Simplify.Engine.Simplifiable Futhark.Representation.Kernels.Kernel.SpaceStructure instance Futhark.Optimise.Simplify.Engine.Simplifiable Futhark.Representation.Kernels.Kernel.KernelResult instance Futhark.Optimise.Simplify.Engine.Simplifiable Futhark.Representation.Kernels.Kernel.WhichThreads instance Futhark.Binder.BinderOps (Futhark.Optimise.Simplify.Lore.Wise Futhark.Representation.Kernels.Kernels) instance Futhark.Binder.BinderOps (Futhark.Optimise.Simplify.Lore.Wise Futhark.Representation.Kernels.InKernel) module Futhark.Representation.ExplicitMemory.Simplify simplifyExplicitMemory :: Prog ExplicitMemory -> PassM (Prog ExplicitMemory) simplifyStms :: (HasScope ExplicitMemory m, MonadFreshNames m) => Stms ExplicitMemory -> m (Stms ExplicitMemory) module Futhark.Pass.Simplify simplify :: (Prog lore -> PassM (Prog lore)) -> Pass lore lore simplifySOACS :: Pass SOACS SOACS simplifyKernels :: Pass Kernels Kernels simplifyExplicitMemory :: Pass ExplicitMemory ExplicitMemory -- | Expand allocations inside of maps when possible. module Futhark.Pass.ExpandAllocations expandAllocations :: Pass ExplicitMemory ExplicitMemory -- | Go through the program and use algebraic simplification and range -- analysis to try to figure out which assertions are statically true. -- -- Currently implemented by running the simplifier with a special rule -- that is too expensive to run all the time. module Futhark.Pass.ResolveAssertions -- | The assertion-resolver pass. resolveAssertions :: Pass SOACS SOACS -- | High-level representation of SOACs. When performing -- SOAC-transformations, operating on normal Exp values is -- somewhat of a nuisance, as they can represent terms that are not -- proper SOACs. In contrast, this module exposes a SOAC representation -- that does not enable invalid representations (except for type errors). -- -- Furthermore, while standard normalised Futhark requires that the -- inputs to a SOAC are variables or constants, the representation in -- this module also supports various index-space transformations, like -- replicate or rearrange. This is also very convenient -- when implementing transformations. -- -- The names exported by this module conflict with the standard Futhark -- syntax tree constructors, so you are advised to use a qualified -- import: -- --
-- import Futhark.Analysis.HORepresentation.SOAC (SOAC) -- import qualified Futhark.Analysis.HORepresentation.SOAC as SOAC --module Futhark.Analysis.HORepresentation.SOAC -- | A definite representation of a SOAC expression. data SOAC lore Stream :: SubExp -> StreamForm lore -> Lambda lore -> [Input] -> SOAC lore Scatter :: SubExp -> Lambda lore -> [Input] -> [(SubExp, Int, VName)] -> SOAC lore Screma :: SubExp -> ScremaForm lore -> [Input] -> SOAC lore GenReduce :: SubExp -> [GenReduceOp lore] -> Lambda lore -> [Input] -> SOAC lore -- | The essential parts of a Screma factored out (everything except -- the input arrays). data ScremaForm lore ScremaForm :: Scan lore -> Reduce lore -> LambdaT lore -> ScremaForm lore -- | Returns the inputs used in a SOAC. inputs :: SOAC lore -> [Input] -- | Set the inputs to a SOAC. setInputs :: [Input] -> SOAC lore -> SOAC lore -- | The lambda used in a given SOAC. lambda :: SOAC lore -> Lambda lore -- | Set the lambda used in the SOAC. setLambda :: Lambda lore -> SOAC lore -> SOAC lore -- | The return type of a SOAC. typeOf :: SOAC lore -> [Type] -- | The "width" of a SOAC is the expected outer size of its array inputs -- _after_ input-transforms have been carried out. width :: SOAC lore -> SubExp -- | The reason why some expression cannot be converted to a SOAC -- value. data NotSOAC -- | The expression is not a (tuple-)SOAC at all. NotSOAC :: NotSOAC -- | Either convert an expression to the normalised SOAC representation, or -- a reason why the expression does not have the valid form. fromExp :: (Op lore ~ SOAC lore, Bindable lore, HasScope lore m, MonadFreshNames m) => Exp lore -> m (Either NotSOAC (SOAC lore)) -- | Convert a SOAC to the corresponding expression. toExp :: (MonadBinder m, Op (Lore m) ~ SOAC (Lore m)) => SOAC (Lore m) -> m (Exp (Lore m)) -- | Convert a SOAC to a Futhark-level SOAC. toSOAC :: MonadBinder m => SOAC (Lore m) -> m (SOAC (Lore m)) -- | One array input to a SOAC - a SOAC may have multiple inputs, but all -- are of this form. Only the array inputs are expressed with this type; -- other arguments, such as initial accumulator values, are plain -- expressions. The transforms are done left-to-right, that is, the first -- element of the ArrayTransform list is applied first. data Input Input :: ArrayTransforms -> VName -> Type -> Input -- | Create a plain array variable input with no transformations. varInput :: HasScope t f => VName -> f Input -- | Create a plain array variable input with no transformations, from an -- Ident. identInput :: Ident -> Input -- | If the given input is a plain variable input, with no transforms, -- return the variable. isVarInput :: Input -> Maybe VName -- | If the given input is a plain variable input, with no non-vacuous -- transforms, return the variable. isVarishInput :: Input -> Maybe VName -- | Add a transformation to the end of the transformation list. addTransform :: ArrayTransform -> Input -> Input -- | Add several transformations to the end of the transformation list. addTransforms :: ArrayTransforms -> Input -> Input -- | Add several transformations to the start of the transformation list. addInitialTransforms :: ArrayTransforms -> Input -> Input -- | Return the array name of the input. inputArray :: Input -> VName -- | Return the array rank (dimensionality) of an input. Just a convenient -- alias. inputRank :: Input -> Int -- | Return the type of an input. inputType :: Input -> Type -- | Return the row type of an input. Just a convenient alias. inputRowType :: Input -> Type -- | Apply the transformations to every row of the input. transformRows :: ArrayTransforms -> Input -> Input -- | Add to the input a Rearrange transform that performs an -- (k,n) transposition. The new transform will be at the end of -- the current transformation list. transposeInput :: Int -> Int -> Input -> Input -- | A sequence of array transformations, heavily inspired by -- Data.Seq. You can decompose it using viewF and -- viewL, and grow it by using |> and <|. -- These correspond closely to the similar operations for sequences, -- except that appending will try to normalise and simplify the -- transformation sequence. -- -- The data type is opaque in order to enforce normalisation invariants. -- Basically, when you grow the sequence, the implementation will try to -- coalesce neighboring permutations, for example by composing -- permutations and removing identity transformations. data ArrayTransforms -- | The empty transformation list. noTransforms :: ArrayTransforms -- | A transformation list containing just a single transformation. singleTransform :: ArrayTransform -> ArrayTransforms -- | Is it an empty transformation list? nullTransforms :: ArrayTransforms -> Bool -- | Add a transform to the end of the transformation list. (|>) :: ArrayTransforms -> ArrayTransform -> ArrayTransforms -- | Add a transform at the beginning of the transformation list. (<|) :: ArrayTransform -> ArrayTransforms -> ArrayTransforms -- | Decompose the input-end of the transformation sequence. viewf :: ArrayTransforms -> ViewF -- | A view of the first transformation to be applied. data ViewF EmptyF :: ViewF (:<) :: ArrayTransform -> ArrayTransforms -> ViewF -- | Decompose the output-end of the transformation sequence. viewl :: ArrayTransforms -> ViewL -- | A view of the last transformation to be applied. data ViewL EmptyL :: ViewL (:>) :: ArrayTransforms -> ArrayTransform -> ViewL -- | A single, simple transformation. If you want several, don't just -- create a list, use ArrayTransforms instead. data ArrayTransform -- | A permutation of an otherwise valid input. Rearrange :: Certificates -> [Int] -> ArrayTransform -- | A reshaping of an otherwise valid input. Reshape :: Certificates -> ShapeChange SubExp -> ArrayTransform -- | A reshaping of the outer dimension. ReshapeOuter :: Certificates -> ShapeChange SubExp -> ArrayTransform -- | A reshaping of everything but the outer dimension. ReshapeInner :: Certificates -> ShapeChange SubExp -> ArrayTransform -- | Replicate the rows of the array a number of times. Replicate :: Certificates -> Shape -> ArrayTransform -- | Given an expression, determine whether the expression represents an -- input transformation of an array variable. If so, return the variable -- and the transformation. Only Rearrange and Reshape are -- possible to express this way. transformFromExp :: Certificates -> Exp lore -> Maybe (VName, ArrayTransform) -- | To-Stream translation of SOACs. Returns the Stream SOAC and the -- extra-accumulator body-result ident if any. soacToStream :: (MonadFreshNames m, Bindable lore, Op lore ~ SOAC lore) => SOAC lore -> m (SOAC lore, [Ident]) instance GHC.Show.Show Futhark.Analysis.HORepresentation.SOAC.NotSOAC instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Show.Show (Futhark.Analysis.HORepresentation.SOAC.SOAC lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Classes.Eq (Futhark.Analysis.HORepresentation.SOAC.SOAC lore) instance GHC.Classes.Ord Futhark.Analysis.HORepresentation.SOAC.Input instance GHC.Classes.Eq Futhark.Analysis.HORepresentation.SOAC.Input instance GHC.Show.Show Futhark.Analysis.HORepresentation.SOAC.Input instance GHC.Show.Show Futhark.Analysis.HORepresentation.SOAC.ArrayTransforms instance GHC.Classes.Ord Futhark.Analysis.HORepresentation.SOAC.ArrayTransforms instance GHC.Classes.Eq Futhark.Analysis.HORepresentation.SOAC.ArrayTransforms instance GHC.Classes.Ord Futhark.Analysis.HORepresentation.SOAC.ArrayTransform instance GHC.Classes.Eq Futhark.Analysis.HORepresentation.SOAC.ArrayTransform instance GHC.Show.Show Futhark.Analysis.HORepresentation.SOAC.ArrayTransform instance Futhark.Representation.AST.Pretty.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Analysis.HORepresentation.SOAC.SOAC lore) instance Futhark.Transform.Substitute.Substitute Futhark.Analysis.HORepresentation.SOAC.Input instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Analysis.HORepresentation.SOAC.Input instance GHC.Base.Semigroup Futhark.Analysis.HORepresentation.SOAC.ArrayTransforms instance GHC.Base.Monoid Futhark.Analysis.HORepresentation.SOAC.ArrayTransforms instance Futhark.Transform.Substitute.Substitute Futhark.Analysis.HORepresentation.SOAC.ArrayTransforms instance Futhark.Transform.Substitute.Substitute Futhark.Analysis.HORepresentation.SOAC.ArrayTransform -- | Facilities for composing SOAC functions. Mostly intended for use by -- the fusion module, but factored into a separate module for ease of -- testing, debugging and development. Of course, there is nothing -- preventing you from using the exported functions whereever you want. -- -- Important: this module is "dumb" in the sense that it does not check -- the validity of its inputs, and does not have any functionality for -- massaging SOACs to be fusible. It is assumed that the given SOACs are -- immediately compatible. -- -- The module will, however, remove duplicate inputs after fusion. module Futhark.Optimise.Fusion.Composing -- | fuseMaps lam1 inp1 out1 lam2 inp2 fuses the function -- lam1 into lam2. Both functions must be mapping -- functions, although lam2 may have leading reduction -- parameters. inp1 and inp2 are the array inputs to -- the SOACs containing lam1 and lam2 respectively. -- out1 are the identifiers to which the output of the SOAC -- containing lam1 is bound. It is nonsensical to call this -- function unless the intersection of out1 and inp2 is -- non-empty. -- -- If lam2 accepts more parameters than there are elements in -- inp2, it is assumed that the surplus (which are positioned at -- the beginning of the parameter list) are reduction (accumulator) -- parameters, that do not correspond to array elements, and they are -- thus not modified. -- -- The result is the fused function, and a list of the array inputs -- expected by the SOAC containing the fused function. fuseMaps :: Bindable lore => Names -> Lambda lore -> [Input] -> [(VName, Ident)] -> Lambda lore -> [Input] -> (Lambda lore, [Input]) fuseRedomap :: Bindable lore => Names -> [VName] -> Lambda lore -> [SubExp] -> [SubExp] -> [Input] -> [(VName, Ident)] -> Lambda lore -> [SubExp] -> [SubExp] -> [Input] -> (Lambda lore, [Input]) mergeReduceOps :: Lambda lore -> Lambda lore -> Lambda lore module Futhark.Analysis.HORepresentation.MapNest data Nesting lore Nesting :: [VName] -> [VName] -> [Type] -> SubExp -> Nesting lore [nestingParamNames] :: Nesting lore -> [VName] [nestingResult] :: Nesting lore -> [VName] [nestingReturnType] :: Nesting lore -> [Type] [nestingWidth] :: Nesting lore -> SubExp data MapNest lore MapNest :: SubExp -> Lambda lore -> [Nesting lore] -> [Input] -> MapNest lore typeOf :: MapNest lore -> [Type] params :: MapNest lore -> [VName] inputs :: MapNest lore -> [Input] setInputs :: [Input] -> MapNest lore -> MapNest lore fromSOAC :: (Bindable lore, MonadFreshNames m, LocalScope lore m, Op lore ~ SOAC lore) => SOAC lore -> m (Maybe (MapNest lore)) toSOAC :: (MonadFreshNames m, HasScope lore m, Bindable lore, BinderOps lore, Op lore ~ SOAC lore) => MapNest lore -> m (SOAC lore) instance Futhark.Representation.AST.Annotations.Annotations lore => GHC.Show.Show (Futhark.Analysis.HORepresentation.MapNest.MapNest lore) instance GHC.Show.Show (Futhark.Analysis.HORepresentation.MapNest.Nesting lore) instance GHC.Classes.Ord (Futhark.Analysis.HORepresentation.MapNest.Nesting lore) instance GHC.Classes.Eq (Futhark.Analysis.HORepresentation.MapNest.Nesting lore) module Futhark.Optimise.Fusion.LoopKernel data FusedKer FusedKer :: SOAC -> Names -> [VName] -> Names -> Scope SOACS -> ArrayTransforms -> [VName] -> Certificates -> FusedKer -- | the SOAC expression, e.g., mapT( f(a,b), x, y ) [fsoac] :: FusedKer -> SOAC -- | Variables used in in-place updates in the kernel itself, as well as on -- the path to the kernel from the current position. This is used to -- avoid fusion that would violate in-place restrictions. [inplace] :: FusedKer -> Names -- | whether at least a fusion has been performed. [fusedVars] :: FusedKer -> [VName] -- | The set of variables that were consumed by the SOACs contributing to -- this kernel. Note that, by the type rules, the final SOAC may actually -- consume _more_ than its original contributors, which implies the need -- for Copy expressions. [fusedConsumed] :: FusedKer -> Names -- | The names in scope at the kernel. [kernelScope] :: FusedKer -> Scope SOACS [outputTransform] :: FusedKer -> ArrayTransforms [outNames] :: FusedKer -> [VName] [certificates] :: FusedKer -> Certificates newKernel :: Certificates -> SOAC -> Names -> [VName] -> Scope SOACS -> FusedKer inputs :: FusedKer -> [Input] setInputs :: [Input] -> FusedKer -> FusedKer arrInputs :: FusedKer -> Set VName kernelType :: FusedKer -> [Type] transformOutput :: ArrayTransforms -> [VName] -> [Ident] -> Binder SOACS () attemptFusion :: MonadFreshNames m => Names -> [VName] -> SOAC -> Names -> FusedKer -> m (Maybe FusedKer) type SOAC = SOAC SOACS type MapNest = MapNest SOACS instance GHC.Show.Show Futhark.Optimise.Fusion.LoopKernel.FusedKer -- | Perform horizontal and vertical fusion of SOACs. module Futhark.Optimise.Fusion fuseSOACs :: Pass SOACS SOACS instance Control.Monad.Reader.Class.MonadReader Futhark.Optimise.Fusion.FusionGEnv Futhark.Optimise.Fusion.FusionGM instance Control.Monad.State.Class.MonadState Futhark.FreshNames.VNameSource Futhark.Optimise.Fusion.FusionGM instance Control.Monad.Error.Class.MonadError Futhark.Optimise.Fusion.Error Futhark.Optimise.Fusion.FusionGM instance GHC.Base.Functor Futhark.Optimise.Fusion.FusionGM instance GHC.Base.Applicative Futhark.Optimise.Fusion.FusionGM instance GHC.Base.Monad Futhark.Optimise.Fusion.FusionGM instance GHC.Show.Show Futhark.Optimise.Fusion.KernName instance GHC.Classes.Ord Futhark.Optimise.Fusion.KernName instance GHC.Classes.Eq Futhark.Optimise.Fusion.KernName instance Futhark.MonadFreshNames.MonadFreshNames Futhark.Optimise.Fusion.FusionGM instance Futhark.Representation.AST.Attributes.Scope.HasScope Futhark.Representation.SOACS.SOACS Futhark.Optimise.Fusion.FusionGM instance GHC.Base.Semigroup Futhark.Optimise.Fusion.FusedRes instance GHC.Base.Monoid Futhark.Optimise.Fusion.FusedRes instance GHC.Show.Show Futhark.Optimise.Fusion.Error -- | Optimisation pipelines. module Futhark.Passes standardPipeline :: Pipeline SOACS SOACS sequentialPipeline :: Pipeline SOACS Kernels kernelsPipeline :: Pipeline SOACS Kernels sequentialCpuPipeline :: Pipeline SOACS ExplicitMemory gpuPipeline :: Pipeline SOACS ExplicitMemory -- | Imperative intermediate language used as a stepping stone in code -- generation. -- -- This is a generic representation parametrised on an extensible -- arbitrary operation. -- -- Originally inspired by the paper "Defunctionalizing Push Arrays" (FHPC -- '14). module Futhark.CodeGen.ImpCode -- | A collection of imperative functions. newtype Functions a Functions :: [(Name, Function a)] -> Functions a -- | Type alias for namespace control. type Function = FunctionT -- | A imperative function, containing the body as well as its low-level -- inputs and outputs, as well as its high-level arguments and results. -- The latter are only used if the function is an entry point. data FunctionT a Function :: Bool -> [Param] -> [Param] -> Code a -> [ExternalValue] -> [ExternalValue] -> FunctionT a [functionEntry] :: FunctionT a -> Bool [functionOutput] :: FunctionT a -> [Param] [functionInput] :: FunctionT a -> [Param] [functionbBody] :: FunctionT a -> Code a [functionResult] :: FunctionT a -> [ExternalValue] [functionArgs] :: FunctionT a -> [ExternalValue] -- | A description of an externally meaningful value. data ValueDesc -- | An array with memory block, memory block size, memory space, element -- type, signedness of element type (if applicable), and shape. ArrayValue :: VName -> MemSize -> Space -> PrimType -> Signedness -> [DimSize] -> ValueDesc -- | A scalar value with signedness if applicable. ScalarValue :: PrimType -> Signedness -> VName -> ValueDesc data Signedness TypeUnsigned :: Signedness TypeDirect :: Signedness -- | ^ An externally visible value. This can be an opaque value (covering -- several physical internal values), or a single value that can be used -- externally. data ExternalValue -- | The string is a human-readable description with no other semantics. OpaqueValue :: String -> [ValueDesc] -> ExternalValue TransparentValue :: ValueDesc -> ExternalValue data Param MemParam :: VName -> Space -> Param ScalarParam :: VName -> PrimType -> Param paramName :: Param -> VName data Size ConstSize :: Int64 -> Size VarSize :: VName -> Size type MemSize = Size type DimSize = Size data Type Scalar :: PrimType -> Type Mem :: MemSize -> Space -> Type -- | The memory space of a block. If DefaultSpace, this is the -- "default" space, whatever that is. The exact meaning of the -- SpaceID depends on the backend used. In GPU kernels, for -- example, this is used to distinguish between constant, global and -- shared memory spaces. In GPU-enabled host code, it is used to -- distinguish between host memory (DefaultSpace) and GPU space. data Space DefaultSpace :: Space Space :: SpaceId -> Space -- | A string representing a specific non-default memory space. type SpaceId = String data Code a Skip :: Code a (:>>:) :: Code a -> Code a -> Code a For :: VName -> IntType -> Exp -> Code a -> Code a While :: Exp -> Code a -> Code a DeclareMem :: VName -> Space -> Code a DeclareScalar :: VName -> PrimType -> Code a -- | Create a read-only array containing the given values. DeclareArray :: VName -> Space -> PrimType -> [PrimValue] -> Code a -- | Memory space must match the corresponding DeclareMem. Allocate :: VName -> Count Bytes -> Space -> Code a -- | Indicate that some memory block will never again be referenced via the -- indicated variable. However, it may still be accessed through aliases. -- It is only safe to actually deallocate the memory block if this is the -- last reference. There is no guarantee that all memory blocks will be -- freed with this statement. Backends are free to ignore it entirely. Free :: VName -> Space -> Code a -- | Destination, offset in destination, destination space, source, offset -- in source, offset space, number of bytes. Copy :: VName -> Count Bytes -> Space -> VName -> Count Bytes -> Space -> Count Bytes -> Code a Write :: VName -> Count Bytes -> PrimType -> Space -> Volatility -> Exp -> Code a SetScalar :: VName -> Exp -> Code a -- | Must be in same space. SetMem :: VName -> VName -> Space -> Code a Call :: [VName] -> Name -> [Arg] -> Code a If :: Exp -> Code a -> Code a -> Code a Assert :: Exp -> ErrorMsg Exp -> (SrcLoc, [SrcLoc]) -> Code a -- | Has the same semantics as the contained code, but the comment should -- show up in generated code for ease of inspection. Comment :: String -> Code a -> Code a -- | Print the given value (of the given type) to the screen, somehow -- annotated with the given string as a description. This has no semantic -- meaning, but is used entirely for debugging. Code generators are free -- to ignore this statement. DebugPrint :: String -> PrimType -> Exp -> Code a Op :: a -> Code a -- | Non-array values. data PrimValue IntValue :: !IntValue -> PrimValue FloatValue :: !FloatValue -> PrimValue BoolValue :: !Bool -> PrimValue -- | The only value of type cert. Checked :: PrimValue data ExpLeaf ScalarVar :: VName -> ExpLeaf SizeOf :: PrimType -> ExpLeaf Index :: VName -> Count Bytes -> PrimType -> Space -> Volatility -> ExpLeaf type Exp = PrimExp ExpLeaf -- | The volatility of a memory access. data Volatility Volatile :: Volatility Nonvolatile :: Volatility -- | A function call argument. data Arg ExpArg :: Exp -> Arg MemArg :: VName -> Arg var :: VName -> PrimType -> Exp index :: VName -> Count Bytes -> PrimType -> Space -> Volatility -> Exp -- | An error message is a list of error parts, which are concatenated to -- form the final message. newtype ErrorMsg a ErrorMsg :: [ErrorMsgPart a] -> ErrorMsg a -- | A part of an error message. data ErrorMsgPart a -- | A literal string. ErrorString :: String -> ErrorMsgPart a -- | A run-time integer value. ErrorInt32 :: a -> ErrorMsgPart a -- | A wrapper around Exp that maintains a unit as a phantom type. newtype Count u Count :: Exp -> Count u [innerExp] :: Count u -> Exp -- | Phantom type for a count of bytes. data Bytes -- | Phantom type for a count of elements. data Elements elements :: Exp -> Count Elements bytes :: Exp -> Count Bytes -- | Convert a count of elements into a count of bytes, given the -- per-element size. withElemType :: Count Elements -> PrimType -> Count Bytes sizeToExp :: Size -> Exp dimSizeToExp :: DimSize -> Count Elements memSizeToExp :: MemSize -> Count Bytes instance GHC.Show.Show a => GHC.Show.Show (Futhark.CodeGen.ImpCode.FunctionT a) instance GHC.Show.Show a => GHC.Show.Show (Futhark.CodeGen.ImpCode.Code a) instance GHC.Show.Show Futhark.CodeGen.ImpCode.Arg instance Text.PrettyPrint.Mainland.Class.Pretty (Futhark.CodeGen.ImpCode.Count u) instance Futhark.Representation.AST.Attributes.Names.FreeIn (Futhark.CodeGen.ImpCode.Count u) instance Futhark.Util.IntegralExp.IntegralExp (Futhark.CodeGen.ImpCode.Count u) instance GHC.Num.Num (Futhark.CodeGen.ImpCode.Count u) instance GHC.Show.Show (Futhark.CodeGen.ImpCode.Count u) instance GHC.Classes.Eq (Futhark.CodeGen.ImpCode.Count u) instance GHC.Show.Show Futhark.CodeGen.ImpCode.ExpLeaf instance GHC.Classes.Eq Futhark.CodeGen.ImpCode.ExpLeaf instance GHC.Show.Show Futhark.CodeGen.ImpCode.Volatility instance GHC.Classes.Ord Futhark.CodeGen.ImpCode.Volatility instance GHC.Classes.Eq Futhark.CodeGen.ImpCode.Volatility instance GHC.Show.Show Futhark.CodeGen.ImpCode.ExternalValue instance GHC.Show.Show Futhark.CodeGen.ImpCode.ValueDesc instance GHC.Classes.Eq Futhark.CodeGen.ImpCode.ValueDesc instance GHC.Show.Show Futhark.CodeGen.ImpCode.Signedness instance GHC.Classes.Eq Futhark.CodeGen.ImpCode.Signedness instance GHC.Show.Show Futhark.CodeGen.ImpCode.Param instance GHC.Show.Show Futhark.CodeGen.ImpCode.Size instance GHC.Classes.Eq Futhark.CodeGen.ImpCode.Size instance GHC.Base.Semigroup (Futhark.CodeGen.ImpCode.Functions a) instance GHC.Base.Monoid (Futhark.CodeGen.ImpCode.Functions a) instance Text.PrettyPrint.Mainland.Class.Pretty op => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.CodeGen.ImpCode.Functions op) instance GHC.Base.Functor Futhark.CodeGen.ImpCode.Functions instance Data.Foldable.Foldable Futhark.CodeGen.ImpCode.Functions instance Data.Traversable.Traversable Futhark.CodeGen.ImpCode.Functions instance Text.PrettyPrint.Mainland.Class.Pretty op => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.CodeGen.ImpCode.FunctionT op) instance GHC.Base.Functor Futhark.CodeGen.ImpCode.FunctionT instance Data.Foldable.Foldable Futhark.CodeGen.ImpCode.FunctionT instance Data.Traversable.Traversable Futhark.CodeGen.ImpCode.FunctionT instance GHC.Base.Semigroup (Futhark.CodeGen.ImpCode.Code a) instance GHC.Base.Monoid (Futhark.CodeGen.ImpCode.Code a) instance Text.PrettyPrint.Mainland.Class.Pretty op => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.CodeGen.ImpCode.Code op) instance GHC.Base.Functor Futhark.CodeGen.ImpCode.Code instance Data.Foldable.Foldable Futhark.CodeGen.ImpCode.Code instance Data.Traversable.Traversable Futhark.CodeGen.ImpCode.Code instance Futhark.Representation.AST.Attributes.Names.FreeIn a => Futhark.Representation.AST.Attributes.Names.FreeIn (Futhark.CodeGen.ImpCode.Code a) instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.Arg instance Futhark.Representation.AST.Attributes.Names.FreeIn Futhark.CodeGen.ImpCode.Arg instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.ExpLeaf instance Futhark.Representation.AST.Attributes.Names.FreeIn Futhark.CodeGen.ImpCode.ExpLeaf instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.ExternalValue instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.ValueDesc instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.Param instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.Size instance Futhark.Representation.AST.Attributes.Names.FreeIn Futhark.CodeGen.ImpCode.Size module Futhark.CodeGen.SetDefaultSpace -- | Set all uses of DefaultSpace in the given functions to another -- memory space. setDefaultSpace :: Space -> Functions op -> Functions op module Futhark.CodeGen.ImpGen compileProg :: (ExplicitMemorish lore, MonadFreshNames m) => Operations lore op -> Space -> Prog lore -> m (Either InternalError (Functions op)) -- | How to compile an ExpT. type OpCompiler lore op = Destination -> Op lore -> ImpM lore op () -- | How to compile an Exp. type ExpCompiler lore op = Destination -> Exp lore -> ImpM lore op () type CopyCompiler lore op = PrimType -> MemLocation -> MemLocation -> Count Elements " Number of row elements of the source." -> ImpM lore op () -- | How to compile a BodyT. type BodyCompiler lore op = Destination -> Body lore -> ImpM lore op () data Operations lore op Operations :: ExpCompiler lore op -> OpCompiler lore op -> BodyCompiler lore op -> CopyCompiler lore op -> Operations lore op [opsExpCompiler] :: Operations lore op -> ExpCompiler lore op [opsOpCompiler] :: Operations lore op -> OpCompiler lore op [opsBodyCompiler] :: Operations lore op -> BodyCompiler lore op [opsCopyCompiler] :: Operations lore op -> CopyCompiler lore op -- | An operations set for which the expression compiler always returns -- CompileExp. defaultOperations :: (ExplicitMemorish lore, FreeIn op) => OpCompiler lore op -> Operations lore op -- | When compiling an expression, this is a description of where the -- result should end up. The integer is a reference to the construct that -- gave rise to this destination (for patterns, this will be the tag of -- the first name in the pattern). This can be used to make the generated -- code easier to relate to the original code. data Destination Destination :: Maybe Int -> [ValueDestination] -> Destination [destinationTag] :: Destination -> Maybe Int [valueDestinations] :: Destination -> [ValueDestination] data ValueDestination ScalarDestination :: VName -> ValueDestination ArrayElemDestination :: VName -> PrimType -> Space -> Count Bytes -> ValueDestination MemoryDestination :: VName -> ValueDestination -- | The MemLocation is Just if a copy if required. If it is -- Nothing, then a copy/assignment of a memory block somewhere -- takes care of this array. ArrayDestination :: Maybe MemLocation -> ValueDestination -- | When an array is declared, this is where it is stored. data MemLocation MemLocation :: VName -> [DimSize] -> IxFun Exp -> MemLocation [memLocationName] :: MemLocation -> VName [memLocationShape] :: MemLocation -> [DimSize] [memLocationIxFun] :: MemLocation -> IxFun Exp data MemEntry MemEntry :: MemSize -> Space -> MemEntry [entryMemSize] :: MemEntry -> MemSize [entryMemSpace] :: MemEntry -> Space newtype ScalarEntry ScalarEntry :: PrimType -> ScalarEntry [entryScalarType] :: ScalarEntry -> PrimType data ImpM lore op a data Env lore op subImpM :: Operations lore' op' -> ImpM lore' op' a -> ImpM lore op (a, Code op') subImpM_ :: Operations lore' op' -> ImpM lore' op' a -> ImpM lore op (Code op') -- | Emit some generated imperative code. emit :: Code op -> ImpM lore op () -- | Execute a code generation action, returning the code that was emitted. collect :: ImpM lore op () -> ImpM lore op (Code op) -- | Execute a code generation action, wrapping the generated code within a -- Comment with the given description. comment :: String -> ImpM lore op () -> ImpM lore op () -- | Every non-scalar variable must be associated with an entry. data VarEntry lore ArrayVar :: Maybe (Exp lore) -> ArrayEntry -> VarEntry lore ScalarVar :: Maybe (Exp lore) -> ScalarEntry -> VarEntry lore MemVar :: Maybe (Exp lore) -> MemEntry -> VarEntry lore data ArrayEntry ArrayEntry :: MemLocation -> PrimType -> ArrayEntry [entryArrayLocation] :: ArrayEntry -> MemLocation [entryArrayElemType] :: ArrayEntry -> PrimType lookupVar :: VName -> ImpM lore op (VarEntry lore) lookupArray :: VName -> ImpM lore op ArrayEntry arrayLocation :: VName -> ImpM lore op MemLocation lookupMemory :: VName -> ImpM lore op MemEntry compileSubExp :: SubExp -> ImpM lore op Exp compileSubExpOfType :: PrimType -> SubExp -> Exp compileSubExpTo :: ValueDestination -> SubExp -> ImpM lore op () compilePrimExp :: PrimExp VName -> Exp -- | compileAlloc dest size space allocates n bytes of -- memory in space, writing the result to dest, which -- must be a single MemoryDestination, compileAlloc :: Destination -> SubExp -> Space -> ImpM lore op () subExpToDimSize :: SubExp -> ImpM lore op DimSize declaringLParams :: ExplicitMemorish lore => [LParam lore] -> ImpM lore op a -> ImpM lore op a declaringFParams :: ExplicitMemorish lore => [FParam lore] -> ImpM lore op a -> ImpM lore op a declaringVarEntry :: VName -> VarEntry lore -> ImpM lore op a -> ImpM lore op a declaringScope :: Maybe (Exp lore) -> Scope ExplicitMemory -> ImpM lore op a -> ImpM lore op a declaringScopes :: [(Maybe (Exp lore), Scope ExplicitMemory)] -> ImpM lore op a -> ImpM lore op a declaringPrimVar :: VName -> PrimType -> ImpM lore op a -> ImpM lore op a declaringPrimVars :: [(VName, PrimType)] -> ImpM lore op a -> ImpM lore op a withPrimVar :: VName -> PrimType -> ImpM lore op a -> ImpM lore op a everythingVolatile :: ImpM lore op a -> ImpM lore op a compileBody :: Destination -> Body lore -> ImpM lore op () compileLoopBody :: (ExplicitMemorish lore, FreeIn op) => [VName] -> Body lore -> ImpM lore op (Code op) defCompileBody :: (ExplicitMemorish lore, FreeIn op) => Destination -> Body lore -> ImpM lore op () compileStms :: (ExplicitMemorish lore, FreeIn op) => Names -> [Stm lore] -> ImpM lore op () -> ImpM lore op () compileExp :: Destination -> Exp lore -> ImpM lore op () defCompileExp :: (ExplicitMemorish lore, FreeIn op) => Destination -> Exp lore -> ImpM lore op () sliceArray :: MemLocation -> Slice Exp -> MemLocation offsetArray :: MemLocation -> Exp -> MemLocation strideArray :: MemLocation -> Exp -> MemLocation fullyIndexArray :: VName -> [Exp] -> ImpM lore op (VName, Space, Count Bytes) fullyIndexArray' :: MemLocation -> [Exp] -> PrimType -> ImpM lore op (VName, Space, Count Bytes) varIndex :: VName -> Exp dimSizeToExp :: DimSize -> Count Elements dimSizeToSubExp :: Size -> SubExp destinationFromParam :: Param (MemBound u) -> ImpM lore op ValueDestination destinationFromParams :: [Param (MemBound u)] -> ImpM lore op Destination destinationFromPattern :: ExplicitMemorish lore => Pattern lore -> ImpM lore op Destination -- | Remove the array targets. funcallTargets :: Destination -> ImpM lore op [VName] copy :: CopyCompiler lore op -- | Copy from here to there; both destination and source be indexeded. If -- so, they better be arrays of enough dimensions. This function will -- generally just Do What I Mean, and Do The Right Thing. Both -- destination and source must be in scope. copyDWIM :: VName -> [Exp] -> SubExp -> [Exp] -> ImpM lore op () -- | Like copyDWIM, but the target is a ValueDestination -- instead of a variable name. copyDWIMDest :: ValueDestination -> [Exp] -> SubExp -> [Exp] -> ImpM lore op () copyElementWise :: CopyCompiler lore op instance Control.Monad.Error.Class.MonadError Futhark.Error.InternalError (Futhark.CodeGen.ImpGen.ImpM lore op) instance Control.Monad.Writer.Class.MonadWriter (Futhark.CodeGen.ImpCode.Code op) (Futhark.CodeGen.ImpGen.ImpM lore op) instance Control.Monad.Reader.Class.MonadReader (Futhark.CodeGen.ImpGen.Env lore op) (Futhark.CodeGen.ImpGen.ImpM lore op) instance Control.Monad.State.Class.MonadState Futhark.FreshNames.VNameSource (Futhark.CodeGen.ImpGen.ImpM lore op) instance GHC.Base.Monad (Futhark.CodeGen.ImpGen.ImpM lore op) instance GHC.Base.Applicative (Futhark.CodeGen.ImpGen.ImpM lore op) instance GHC.Base.Functor (Futhark.CodeGen.ImpGen.ImpM lore op) instance GHC.Show.Show Futhark.CodeGen.ImpGen.Destination instance GHC.Show.Show Futhark.CodeGen.ImpGen.ValueDestination instance GHC.Show.Show Futhark.CodeGen.ImpGen.MemLocation instance GHC.Classes.Eq Futhark.CodeGen.ImpGen.MemLocation instance Control.Monad.Fail.MonadFail (Futhark.CodeGen.ImpGen.ImpM lore op) instance Futhark.MonadFreshNames.MonadFreshNames (Futhark.CodeGen.ImpGen.ImpM lore op) instance Futhark.Representation.AST.Attributes.Scope.HasScope Futhark.Representation.SOACS.SOACS (Futhark.CodeGen.ImpGen.ImpM lore op) -- | Sequential imperative code. module Futhark.CodeGen.ImpCode.Sequential -- | An imperative program. type Program = Functions Sequential -- | An imperative function. type Function = Function Sequential -- | A imperative function, containing the body as well as its low-level -- inputs and outputs, as well as its high-level arguments and results. -- The latter are only used if the function is an entry point. data FunctionT a Function :: Bool -> [Param] -> [Param] -> Code a -> [ExternalValue] -> [ExternalValue] -> FunctionT a -- | A piece of imperative code. type Code = Code Sequential -- | Phantom type for identifying sequential imperative code. data Sequential -- | 8-bit signed integer type data Int8 -- | 16-bit signed integer type data Int16 -- | 32-bit signed integer type data Int32 -- | 64-bit signed integer type data Int64 -- | 8-bit unsigned integer type data Word8 -- | 16-bit unsigned integer type data Word16 -- | 32-bit unsigned integer type data Word32 -- | 64-bit unsigned integer type data Word64 -- | Prettyprint a value, wrapped to 80 characters. pretty :: Pretty a => a -> String -- | Conversion operators try to generalise the from t0 x to t1 -- instructions from LLVM. data ConvOp -- | Zero-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. ZExt :: IntType -> IntType -> ConvOp -- | Sign-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. SExt :: IntType -> IntType -> ConvOp -- | Convert value of the former floating-point type to the latter. If the -- new type is smaller, the result is a truncation. FPConv :: FloatType -> FloatType -> ConvOp -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). FPToUI :: FloatType -> IntType -> ConvOp -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). FPToSI :: FloatType -> IntType -> ConvOp -- | Convert an unsigned integer to a floating-point value. UIToFP :: IntType -> FloatType -> ConvOp -- | Convert a signed integer to a floating-point value. SIToFP :: IntType -> FloatType -> ConvOp -- | Convert an integer to a boolean value. Zero becomes false; anything -- else is true. IToB :: IntType -> ConvOp -- | Convert a boolean to an integer. True is converted to 1 and False to -- 0. BToI :: IntType -> ConvOp -- | Comparison operators are like BinOps, but they return -- PrimTypes. The somewhat ugly constructor names are straight out -- of LLVM. data CmpOp -- | All types equality. CmpEq :: PrimType -> CmpOp -- | Unsigned less than. CmpUlt :: IntType -> CmpOp -- | Unsigned less than or equal. CmpUle :: IntType -> CmpOp -- | Signed less than. CmpSlt :: IntType -> CmpOp -- | Signed less than or equal. CmpSle :: IntType -> CmpOp -- | Floating-point less than. FCmpLt :: FloatType -> CmpOp -- | Floating-point less than or equal. FCmpLe :: FloatType -> CmpOp -- | Boolean less than. CmpLlt :: CmpOp -- | Boolean less than or equal. CmpLle :: CmpOp -- | Binary operators. These correspond closely to the binary operators in -- LLVM. Most are parametrised by their expected input and output types. data BinOp -- | Integer addition. Add :: IntType -> BinOp -- | Floating-point addition. FAdd :: FloatType -> BinOp -- | Integer subtraction. Sub :: IntType -> BinOp -- | Floating-point subtraction. FSub :: FloatType -> BinOp -- | Integer multiplication. Mul :: IntType -> BinOp -- | Floating-point multiplication. FMul :: FloatType -> BinOp -- | Unsigned integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. UDiv :: IntType -> BinOp -- | Signed integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. SDiv :: IntType -> BinOp -- | Floating-point division. FDiv :: FloatType -> BinOp -- | Unsigned integer modulus; the countepart to UDiv. UMod :: IntType -> BinOp -- | Signed integer modulus; the countepart to SDiv. SMod :: IntType -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- sdiv instruction in LLVM. SQuot :: IntType -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- srem instruction in LLVM. SRem :: IntType -> BinOp -- | Returns the smallest of two signed integers. SMin :: IntType -> BinOp -- | Returns the smallest of two unsigned integers. UMin :: IntType -> BinOp -- | Returns the smallest of two floating-point numbers. FMin :: FloatType -> BinOp -- | Returns the greatest of two signed integers. SMax :: IntType -> BinOp -- | Returns the greatest of two unsigned integers. UMax :: IntType -> BinOp -- | Returns the greatest of two floating-point numbers. FMax :: FloatType -> BinOp -- | Left-shift. Shl :: IntType -> BinOp -- | Logical right-shift, zero-extended. LShr :: IntType -> BinOp -- | Arithmetic right-shift, sign-extended. AShr :: IntType -> BinOp -- | Bitwise and. And :: IntType -> BinOp -- | Bitwise or. Or :: IntType -> BinOp -- | Bitwise exclusive-or. Xor :: IntType -> BinOp -- | Integer exponentiation. Pow :: IntType -> BinOp -- | Floating-point exponentiation. FPow :: FloatType -> BinOp -- | Boolean and - not short-circuiting. LogAnd :: BinOp -- | Boolean or - not short-circuiting. LogOr :: BinOp -- | Various unary operators. It is a bit ad-hoc what is a unary operator -- and what is a built-in function. Perhaps these should all go away -- eventually. data UnOp -- | E.g., ! True == False. Not :: UnOp -- | E.g., ~(~1) = 1. Complement :: IntType -> UnOp -- | abs(-2) = 2. Abs :: IntType -> UnOp -- | fabs(-2.0) = 2.0. FAbs :: FloatType -> UnOp -- | Signed sign function: ssignum(-2) = -1. SSignum :: IntType -> UnOp -- | Unsigned sign function: usignum(2) = 1. USignum :: IntType -> UnOp -- | Non-array values. data PrimValue IntValue :: !IntValue -> PrimValue FloatValue :: !FloatValue -> PrimValue BoolValue :: !Bool -> PrimValue -- | The only value of type cert. Checked :: PrimValue -- | A floating-point value. data FloatValue Float32Value :: !Float -> FloatValue Float64Value :: !Double -> FloatValue -- | An integer value. data IntValue Int8Value :: !Int8 -> IntValue Int16Value :: !Int16 -> IntValue Int32Value :: !Int32 -> IntValue Int64Value :: !Int64 -> IntValue -- | Low-level primitive types. data PrimType IntType :: IntType -> PrimType FloatType :: FloatType -> PrimType Bool :: PrimType Cert :: PrimType -- | A floating point type. data FloatType Float32 :: FloatType Float64 :: FloatType -- | An integer type, ordered by size. Note that signedness is not a -- property of the type, but a property of the operations performed on -- values of these types. data IntType Int8 :: IntType Int16 :: IntType Int32 :: IntType Int64 :: IntType -- | A list of all integer types. allIntTypes :: [IntType] -- | A list of all floating-point types. allFloatTypes :: [FloatType] -- | A list of all primitive types. allPrimTypes :: [PrimType] -- | Create an IntValue from a type and an Integer. intValue :: Integral int => IntType -> int -> IntValue intValueType :: IntValue -> IntType -- | Convert an IntValue to any Integral type. valueIntegral :: Integral int => IntValue -> int -- | Create a FloatValue from a type and a Rational. floatValue :: Real num => FloatType -> num -> FloatValue floatValueType :: FloatValue -> FloatType -- | The type of a basic value. primValueType :: PrimValue -> PrimType -- | A "blank" value of the given primitive type - this is zero, or -- whatever is close to it. Don't depend on this value, but use it for -- e.g. creating arrays to be populated by do-loops. blankPrimValue :: PrimType -> PrimValue -- | A list of all unary operators for all types. allUnOps :: [UnOp] -- | A list of all binary operators for all types. allBinOps :: [BinOp] -- | A list of all comparison operators for all types. allCmpOps :: [CmpOp] -- | A list of all conversion operators for all types. allConvOps :: [ConvOp] doUnOp :: UnOp -> PrimValue -> Maybe PrimValue -- | E.g., ~(~1) = 1. doComplement :: IntValue -> IntValue -- | abs(-2) = 2. doAbs :: IntValue -> IntValue -- | abs(-2.0) = 2.0. doFAbs :: FloatValue -> FloatValue -- | ssignum(-2) = -1. doSSignum :: IntValue -> IntValue -- | usignum(-2) = -1. doUSignum :: IntValue -> IntValue doBinOp :: BinOp -> PrimValue -> PrimValue -> Maybe PrimValue -- | Integer addition. doAdd :: IntValue -> IntValue -> IntValue -- | Integer multiplication. doMul :: IntValue -> IntValue -> IntValue -- | Signed integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. doSDiv :: IntValue -> IntValue -> Maybe IntValue -- | Signed integer modulus; the countepart to SDiv. doSMod :: IntValue -> IntValue -> Maybe IntValue -- | Signed integer exponentatation. doPow :: IntValue -> IntValue -> Maybe IntValue doConvOp :: ConvOp -> PrimValue -> Maybe PrimValue -- | Zero-extend the given integer value to the size of the given type. If -- the type is smaller than the given value, the result is a truncation. doZExt :: IntValue -> IntType -> IntValue -- | Sign-extend the given integer value to the size of the given type. If -- the type is smaller than the given value, the result is a truncation. doSExt :: IntValue -> IntType -> IntValue -- | Convert the former floating-point type to the latter. doFPConv :: FloatValue -> FloatType -> FloatValue -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). doFPToUI :: FloatValue -> IntType -> IntValue -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). doFPToSI :: FloatValue -> IntType -> IntValue -- | Convert an unsigned integer to a floating-point value. doUIToFP :: IntValue -> FloatType -> FloatValue -- | Convert a signed integer to a floating-point value. doSIToFP :: IntValue -> FloatType -> FloatValue doCmpOp :: CmpOp -> PrimValue -> PrimValue -> Maybe Bool -- | Compare any two primtive values for exact equality. doCmpEq :: PrimValue -> PrimValue -> Bool -- | Unsigned less than. doCmpUlt :: IntValue -> IntValue -> Bool -- | Unsigned less than or equal. doCmpUle :: IntValue -> IntValue -> Bool -- | Signed less than. doCmpSlt :: IntValue -> IntValue -> Bool -- | Signed less than or equal. doCmpSle :: IntValue -> IntValue -> Bool -- | Floating-point less than. doFCmpLt :: FloatValue -> FloatValue -> Bool -- | Floating-point less than or equal. doFCmpLe :: FloatValue -> FloatValue -> Bool -- | Translate an IntValue to Word64. This is guaranteed to -- fit. intToWord64 :: IntValue -> Word64 -- | Translate an IntValue to IntType. This is guaranteed to -- fit. intToInt64 :: IntValue -> Int64 -- | The result type of a binary operator. binOpType :: BinOp -> PrimType -- | The operand types of a comparison operator. cmpOpType :: CmpOp -> PrimType -- | The operand and result type of a unary operator. unOpType :: UnOp -> PrimType -- | The input and output types of a conversion operator. convOpType :: ConvOp -> (PrimType, PrimType) -- | A mapping from names of primitive functions to their parameter types, -- their result type, and a function for evaluating them. primFuns :: Map String ([PrimType], PrimType, [PrimValue] -> Maybe PrimValue) -- | Is the given value kind of zero? zeroIsh :: PrimValue -> Bool -- | Is the given value kind of one? oneIsh :: PrimValue -> Bool -- | Is the given value kind of negative? negativeIsh :: PrimValue -> Bool -- | The size of a value of a given primitive type in bites. primBitSize :: PrimType -> Int -- | The size of a value of a given primitive type in eight-bit bytes. primByteSize :: Num a => PrimType -> a -- | True if the given binary operator is commutative. commutativeBinOp :: BinOp -> Bool convOpFun :: ConvOp -> String -- | True if signed. Only makes a difference for integer types. prettySigned :: Bool -> PrimType -> String -- | A name tagged with some integer. Only the integer is used in -- comparisons, no matter the type of vn. data VName VName :: !Name -> !Int -> VName -- | The abstract (not really) type representing names in the Futhark -- compiler. Strings, being lists of characters, are very slow, -- while Texts are based on byte-arrays. data Name -- | Whether some operator is commutative or not. The Monoid -- instance returns the least commutative of its arguments. data Commutativity Noncommutative :: Commutativity Commutative :: Commutativity data StreamOrd InOrder :: StreamOrd Disorder :: StreamOrd -- | The uniqueness attribute of a type. This essentially indicates whether -- or not in-place modifications are acceptable. With respect to -- ordering, Unique is greater than Nonunique. data Uniqueness -- | May have references outside current function. Nonunique :: Uniqueness -- | No references outside current function. Unique :: Uniqueness -- | The name of the default program entry point (main). defaultEntryPoint :: Name -- | Convert a name to the corresponding list of characters. nameToString :: Name -> String -- | Convert a list of characters to the corresponding name. nameFromString :: String -> Name -- | Convert a name to the corresponding Text. nameToText :: Name -> Text -- | Convert a Text to the corresponding name. nameFromText :: Text -> Name -- | A human-readable location string, of the form -- filename:lineno:columnno. locStr :: SrcLoc -> String -- | Return the tag contained in the VName. baseTag :: VName -> Int -- | Return the name contained in the VName. baseName :: VName -> Name -- | Return the base Name converted to a string. baseString :: VName -> String -- | A part of an error message. data ErrorMsgPart a -- | A literal string. ErrorString :: String -> ErrorMsgPart a -- | A run-time integer value. ErrorInt32 :: a -> ErrorMsgPart a -- | An error message is a list of error parts, which are concatenated to -- form the final message. newtype ErrorMsg a ErrorMsg :: [ErrorMsgPart a] -> ErrorMsg a -- | A string representing a specific non-default memory space. type SpaceId = String -- | The memory space of a block. If DefaultSpace, this is the -- "default" space, whatever that is. The exact meaning of the -- SpaceID depends on the backend used. In GPU kernels, for -- example, this is used to distinguish between constant, global and -- shared memory spaces. In GPU-enabled host code, it is used to -- distinguish between host memory (DefaultSpace) and GPU space. data Space DefaultSpace :: Space Space :: SpaceId -> Space -- | A primitive expression parametrised over the representation of free -- variables. data PrimExp v LeafExp :: v -> PrimType -> PrimExp v ValueExp :: PrimValue -> PrimExp v BinOpExp :: BinOp -> PrimExp v -> PrimExp v -> PrimExp v CmpOpExp :: CmpOp -> PrimExp v -> PrimExp v -> PrimExp v UnOpExp :: UnOp -> PrimExp v -> PrimExp v ConvOpExp :: ConvOp -> PrimExp v -> PrimExp v FunExp :: String -> [PrimExp v] -> PrimType -> PrimExp v -- | Evaluate a PrimExp in the given monad. Invokes fail on -- type errors. evalPrimExp :: (Pretty v, Monad m) => (v -> m PrimValue) -> PrimExp v -> m PrimValue -- | The type of values returned by a PrimExp. This function -- returning does not imply that the PrimExp is type-correct. primExpType :: PrimExp v -> PrimType -- | If the given PrimExp is a constant of the wrong integer type, -- coerce it to the given integer type. This is a workaround for an issue -- in the Num instance. coerceIntPrimExp :: IntType -> PrimExp v -> PrimExp v -- | Phantom type for a count of bytes. data Bytes -- | Phantom type for a count of elements. data Elements -- | A wrapper around Exp that maintains a unit as a phantom type. newtype Count u Count :: Exp -> Count u [innerExp] :: Count u -> Exp -- | A function call argument. data Arg ExpArg :: Exp -> Arg MemArg :: VName -> Arg type Exp = PrimExp ExpLeaf data ExpLeaf ScalarVar :: VName -> ExpLeaf SizeOf :: PrimType -> ExpLeaf Index :: VName -> Count Bytes -> PrimType -> Space -> Volatility -> ExpLeaf -- | The volatility of a memory access. data Volatility Volatile :: Volatility Nonvolatile :: Volatility -- | Has the same semantics as the contained code, but the comment should -- show up in generated code for ease of inspection. -- | Indicate that some memory block will never again be referenced via the -- indicated variable. However, it may still be accessed through aliases. -- It is only safe to actually deallocate the memory block if this is the -- last reference. There is no guarantee that all memory blocks will be -- freed with this statement. Backends are free to ignore it entirely. -- | Memory space must match the corresponding DeclareMem. -- | Destination, offset in destination, destination space, source, offset -- in source, offset space, number of bytes. -- | Create a read-only array containing the given values. -- | Must be in same space. -- | Print the given value (of the given type) to the screen, somehow -- annotated with the given string as a description. This has no semantic -- meaning, but is used entirely for debugging. Code generators are free -- to ignore this statement. -- | A imperative function, containing the body as well as its low-level -- inputs and outputs, as well as its high-level arguments and results. -- The latter are only used if the function is an entry point. data FunctionT a -- | ^ An externally visible value. This can be an opaque value (covering -- several physical internal values), or a single value that can be used -- externally. data ExternalValue -- | The string is a human-readable description with no other semantics. OpaqueValue :: String -> [ValueDesc] -> ExternalValue TransparentValue :: ValueDesc -> ExternalValue -- | A description of an externally meaningful value. data ValueDesc -- | An array with memory block, memory block size, memory space, element -- type, signedness of element type (if applicable), and shape. ArrayValue :: VName -> MemSize -> Space -> PrimType -> Signedness -> [DimSize] -> ValueDesc -- | A scalar value with signedness if applicable. ScalarValue :: PrimType -> Signedness -> VName -> ValueDesc data Signedness TypeUnsigned :: Signedness TypeDirect :: Signedness -- | A collection of imperative functions. newtype Functions a Functions :: [(Name, Function a)] -> Functions a data Param MemParam :: VName -> Space -> Param ScalarParam :: VName -> PrimType -> Param data Type Scalar :: PrimType -> Type Mem :: MemSize -> Space -> Type type DimSize = Size type MemSize = Size data Size ConstSize :: Int64 -> Size VarSize :: VName -> Size paramName :: Param -> VName elements :: Exp -> Count Elements bytes :: Exp -> Count Bytes -- | Convert a count of elements into a count of bytes, given the -- per-element size. withElemType :: Count Elements -> PrimType -> Count Bytes dimSizeToExp :: DimSize -> Count Elements memSizeToExp :: MemSize -> Count Bytes sizeToExp :: Size -> Exp var :: VName -> PrimType -> Exp index :: VName -> Count Bytes -> PrimType -> Space -> Volatility -> Exp instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.Sequential.Sequential instance Futhark.Representation.AST.Attributes.Names.FreeIn Futhark.CodeGen.ImpCode.Sequential.Sequential module Futhark.CodeGen.ImpGen.Sequential compileProg :: MonadFreshNames m => Prog ExplicitMemory -> m (Either InternalError Program) -- | Imperative code with an OpenCL component. -- -- Apart from ordinary imperative code, this also carries around an -- OpenCL program as a string, as well as a list of kernels defined by -- the OpenCL program. -- -- The imperative code has been augmented with a LaunchKernel -- operation that allows one to execute an OpenCL kernel. module Futhark.CodeGen.ImpCode.OpenCL -- | An program calling OpenCL kernels. data Program Program :: String -> String -> [KernelName] -> [PrimType] -> Map VName (SizeClass, Name) -> Functions OpenCL -> Program [openClProgram] :: Program -> String -- | Must be prepended to the program. [openClPrelude] :: Program -> String [openClKernelNames] :: Program -> [KernelName] -- | So we can detect whether the device is capable. [openClUsedTypes] :: Program -> [PrimType] -- | Runtime-configurable constants. [openClSizes] :: Program -> Map VName (SizeClass, Name) [hostFunctions] :: Program -> Functions OpenCL -- | A function calling OpenCL kernels. type Function = Function OpenCL -- | A imperative function, containing the body as well as its low-level -- inputs and outputs, as well as its high-level arguments and results. -- The latter are only used if the function is an entry point. data FunctionT a Function :: Bool -> [Param] -> [Param] -> Code a -> [ExternalValue] -> [ExternalValue] -> FunctionT a -- | A piece of code calling OpenCL. type Code = Code OpenCL -- | The name of a kernel. type KernelName = String -- | An argument to be passed to a kernel. data KernelArg -- | Pass the value of this scalar expression as argument. ValueKArg :: Exp -> PrimType -> KernelArg -- | Pass this pointer as argument. MemKArg :: VName -> KernelArg -- | Create this much local memory per workgroup. SharedMemoryKArg :: Count Bytes -> KernelArg -- | Host-level OpenCL operation. data OpenCL LaunchKernel :: KernelName -> [KernelArg] -> [Exp] -> [Exp] -> OpenCL HostCode :: Code -> OpenCL GetSize :: VName -> VName -> OpenCL CmpSizeLe :: VName -> VName -> Exp -> OpenCL GetSizeMax :: VName -> SizeClass -> OpenCL -- | The block size when transposing. transposeBlockDim :: Num a => a -- | 8-bit signed integer type data Int8 -- | 16-bit signed integer type data Int16 -- | 32-bit signed integer type data Int32 -- | 64-bit signed integer type data Int64 -- | 8-bit unsigned integer type data Word8 -- | 16-bit unsigned integer type data Word16 -- | 32-bit unsigned integer type data Word32 -- | 64-bit unsigned integer type data Word64 -- | Prettyprint a value, wrapped to 80 characters. pretty :: Pretty a => a -> String -- | Conversion operators try to generalise the from t0 x to t1 -- instructions from LLVM. data ConvOp -- | Zero-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. ZExt :: IntType -> IntType -> ConvOp -- | Sign-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. SExt :: IntType -> IntType -> ConvOp -- | Convert value of the former floating-point type to the latter. If the -- new type is smaller, the result is a truncation. FPConv :: FloatType -> FloatType -> ConvOp -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). FPToUI :: FloatType -> IntType -> ConvOp -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). FPToSI :: FloatType -> IntType -> ConvOp -- | Convert an unsigned integer to a floating-point value. UIToFP :: IntType -> FloatType -> ConvOp -- | Convert a signed integer to a floating-point value. SIToFP :: IntType -> FloatType -> ConvOp -- | Convert an integer to a boolean value. Zero becomes false; anything -- else is true. IToB :: IntType -> ConvOp -- | Convert a boolean to an integer. True is converted to 1 and False to -- 0. BToI :: IntType -> ConvOp -- | Comparison operators are like BinOps, but they return -- PrimTypes. The somewhat ugly constructor names are straight out -- of LLVM. data CmpOp -- | All types equality. CmpEq :: PrimType -> CmpOp -- | Unsigned less than. CmpUlt :: IntType -> CmpOp -- | Unsigned less than or equal. CmpUle :: IntType -> CmpOp -- | Signed less than. CmpSlt :: IntType -> CmpOp -- | Signed less than or equal. CmpSle :: IntType -> CmpOp -- | Floating-point less than. FCmpLt :: FloatType -> CmpOp -- | Floating-point less than or equal. FCmpLe :: FloatType -> CmpOp -- | Boolean less than. CmpLlt :: CmpOp -- | Boolean less than or equal. CmpLle :: CmpOp -- | Binary operators. These correspond closely to the binary operators in -- LLVM. Most are parametrised by their expected input and output types. data BinOp -- | Integer addition. Add :: IntType -> BinOp -- | Floating-point addition. FAdd :: FloatType -> BinOp -- | Integer subtraction. Sub :: IntType -> BinOp -- | Floating-point subtraction. FSub :: FloatType -> BinOp -- | Integer multiplication. Mul :: IntType -> BinOp -- | Floating-point multiplication. FMul :: FloatType -> BinOp -- | Unsigned integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. UDiv :: IntType -> BinOp -- | Signed integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. SDiv :: IntType -> BinOp -- | Floating-point division. FDiv :: FloatType -> BinOp -- | Unsigned integer modulus; the countepart to UDiv. UMod :: IntType -> BinOp -- | Signed integer modulus; the countepart to SDiv. SMod :: IntType -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- sdiv instruction in LLVM. SQuot :: IntType -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- srem instruction in LLVM. SRem :: IntType -> BinOp -- | Returns the smallest of two signed integers. SMin :: IntType -> BinOp -- | Returns the smallest of two unsigned integers. UMin :: IntType -> BinOp -- | Returns the smallest of two floating-point numbers. FMin :: FloatType -> BinOp -- | Returns the greatest of two signed integers. SMax :: IntType -> BinOp -- | Returns the greatest of two unsigned integers. UMax :: IntType -> BinOp -- | Returns the greatest of two floating-point numbers. FMax :: FloatType -> BinOp -- | Left-shift. Shl :: IntType -> BinOp -- | Logical right-shift, zero-extended. LShr :: IntType -> BinOp -- | Arithmetic right-shift, sign-extended. AShr :: IntType -> BinOp -- | Bitwise and. And :: IntType -> BinOp -- | Bitwise or. Or :: IntType -> BinOp -- | Bitwise exclusive-or. Xor :: IntType -> BinOp -- | Integer exponentiation. Pow :: IntType -> BinOp -- | Floating-point exponentiation. FPow :: FloatType -> BinOp -- | Boolean and - not short-circuiting. LogAnd :: BinOp -- | Boolean or - not short-circuiting. LogOr :: BinOp -- | Various unary operators. It is a bit ad-hoc what is a unary operator -- and what is a built-in function. Perhaps these should all go away -- eventually. data UnOp -- | E.g., ! True == False. Not :: UnOp -- | E.g., ~(~1) = 1. Complement :: IntType -> UnOp -- | abs(-2) = 2. Abs :: IntType -> UnOp -- | fabs(-2.0) = 2.0. FAbs :: FloatType -> UnOp -- | Signed sign function: ssignum(-2) = -1. SSignum :: IntType -> UnOp -- | Unsigned sign function: usignum(2) = 1. USignum :: IntType -> UnOp -- | Non-array values. data PrimValue IntValue :: !IntValue -> PrimValue FloatValue :: !FloatValue -> PrimValue BoolValue :: !Bool -> PrimValue -- | The only value of type cert. Checked :: PrimValue -- | A floating-point value. data FloatValue Float32Value :: !Float -> FloatValue Float64Value :: !Double -> FloatValue -- | An integer value. data IntValue Int8Value :: !Int8 -> IntValue Int16Value :: !Int16 -> IntValue Int32Value :: !Int32 -> IntValue Int64Value :: !Int64 -> IntValue -- | Low-level primitive types. data PrimType IntType :: IntType -> PrimType FloatType :: FloatType -> PrimType Bool :: PrimType Cert :: PrimType -- | A floating point type. data FloatType Float32 :: FloatType Float64 :: FloatType -- | An integer type, ordered by size. Note that signedness is not a -- property of the type, but a property of the operations performed on -- values of these types. data IntType Int8 :: IntType Int16 :: IntType Int32 :: IntType Int64 :: IntType -- | A list of all integer types. allIntTypes :: [IntType] -- | A list of all floating-point types. allFloatTypes :: [FloatType] -- | A list of all primitive types. allPrimTypes :: [PrimType] -- | Create an IntValue from a type and an Integer. intValue :: Integral int => IntType -> int -> IntValue intValueType :: IntValue -> IntType -- | Convert an IntValue to any Integral type. valueIntegral :: Integral int => IntValue -> int -- | Create a FloatValue from a type and a Rational. floatValue :: Real num => FloatType -> num -> FloatValue floatValueType :: FloatValue -> FloatType -- | The type of a basic value. primValueType :: PrimValue -> PrimType -- | A "blank" value of the given primitive type - this is zero, or -- whatever is close to it. Don't depend on this value, but use it for -- e.g. creating arrays to be populated by do-loops. blankPrimValue :: PrimType -> PrimValue -- | A list of all unary operators for all types. allUnOps :: [UnOp] -- | A list of all binary operators for all types. allBinOps :: [BinOp] -- | A list of all comparison operators for all types. allCmpOps :: [CmpOp] -- | A list of all conversion operators for all types. allConvOps :: [ConvOp] doUnOp :: UnOp -> PrimValue -> Maybe PrimValue -- | E.g., ~(~1) = 1. doComplement :: IntValue -> IntValue -- | abs(-2) = 2. doAbs :: IntValue -> IntValue -- | abs(-2.0) = 2.0. doFAbs :: FloatValue -> FloatValue -- | ssignum(-2) = -1. doSSignum :: IntValue -> IntValue -- | usignum(-2) = -1. doUSignum :: IntValue -> IntValue doBinOp :: BinOp -> PrimValue -> PrimValue -> Maybe PrimValue -- | Integer addition. doAdd :: IntValue -> IntValue -> IntValue -- | Integer multiplication. doMul :: IntValue -> IntValue -> IntValue -- | Signed integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. doSDiv :: IntValue -> IntValue -> Maybe IntValue -- | Signed integer modulus; the countepart to SDiv. doSMod :: IntValue -> IntValue -> Maybe IntValue -- | Signed integer exponentatation. doPow :: IntValue -> IntValue -> Maybe IntValue doConvOp :: ConvOp -> PrimValue -> Maybe PrimValue -- | Zero-extend the given integer value to the size of the given type. If -- the type is smaller than the given value, the result is a truncation. doZExt :: IntValue -> IntType -> IntValue -- | Sign-extend the given integer value to the size of the given type. If -- the type is smaller than the given value, the result is a truncation. doSExt :: IntValue -> IntType -> IntValue -- | Convert the former floating-point type to the latter. doFPConv :: FloatValue -> FloatType -> FloatValue -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). doFPToUI :: FloatValue -> IntType -> IntValue -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). doFPToSI :: FloatValue -> IntType -> IntValue -- | Convert an unsigned integer to a floating-point value. doUIToFP :: IntValue -> FloatType -> FloatValue -- | Convert a signed integer to a floating-point value. doSIToFP :: IntValue -> FloatType -> FloatValue doCmpOp :: CmpOp -> PrimValue -> PrimValue -> Maybe Bool -- | Compare any two primtive values for exact equality. doCmpEq :: PrimValue -> PrimValue -> Bool -- | Unsigned less than. doCmpUlt :: IntValue -> IntValue -> Bool -- | Unsigned less than or equal. doCmpUle :: IntValue -> IntValue -> Bool -- | Signed less than. doCmpSlt :: IntValue -> IntValue -> Bool -- | Signed less than or equal. doCmpSle :: IntValue -> IntValue -> Bool -- | Floating-point less than. doFCmpLt :: FloatValue -> FloatValue -> Bool -- | Floating-point less than or equal. doFCmpLe :: FloatValue -> FloatValue -> Bool -- | Translate an IntValue to Word64. This is guaranteed to -- fit. intToWord64 :: IntValue -> Word64 -- | Translate an IntValue to IntType. This is guaranteed to -- fit. intToInt64 :: IntValue -> Int64 -- | The result type of a binary operator. binOpType :: BinOp -> PrimType -- | The operand types of a comparison operator. cmpOpType :: CmpOp -> PrimType -- | The operand and result type of a unary operator. unOpType :: UnOp -> PrimType -- | The input and output types of a conversion operator. convOpType :: ConvOp -> (PrimType, PrimType) -- | A mapping from names of primitive functions to their parameter types, -- their result type, and a function for evaluating them. primFuns :: Map String ([PrimType], PrimType, [PrimValue] -> Maybe PrimValue) -- | Is the given value kind of zero? zeroIsh :: PrimValue -> Bool -- | Is the given value kind of one? oneIsh :: PrimValue -> Bool -- | Is the given value kind of negative? negativeIsh :: PrimValue -> Bool -- | The size of a value of a given primitive type in bites. primBitSize :: PrimType -> Int -- | The size of a value of a given primitive type in eight-bit bytes. primByteSize :: Num a => PrimType -> a -- | True if the given binary operator is commutative. commutativeBinOp :: BinOp -> Bool convOpFun :: ConvOp -> String -- | True if signed. Only makes a difference for integer types. prettySigned :: Bool -> PrimType -> String -- | A name tagged with some integer. Only the integer is used in -- comparisons, no matter the type of vn. data VName VName :: !Name -> !Int -> VName -- | The abstract (not really) type representing names in the Futhark -- compiler. Strings, being lists of characters, are very slow, -- while Texts are based on byte-arrays. data Name -- | Whether some operator is commutative or not. The Monoid -- instance returns the least commutative of its arguments. data Commutativity Noncommutative :: Commutativity Commutative :: Commutativity data StreamOrd InOrder :: StreamOrd Disorder :: StreamOrd -- | The uniqueness attribute of a type. This essentially indicates whether -- or not in-place modifications are acceptable. With respect to -- ordering, Unique is greater than Nonunique. data Uniqueness -- | May have references outside current function. Nonunique :: Uniqueness -- | No references outside current function. Unique :: Uniqueness -- | The name of the default program entry point (main). defaultEntryPoint :: Name -- | Convert a name to the corresponding list of characters. nameToString :: Name -> String -- | Convert a list of characters to the corresponding name. nameFromString :: String -> Name -- | Convert a name to the corresponding Text. nameToText :: Name -> Text -- | Convert a Text to the corresponding name. nameFromText :: Text -> Name -- | A human-readable location string, of the form -- filename:lineno:columnno. locStr :: SrcLoc -> String -- | Return the tag contained in the VName. baseTag :: VName -> Int -- | Return the name contained in the VName. baseName :: VName -> Name -- | Return the base Name converted to a string. baseString :: VName -> String -- | A part of an error message. data ErrorMsgPart a -- | A literal string. ErrorString :: String -> ErrorMsgPart a -- | A run-time integer value. ErrorInt32 :: a -> ErrorMsgPart a -- | An error message is a list of error parts, which are concatenated to -- form the final message. newtype ErrorMsg a ErrorMsg :: [ErrorMsgPart a] -> ErrorMsg a -- | A string representing a specific non-default memory space. type SpaceId = String -- | The memory space of a block. If DefaultSpace, this is the -- "default" space, whatever that is. The exact meaning of the -- SpaceID depends on the backend used. In GPU kernels, for -- example, this is used to distinguish between constant, global and -- shared memory spaces. In GPU-enabled host code, it is used to -- distinguish between host memory (DefaultSpace) and GPU space. data Space DefaultSpace :: Space Space :: SpaceId -> Space -- | A primitive expression parametrised over the representation of free -- variables. data PrimExp v LeafExp :: v -> PrimType -> PrimExp v ValueExp :: PrimValue -> PrimExp v BinOpExp :: BinOp -> PrimExp v -> PrimExp v -> PrimExp v CmpOpExp :: CmpOp -> PrimExp v -> PrimExp v -> PrimExp v UnOpExp :: UnOp -> PrimExp v -> PrimExp v ConvOpExp :: ConvOp -> PrimExp v -> PrimExp v FunExp :: String -> [PrimExp v] -> PrimType -> PrimExp v -- | Evaluate a PrimExp in the given monad. Invokes fail on -- type errors. evalPrimExp :: (Pretty v, Monad m) => (v -> m PrimValue) -> PrimExp v -> m PrimValue -- | The type of values returned by a PrimExp. This function -- returning does not imply that the PrimExp is type-correct. primExpType :: PrimExp v -> PrimType -- | If the given PrimExp is a constant of the wrong integer type, -- coerce it to the given integer type. This is a workaround for an issue -- in the Num instance. coerceIntPrimExp :: IntType -> PrimExp v -> PrimExp v -- | Phantom type for a count of bytes. data Bytes -- | Phantom type for a count of elements. data Elements -- | A wrapper around Exp that maintains a unit as a phantom type. newtype Count u Count :: Exp -> Count u [innerExp] :: Count u -> Exp -- | A function call argument. data Arg ExpArg :: Exp -> Arg MemArg :: VName -> Arg type Exp = PrimExp ExpLeaf data ExpLeaf ScalarVar :: VName -> ExpLeaf SizeOf :: PrimType -> ExpLeaf Index :: VName -> Count Bytes -> PrimType -> Space -> Volatility -> ExpLeaf -- | The volatility of a memory access. data Volatility Volatile :: Volatility Nonvolatile :: Volatility -- | Has the same semantics as the contained code, but the comment should -- show up in generated code for ease of inspection. -- | Indicate that some memory block will never again be referenced via the -- indicated variable. However, it may still be accessed through aliases. -- It is only safe to actually deallocate the memory block if this is the -- last reference. There is no guarantee that all memory blocks will be -- freed with this statement. Backends are free to ignore it entirely. -- | Memory space must match the corresponding DeclareMem. -- | Destination, offset in destination, destination space, source, offset -- in source, offset space, number of bytes. -- | Create a read-only array containing the given values. -- | Must be in same space. -- | Print the given value (of the given type) to the screen, somehow -- annotated with the given string as a description. This has no semantic -- meaning, but is used entirely for debugging. Code generators are free -- to ignore this statement. -- | A imperative function, containing the body as well as its low-level -- inputs and outputs, as well as its high-level arguments and results. -- The latter are only used if the function is an entry point. data FunctionT a -- | ^ An externally visible value. This can be an opaque value (covering -- several physical internal values), or a single value that can be used -- externally. data ExternalValue -- | The string is a human-readable description with no other semantics. OpaqueValue :: String -> [ValueDesc] -> ExternalValue TransparentValue :: ValueDesc -> ExternalValue -- | A description of an externally meaningful value. data ValueDesc -- | An array with memory block, memory block size, memory space, element -- type, signedness of element type (if applicable), and shape. ArrayValue :: VName -> MemSize -> Space -> PrimType -> Signedness -> [DimSize] -> ValueDesc -- | A scalar value with signedness if applicable. ScalarValue :: PrimType -> Signedness -> VName -> ValueDesc data Signedness TypeUnsigned :: Signedness TypeDirect :: Signedness -- | A collection of imperative functions. newtype Functions a Functions :: [(Name, Function a)] -> Functions a data Param MemParam :: VName -> Space -> Param ScalarParam :: VName -> PrimType -> Param data Type Scalar :: PrimType -> Type Mem :: MemSize -> Space -> Type type DimSize = Size type MemSize = Size data Size ConstSize :: Int64 -> Size VarSize :: VName -> Size paramName :: Param -> VName elements :: Exp -> Count Elements bytes :: Exp -> Count Bytes -- | Convert a count of elements into a count of bytes, given the -- per-element size. withElemType :: Count Elements -> PrimType -> Count Bytes dimSizeToExp :: DimSize -> Count Elements memSizeToExp :: MemSize -> Count Bytes sizeToExp :: Size -> Exp var :: VName -> PrimType -> Exp index :: VName -> Count Bytes -> PrimType -> Space -> Volatility -> Exp instance GHC.Show.Show Futhark.CodeGen.ImpCode.OpenCL.OpenCL instance GHC.Show.Show Futhark.CodeGen.ImpCode.OpenCL.KernelArg instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.OpenCL.OpenCL -- | Variation of Futhark.CodeGen.ImpCode that contains the notion -- of a kernel invocation. module Futhark.CodeGen.ImpCode.Kernels type Program = Functions HostOp type Function = Function HostOp -- | A imperative function, containing the body as well as its low-level -- inputs and outputs, as well as its high-level arguments and results. -- The latter are only used if the function is an entry point. data FunctionT a Function :: Bool -> [Param] -> [Param] -> Code a -> [ExternalValue] -> [ExternalValue] -> FunctionT a -- | Host-level code that can call kernels. type Code = Code CallKernel -- | Code inside a kernel. type KernelCode = Code KernelOp -- | A run-time constant related to kernels. newtype KernelConst SizeConst :: VName -> KernelConst -- | An expression whose variables are kernel constants. type KernelConstExp = PrimExp KernelConst data HostOp CallKernel :: CallKernel -> HostOp GetSize :: VName -> VName -> SizeClass -> HostOp CmpSizeLe :: VName -> VName -> SizeClass -> Exp -> HostOp GetSizeMax :: VName -> SizeClass -> HostOp data KernelOp GetGroupId :: VName -> Int -> KernelOp GetLocalId :: VName -> Int -> KernelOp GetLocalSize :: VName -> Int -> KernelOp GetGlobalSize :: VName -> Int -> KernelOp GetGlobalId :: VName -> Int -> KernelOp GetLockstepWidth :: VName -> KernelOp Atomic :: AtomicOp -> KernelOp Barrier :: KernelOp MemFence :: KernelOp data AtomicOp AtomicAdd :: VName -> VName -> Count Bytes -> Exp -> AtomicOp AtomicSMax :: VName -> VName -> Count Bytes -> Exp -> AtomicOp AtomicSMin :: VName -> VName -> Count Bytes -> Exp -> AtomicOp AtomicUMax :: VName -> VName -> Count Bytes -> Exp -> AtomicOp AtomicUMin :: VName -> VName -> Count Bytes -> Exp -> AtomicOp AtomicAnd :: VName -> VName -> Count Bytes -> Exp -> AtomicOp AtomicOr :: VName -> VName -> Count Bytes -> Exp -> AtomicOp AtomicXor :: VName -> VName -> Count Bytes -> Exp -> AtomicOp AtomicCmpXchg :: VName -> VName -> Count Bytes -> Exp -> Exp -> AtomicOp AtomicXchg :: VName -> VName -> Count Bytes -> Exp -> AtomicOp data CallKernel Map :: MapKernel -> CallKernel AnyKernel :: Kernel -> CallKernel MapTranspose :: PrimType -> VName -> Exp -> VName -> Exp -> Exp -> Exp -> Exp -> Exp -> Exp -> CallKernel -- | A generic kernel containing arbitrary kernel code. data MapKernel MapKernel :: VName -> String -> Code KernelOp -> [KernelUse] -> DimSize -> DimSize -> Exp -> MapKernel -- | Stm position - also serves as a unique name for the kernel. [mapKernelThreadNum] :: MapKernel -> VName -- | Used to name the kernel for readability. [mapKernelDesc] :: MapKernel -> String [mapKernelBody] :: MapKernel -> Code KernelOp [mapKernelUses] :: MapKernel -> [KernelUse] [mapKernelNumGroups] :: MapKernel -> DimSize [mapKernelGroupSize] :: MapKernel -> DimSize -- | Do not actually execute threads past this. [mapKernelSize] :: MapKernel -> Exp -- | In-kernel name and per-workgroup size in bytes. data Kernel Kernel :: Code KernelOp -> [LocalMemoryUse] -> [KernelUse] -> DimSize -> DimSize -> VName -> String -> Kernel [kernelBody] :: Kernel -> Code KernelOp -- | The local memory used by this kernel. [kernelLocalMemory] :: Kernel -> [LocalMemoryUse] -- | The host variables referenced by the kernel. [kernelUses] :: Kernel -> [KernelUse] [kernelNumGroups] :: Kernel -> DimSize [kernelGroupSize] :: Kernel -> DimSize -- | Unique name for the kernel. [kernelName] :: Kernel -> VName -- | A short descriptive name - should be alphanumeric and without spaces. [kernelDesc] :: Kernel -> String type LocalMemoryUse = (VName, Either MemSize KernelConstExp) data KernelUse ScalarUse :: VName -> PrimType -> KernelUse MemoryUse :: VName -> DimSize -> KernelUse ConstUse :: VName -> KernelConstExp -> KernelUse -- | 8-bit signed integer type data Int8 -- | 16-bit signed integer type data Int16 -- | 32-bit signed integer type data Int32 -- | 64-bit signed integer type data Int64 -- | 8-bit unsigned integer type data Word8 -- | 16-bit unsigned integer type data Word16 -- | 32-bit unsigned integer type data Word32 -- | 64-bit unsigned integer type data Word64 -- | Prettyprint a value, wrapped to 80 characters. pretty :: Pretty a => a -> String -- | Conversion operators try to generalise the from t0 x to t1 -- instructions from LLVM. data ConvOp -- | Zero-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. ZExt :: IntType -> IntType -> ConvOp -- | Sign-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. SExt :: IntType -> IntType -> ConvOp -- | Convert value of the former floating-point type to the latter. If the -- new type is smaller, the result is a truncation. FPConv :: FloatType -> FloatType -> ConvOp -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). FPToUI :: FloatType -> IntType -> ConvOp -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). FPToSI :: FloatType -> IntType -> ConvOp -- | Convert an unsigned integer to a floating-point value. UIToFP :: IntType -> FloatType -> ConvOp -- | Convert a signed integer to a floating-point value. SIToFP :: IntType -> FloatType -> ConvOp -- | Convert an integer to a boolean value. Zero becomes false; anything -- else is true. IToB :: IntType -> ConvOp -- | Convert a boolean to an integer. True is converted to 1 and False to -- 0. BToI :: IntType -> ConvOp -- | Comparison operators are like BinOps, but they return -- PrimTypes. The somewhat ugly constructor names are straight out -- of LLVM. data CmpOp -- | All types equality. CmpEq :: PrimType -> CmpOp -- | Unsigned less than. CmpUlt :: IntType -> CmpOp -- | Unsigned less than or equal. CmpUle :: IntType -> CmpOp -- | Signed less than. CmpSlt :: IntType -> CmpOp -- | Signed less than or equal. CmpSle :: IntType -> CmpOp -- | Floating-point less than. FCmpLt :: FloatType -> CmpOp -- | Floating-point less than or equal. FCmpLe :: FloatType -> CmpOp -- | Boolean less than. CmpLlt :: CmpOp -- | Boolean less than or equal. CmpLle :: CmpOp -- | Binary operators. These correspond closely to the binary operators in -- LLVM. Most are parametrised by their expected input and output types. data BinOp -- | Integer addition. Add :: IntType -> BinOp -- | Floating-point addition. FAdd :: FloatType -> BinOp -- | Integer subtraction. Sub :: IntType -> BinOp -- | Floating-point subtraction. FSub :: FloatType -> BinOp -- | Integer multiplication. Mul :: IntType -> BinOp -- | Floating-point multiplication. FMul :: FloatType -> BinOp -- | Unsigned integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. UDiv :: IntType -> BinOp -- | Signed integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. SDiv :: IntType -> BinOp -- | Floating-point division. FDiv :: FloatType -> BinOp -- | Unsigned integer modulus; the countepart to UDiv. UMod :: IntType -> BinOp -- | Signed integer modulus; the countepart to SDiv. SMod :: IntType -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- sdiv instruction in LLVM. SQuot :: IntType -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- srem instruction in LLVM. SRem :: IntType -> BinOp -- | Returns the smallest of two signed integers. SMin :: IntType -> BinOp -- | Returns the smallest of two unsigned integers. UMin :: IntType -> BinOp -- | Returns the smallest of two floating-point numbers. FMin :: FloatType -> BinOp -- | Returns the greatest of two signed integers. SMax :: IntType -> BinOp -- | Returns the greatest of two unsigned integers. UMax :: IntType -> BinOp -- | Returns the greatest of two floating-point numbers. FMax :: FloatType -> BinOp -- | Left-shift. Shl :: IntType -> BinOp -- | Logical right-shift, zero-extended. LShr :: IntType -> BinOp -- | Arithmetic right-shift, sign-extended. AShr :: IntType -> BinOp -- | Bitwise and. And :: IntType -> BinOp -- | Bitwise or. Or :: IntType -> BinOp -- | Bitwise exclusive-or. Xor :: IntType -> BinOp -- | Integer exponentiation. Pow :: IntType -> BinOp -- | Floating-point exponentiation. FPow :: FloatType -> BinOp -- | Boolean and - not short-circuiting. LogAnd :: BinOp -- | Boolean or - not short-circuiting. LogOr :: BinOp -- | Various unary operators. It is a bit ad-hoc what is a unary operator -- and what is a built-in function. Perhaps these should all go away -- eventually. data UnOp -- | E.g., ! True == False. Not :: UnOp -- | E.g., ~(~1) = 1. Complement :: IntType -> UnOp -- | abs(-2) = 2. Abs :: IntType -> UnOp -- | fabs(-2.0) = 2.0. FAbs :: FloatType -> UnOp -- | Signed sign function: ssignum(-2) = -1. SSignum :: IntType -> UnOp -- | Unsigned sign function: usignum(2) = 1. USignum :: IntType -> UnOp -- | Non-array values. data PrimValue IntValue :: !IntValue -> PrimValue FloatValue :: !FloatValue -> PrimValue BoolValue :: !Bool -> PrimValue -- | The only value of type cert. Checked :: PrimValue -- | A floating-point value. data FloatValue Float32Value :: !Float -> FloatValue Float64Value :: !Double -> FloatValue -- | An integer value. data IntValue Int8Value :: !Int8 -> IntValue Int16Value :: !Int16 -> IntValue Int32Value :: !Int32 -> IntValue Int64Value :: !Int64 -> IntValue -- | Low-level primitive types. data PrimType IntType :: IntType -> PrimType FloatType :: FloatType -> PrimType Bool :: PrimType Cert :: PrimType -- | A floating point type. data FloatType Float32 :: FloatType Float64 :: FloatType -- | An integer type, ordered by size. Note that signedness is not a -- property of the type, but a property of the operations performed on -- values of these types. data IntType Int8 :: IntType Int16 :: IntType Int32 :: IntType Int64 :: IntType -- | A list of all integer types. allIntTypes :: [IntType] -- | A list of all floating-point types. allFloatTypes :: [FloatType] -- | A list of all primitive types. allPrimTypes :: [PrimType] -- | Create an IntValue from a type and an Integer. intValue :: Integral int => IntType -> int -> IntValue intValueType :: IntValue -> IntType -- | Convert an IntValue to any Integral type. valueIntegral :: Integral int => IntValue -> int -- | Create a FloatValue from a type and a Rational. floatValue :: Real num => FloatType -> num -> FloatValue floatValueType :: FloatValue -> FloatType -- | The type of a basic value. primValueType :: PrimValue -> PrimType -- | A "blank" value of the given primitive type - this is zero, or -- whatever is close to it. Don't depend on this value, but use it for -- e.g. creating arrays to be populated by do-loops. blankPrimValue :: PrimType -> PrimValue -- | A list of all unary operators for all types. allUnOps :: [UnOp] -- | A list of all binary operators for all types. allBinOps :: [BinOp] -- | A list of all comparison operators for all types. allCmpOps :: [CmpOp] -- | A list of all conversion operators for all types. allConvOps :: [ConvOp] doUnOp :: UnOp -> PrimValue -> Maybe PrimValue -- | E.g., ~(~1) = 1. doComplement :: IntValue -> IntValue -- | abs(-2) = 2. doAbs :: IntValue -> IntValue -- | abs(-2.0) = 2.0. doFAbs :: FloatValue -> FloatValue -- | ssignum(-2) = -1. doSSignum :: IntValue -> IntValue -- | usignum(-2) = -1. doUSignum :: IntValue -> IntValue doBinOp :: BinOp -> PrimValue -> PrimValue -> Maybe PrimValue -- | Integer addition. doAdd :: IntValue -> IntValue -> IntValue -- | Integer multiplication. doMul :: IntValue -> IntValue -> IntValue -- | Signed integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. doSDiv :: IntValue -> IntValue -> Maybe IntValue -- | Signed integer modulus; the countepart to SDiv. doSMod :: IntValue -> IntValue -> Maybe IntValue -- | Signed integer exponentatation. doPow :: IntValue -> IntValue -> Maybe IntValue doConvOp :: ConvOp -> PrimValue -> Maybe PrimValue -- | Zero-extend the given integer value to the size of the given type. If -- the type is smaller than the given value, the result is a truncation. doZExt :: IntValue -> IntType -> IntValue -- | Sign-extend the given integer value to the size of the given type. If -- the type is smaller than the given value, the result is a truncation. doSExt :: IntValue -> IntType -> IntValue -- | Convert the former floating-point type to the latter. doFPConv :: FloatValue -> FloatType -> FloatValue -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). doFPToUI :: FloatValue -> IntType -> IntValue -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). doFPToSI :: FloatValue -> IntType -> IntValue -- | Convert an unsigned integer to a floating-point value. doUIToFP :: IntValue -> FloatType -> FloatValue -- | Convert a signed integer to a floating-point value. doSIToFP :: IntValue -> FloatType -> FloatValue doCmpOp :: CmpOp -> PrimValue -> PrimValue -> Maybe Bool -- | Compare any two primtive values for exact equality. doCmpEq :: PrimValue -> PrimValue -> Bool -- | Unsigned less than. doCmpUlt :: IntValue -> IntValue -> Bool -- | Unsigned less than or equal. doCmpUle :: IntValue -> IntValue -> Bool -- | Signed less than. doCmpSlt :: IntValue -> IntValue -> Bool -- | Signed less than or equal. doCmpSle :: IntValue -> IntValue -> Bool -- | Floating-point less than. doFCmpLt :: FloatValue -> FloatValue -> Bool -- | Floating-point less than or equal. doFCmpLe :: FloatValue -> FloatValue -> Bool -- | Translate an IntValue to Word64. This is guaranteed to -- fit. intToWord64 :: IntValue -> Word64 -- | Translate an IntValue to IntType. This is guaranteed to -- fit. intToInt64 :: IntValue -> Int64 -- | The result type of a binary operator. binOpType :: BinOp -> PrimType -- | The operand types of a comparison operator. cmpOpType :: CmpOp -> PrimType -- | The operand and result type of a unary operator. unOpType :: UnOp -> PrimType -- | The input and output types of a conversion operator. convOpType :: ConvOp -> (PrimType, PrimType) -- | A mapping from names of primitive functions to their parameter types, -- their result type, and a function for evaluating them. primFuns :: Map String ([PrimType], PrimType, [PrimValue] -> Maybe PrimValue) -- | Is the given value kind of zero? zeroIsh :: PrimValue -> Bool -- | Is the given value kind of one? oneIsh :: PrimValue -> Bool -- | Is the given value kind of negative? negativeIsh :: PrimValue -> Bool -- | The size of a value of a given primitive type in bites. primBitSize :: PrimType -> Int -- | The size of a value of a given primitive type in eight-bit bytes. primByteSize :: Num a => PrimType -> a -- | True if the given binary operator is commutative. commutativeBinOp :: BinOp -> Bool convOpFun :: ConvOp -> String -- | True if signed. Only makes a difference for integer types. prettySigned :: Bool -> PrimType -> String -- | A name tagged with some integer. Only the integer is used in -- comparisons, no matter the type of vn. data VName VName :: !Name -> !Int -> VName -- | The abstract (not really) type representing names in the Futhark -- compiler. Strings, being lists of characters, are very slow, -- while Texts are based on byte-arrays. data Name -- | Whether some operator is commutative or not. The Monoid -- instance returns the least commutative of its arguments. data Commutativity Noncommutative :: Commutativity Commutative :: Commutativity data StreamOrd InOrder :: StreamOrd Disorder :: StreamOrd -- | The uniqueness attribute of a type. This essentially indicates whether -- or not in-place modifications are acceptable. With respect to -- ordering, Unique is greater than Nonunique. data Uniqueness -- | May have references outside current function. Nonunique :: Uniqueness -- | No references outside current function. Unique :: Uniqueness -- | The name of the default program entry point (main). defaultEntryPoint :: Name -- | Convert a name to the corresponding list of characters. nameToString :: Name -> String -- | Convert a list of characters to the corresponding name. nameFromString :: String -> Name -- | Convert a name to the corresponding Text. nameToText :: Name -> Text -- | Convert a Text to the corresponding name. nameFromText :: Text -> Name -- | A human-readable location string, of the form -- filename:lineno:columnno. locStr :: SrcLoc -> String -- | Return the tag contained in the VName. baseTag :: VName -> Int -- | Return the name contained in the VName. baseName :: VName -> Name -- | Return the base Name converted to a string. baseString :: VName -> String -- | A part of an error message. data ErrorMsgPart a -- | A literal string. ErrorString :: String -> ErrorMsgPart a -- | A run-time integer value. ErrorInt32 :: a -> ErrorMsgPart a -- | An error message is a list of error parts, which are concatenated to -- form the final message. newtype ErrorMsg a ErrorMsg :: [ErrorMsgPart a] -> ErrorMsg a -- | A string representing a specific non-default memory space. type SpaceId = String -- | The memory space of a block. If DefaultSpace, this is the -- "default" space, whatever that is. The exact meaning of the -- SpaceID depends on the backend used. In GPU kernels, for -- example, this is used to distinguish between constant, global and -- shared memory spaces. In GPU-enabled host code, it is used to -- distinguish between host memory (DefaultSpace) and GPU space. data Space DefaultSpace :: Space Space :: SpaceId -> Space -- | A primitive expression parametrised over the representation of free -- variables. data PrimExp v LeafExp :: v -> PrimType -> PrimExp v ValueExp :: PrimValue -> PrimExp v BinOpExp :: BinOp -> PrimExp v -> PrimExp v -> PrimExp v CmpOpExp :: CmpOp -> PrimExp v -> PrimExp v -> PrimExp v UnOpExp :: UnOp -> PrimExp v -> PrimExp v ConvOpExp :: ConvOp -> PrimExp v -> PrimExp v FunExp :: String -> [PrimExp v] -> PrimType -> PrimExp v -- | Evaluate a PrimExp in the given monad. Invokes fail on -- type errors. evalPrimExp :: (Pretty v, Monad m) => (v -> m PrimValue) -> PrimExp v -> m PrimValue -- | The type of values returned by a PrimExp. This function -- returning does not imply that the PrimExp is type-correct. primExpType :: PrimExp v -> PrimType -- | If the given PrimExp is a constant of the wrong integer type, -- coerce it to the given integer type. This is a workaround for an issue -- in the Num instance. coerceIntPrimExp :: IntType -> PrimExp v -> PrimExp v -- | Phantom type for a count of bytes. data Bytes -- | Phantom type for a count of elements. data Elements -- | A wrapper around Exp that maintains a unit as a phantom type. newtype Count u Count :: Exp -> Count u [innerExp] :: Count u -> Exp -- | A function call argument. data Arg ExpArg :: Exp -> Arg MemArg :: VName -> Arg type Exp = PrimExp ExpLeaf data ExpLeaf ScalarVar :: VName -> ExpLeaf SizeOf :: PrimType -> ExpLeaf Index :: VName -> Count Bytes -> PrimType -> Space -> Volatility -> ExpLeaf -- | The volatility of a memory access. data Volatility Volatile :: Volatility Nonvolatile :: Volatility -- | Has the same semantics as the contained code, but the comment should -- show up in generated code for ease of inspection. -- | Indicate that some memory block will never again be referenced via the -- indicated variable. However, it may still be accessed through aliases. -- It is only safe to actually deallocate the memory block if this is the -- last reference. There is no guarantee that all memory blocks will be -- freed with this statement. Backends are free to ignore it entirely. -- | Memory space must match the corresponding DeclareMem. -- | Destination, offset in destination, destination space, source, offset -- in source, offset space, number of bytes. -- | Create a read-only array containing the given values. -- | Must be in same space. -- | Print the given value (of the given type) to the screen, somehow -- annotated with the given string as a description. This has no semantic -- meaning, but is used entirely for debugging. Code generators are free -- to ignore this statement. -- | A imperative function, containing the body as well as its low-level -- inputs and outputs, as well as its high-level arguments and results. -- The latter are only used if the function is an entry point. data FunctionT a -- | ^ An externally visible value. This can be an opaque value (covering -- several physical internal values), or a single value that can be used -- externally. data ExternalValue -- | The string is a human-readable description with no other semantics. OpaqueValue :: String -> [ValueDesc] -> ExternalValue TransparentValue :: ValueDesc -> ExternalValue -- | A description of an externally meaningful value. data ValueDesc -- | An array with memory block, memory block size, memory space, element -- type, signedness of element type (if applicable), and shape. ArrayValue :: VName -> MemSize -> Space -> PrimType -> Signedness -> [DimSize] -> ValueDesc -- | A scalar value with signedness if applicable. ScalarValue :: PrimType -> Signedness -> VName -> ValueDesc data Signedness TypeUnsigned :: Signedness TypeDirect :: Signedness -- | A collection of imperative functions. newtype Functions a Functions :: [(Name, Function a)] -> Functions a data Param MemParam :: VName -> Space -> Param ScalarParam :: VName -> PrimType -> Param data Type Scalar :: PrimType -> Type Mem :: MemSize -> Space -> Type type DimSize = Size type MemSize = Size data Size ConstSize :: Int64 -> Size VarSize :: VName -> Size paramName :: Param -> VName elements :: Exp -> Count Elements bytes :: Exp -> Count Bytes -- | Convert a count of elements into a count of bytes, given the -- per-element size. withElemType :: Count Elements -> PrimType -> Count Bytes dimSizeToExp :: DimSize -> Count Elements memSizeToExp :: MemSize -> Count Bytes sizeToExp :: Size -> Exp var :: VName -> PrimType -> Exp index :: VName -> Count Bytes -> PrimType -> Space -> Volatility -> Exp getKernels :: Program -> [CallKernel] instance GHC.Show.Show Futhark.CodeGen.ImpCode.Kernels.HostOp instance GHC.Show.Show Futhark.CodeGen.ImpCode.Kernels.CallKernel instance GHC.Show.Show Futhark.CodeGen.ImpCode.Kernels.MapKernel instance GHC.Show.Show Futhark.CodeGen.ImpCode.Kernels.Kernel instance GHC.Show.Show Futhark.CodeGen.ImpCode.Kernels.KernelOp instance GHC.Show.Show Futhark.CodeGen.ImpCode.Kernels.AtomicOp instance GHC.Show.Show Futhark.CodeGen.ImpCode.Kernels.KernelUse instance GHC.Classes.Eq Futhark.CodeGen.ImpCode.Kernels.KernelUse instance GHC.Show.Show Futhark.CodeGen.ImpCode.Kernels.KernelConst instance GHC.Classes.Ord Futhark.CodeGen.ImpCode.Kernels.KernelConst instance GHC.Classes.Eq Futhark.CodeGen.ImpCode.Kernels.KernelConst instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.Kernels.HostOp instance Futhark.Representation.AST.Attributes.Names.FreeIn Futhark.CodeGen.ImpCode.Kernels.HostOp instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.Kernels.CallKernel instance Futhark.Representation.AST.Attributes.Names.FreeIn Futhark.CodeGen.ImpCode.Kernels.CallKernel instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.Kernels.MapKernel instance Futhark.Representation.AST.Attributes.Names.FreeIn Futhark.CodeGen.ImpCode.Kernels.MapKernel instance Futhark.Representation.AST.Attributes.Names.FreeIn Futhark.CodeGen.ImpCode.Kernels.Kernel instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.Kernels.Kernel instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.Kernels.KernelOp instance Futhark.Representation.AST.Attributes.Names.FreeIn Futhark.CodeGen.ImpCode.Kernels.KernelOp instance Futhark.Representation.AST.Attributes.Names.FreeIn Futhark.CodeGen.ImpCode.Kernels.AtomicOp instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.Kernels.KernelUse instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.Kernels.KernelConst module Futhark.CodeGen.ImpGen.Kernels compileProg :: MonadFreshNames m => Prog ExplicitMemory -> m (Either InternalError Program) module Futhark.Actions printAction :: (Attributes lore, CanBeAliased (Op lore)) => Action lore impCodeGenAction :: Action ExplicitMemory kernelImpCodeGenAction :: Action ExplicitMemory rangeAction :: (Attributes lore, CanBeRanged (Op lore)) => Action lore metricsAction :: OpMetrics (Op lore) => Action lore -- | Simple C runtime representation. module Futhark.CodeGen.Backends.SimpleRepresentation -- | True if both types map to the same runtime representation. This is the -- case if they are identical modulo uniqueness. sameRepresentation :: [Type] -> [Type] -> Bool -- | tupleField i is the name of field number i in a -- tuple. tupleField :: Int -> String -- | tupleFieldExp e i is the expression for accesing field -- i of tuple e. If e is an lvalue, so will -- the resulting expression be. tupleFieldExp :: ToExp a => a -> Int -> Exp -- | funName f is the name of the C function corresponding to the -- Futhark function f. funName :: Name -> String -- | The type of memory blocks in the default memory space. defaultMemBlockType :: Type -- | The C type corresponding to a signed integer type. intTypeToCType :: IntType -> Type -- | The C type corresponding to a float type. floatTypeToCType :: FloatType -> Type -- | The C type corresponding to a primitive type. Integers are assumed to -- be unsigned. primTypeToCType :: PrimType -> Type -- | The C type corresponding to a primitive type. Integers are assumed to -- have the specified sign. signedPrimTypeToCType :: Signedness -> PrimType -> Type cIntOps :: [Definition] cFloat32Ops :: [Definition] cFloat32Funs :: [Definition] cFloat64Ops :: [Definition] cFloat64Funs :: [Definition] cFloatConvOps :: [Definition] -- | C code generator framework. module Futhark.CodeGen.Backends.GenericC -- | Compile imperative program to a C program. Always uses the function -- named "main" as entry point, so make sure it is defined. compileProg :: MonadFreshNames m => Operations op () -> CompilerM op () () -> String -> [Space] -> [Option] -> Functions op -> m CParts -- | The result of compilation to C is four parts, which can be put -- together in various ways. The obvious way is to concatenate all of -- them, which yields a CLI program. Another is to compile the library -- part by itself, and use the header file to call into it. data CParts CParts :: String -> String -> String -> String -> CParts [cHeader] :: CParts -> String -- | Utility definitions that must be visible to both CLI and library -- parts. [cUtils] :: CParts -> String [cCLI] :: CParts -> String [cLib] :: CParts -> String -- | Produce header and implementation files. asLibrary :: CParts -> (String, String) -- | As executable with command-line interface. asExecutable :: CParts -> String data Operations op s Operations :: WriteScalar op s -> ReadScalar op s -> Allocate op s -> Deallocate op s -> Copy op s -> StaticArray op s -> MemoryType op s -> OpCompiler op s -> Bool -> Operations op s [opsWriteScalar] :: Operations op s -> WriteScalar op s [opsReadScalar] :: Operations op s -> ReadScalar op s [opsAllocate] :: Operations op s -> Allocate op s [opsDeallocate] :: Operations op s -> Deallocate op s [opsCopy] :: Operations op s -> Copy op s [opsStaticArray] :: Operations op s -> StaticArray op s [opsMemoryType] :: Operations op s -> MemoryType op s [opsCompiler] :: Operations op s -> OpCompiler op s -- | If true, use reference counting. Otherwise, bare pointers. [opsFatMemory] :: Operations op s -> Bool -- | A set of operations that fail for every operation involving -- non-default memory spaces. Uses plain pointers and malloc for -- memory management. defaultOperations :: Operations op s -- | A substitute expression compiler, tried before the main compilation -- function. type OpCompiler op s = op -> CompilerM op s () -- | The address space qualifiers for a pointer of the given type with the -- given annotation. type PointerQuals op s = String -> CompilerM op s [TypeQual] -- | The type of a memory block in the given memory space. type MemoryType op s = SpaceId -> CompilerM op s Type -- | Write a scalar to the given memory block with the given index and in -- the given memory space. type WriteScalar op s = Exp -> Exp -> Type -> SpaceId -> Volatility -> Exp -> CompilerM op s () writeScalarPointerWithQuals :: PointerQuals op s -> WriteScalar op s -- | Read a scalar from the given memory block with the given index and in -- the given memory space. type ReadScalar op s = Exp -> Exp -> Type -> SpaceId -> Volatility -> CompilerM op s Exp readScalarPointerWithQuals :: PointerQuals op s -> ReadScalar op s -- | Allocate a memory block of the given size and with the given tag in -- the given memory space, saving a reference in the given variable name. type Allocate op s = Exp -> Exp -> Exp -> SpaceId -> CompilerM op s () -- | De-allocate the given memory block with the given tag, which is in the -- given memory space. type Deallocate op s = Exp -> Exp -> SpaceId -> CompilerM op s () -- | Copy from one memory block to another. type Copy op s = Exp -> Exp -> Space -> Exp -> Exp -> Space -> Exp -> CompilerM op s () -- | Create a static array of values - initialised at load time. type StaticArray op s = VName -> SpaceId -> PrimType -> [PrimValue] -> CompilerM op s () data CompilerM op s a data CompilerState s getUserState :: CompilerM op s s putUserState :: s -> CompilerM op s () modifyUserState :: (s -> s) -> CompilerM op s () contextContents :: CompilerM op s ([FieldGroup], [Stm]) contextFinalInits :: CompilerM op s [Stm] runCompilerM :: Functions op -> Operations op s -> VNameSource -> s -> CompilerM op s a -> (a, CompilerState s) blockScope :: CompilerM op s () -> CompilerM op s [BlockItem] compileFun :: (Name, Function op) -> CompilerM op s (Definition, Func) compileCode :: Code op -> CompilerM op s () compileExp :: Exp -> CompilerM op s Exp -- | Tell me how to compile a v, and I'll Compile any PrimExp -- v for you. compilePrimExp :: Monad m => (v -> m Exp) -> PrimExp v -> m Exp compilePrimValue :: PrimValue -> Exp compileExpToName :: String -> PrimType -> Exp -> CompilerM op s VName dimSizeToExp :: DimSize -> Exp rawMem :: ToExp a => a -> CompilerM op s Exp item :: BlockItem -> CompilerM op s () stm :: Stm -> CompilerM op s () stms :: [Stm] -> CompilerM op s () decl :: InitGroup -> CompilerM op s () atInit :: Stm -> CompilerM op s () headerDecl :: HeaderSection -> Definition -> CompilerM op s () -- | Construct a publicly visible definition using the specified name as -- the template. The first returned definition is put in the header file, -- and the second is the implementation. Returns the public name. publicDef :: String -> HeaderSection -> (String -> (Definition, Definition)) -> CompilerM op s String -- | As publicDef, but ignores the public name. publicDef_ :: String -> HeaderSection -> (String -> (Definition, Definition)) -> CompilerM op s () debugReport :: BlockItem -> CompilerM op s () -- | In which part of the header file we put the declaration. This is to -- ensure that the header file remains structured and readable. data HeaderSection ArrayDecl :: String -> HeaderSection OpaqueDecl :: String -> HeaderSection EntryDecl :: HeaderSection MiscDecl :: HeaderSection InitDecl :: HeaderSection libDecl :: Definition -> CompilerM op s () earlyDecls :: [Definition] -> CompilerM op s () -- | Public names must have a consitent prefix. publicName :: String -> CompilerM op s String -- | The generated code must define a struct with this name. contextType :: CompilerM op s Type contextField :: String -> Type -> Maybe Exp -> CompilerM op s () -- | The C type corresponding to a primitive type. Integers are assumed to -- be unsigned. primTypeToCType :: PrimType -> Type copyMemoryDefaultSpace :: Exp -> Exp -> Exp -> Exp -> Exp -> CompilerM op s () instance Control.Monad.Writer.Class.MonadWriter (Futhark.CodeGen.Backends.GenericC.CompilerAcc op s) (Futhark.CodeGen.Backends.GenericC.CompilerM op s) instance Control.Monad.Reader.Class.MonadReader (Futhark.CodeGen.Backends.GenericC.CompilerEnv op s) (Futhark.CodeGen.Backends.GenericC.CompilerM op s) instance Control.Monad.State.Class.MonadState (Futhark.CodeGen.Backends.GenericC.CompilerState s) (Futhark.CodeGen.Backends.GenericC.CompilerM op s) instance GHC.Base.Monad (Futhark.CodeGen.Backends.GenericC.CompilerM op s) instance GHC.Base.Applicative (Futhark.CodeGen.Backends.GenericC.CompilerM op s) instance GHC.Base.Functor (Futhark.CodeGen.Backends.GenericC.CompilerM op s) instance GHC.Classes.Ord Futhark.CodeGen.Backends.GenericC.HeaderSection instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericC.HeaderSection instance Futhark.MonadFreshNames.MonadFreshNames (Futhark.CodeGen.Backends.GenericC.CompilerM op s) instance GHC.Base.Semigroup (Futhark.CodeGen.Backends.GenericC.CompilerAcc op s) instance GHC.Base.Monoid (Futhark.CodeGen.Backends.GenericC.CompilerAcc op s) instance Language.C.Quote.Base.ToIdent Language.Futhark.Core.VName instance Language.C.Quote.Base.ToExp Language.Futhark.Core.VName instance Language.C.Quote.Base.ToExp Futhark.Representation.Primitive.IntValue instance Language.C.Quote.Base.ToExp Futhark.Representation.Primitive.FloatValue instance Language.C.Quote.Base.ToExp Futhark.Representation.Primitive.PrimValue -- | This module defines a translation from imperative code with kernels to -- imperative code with OpenCL calls. module Futhark.CodeGen.ImpGen.Kernels.ToOpenCL -- | Translate a kernels-program to an OpenCL-program. kernelsToOpenCL :: Program -> Either InternalError Program instance GHC.Base.Semigroup Futhark.CodeGen.ImpGen.Kernels.ToOpenCL.ToOpenCL instance GHC.Base.Monoid Futhark.CodeGen.ImpGen.Kernels.ToOpenCL.ToOpenCL instance GHC.Base.Semigroup Futhark.CodeGen.ImpGen.Kernels.ToOpenCL.OpenClRequirements instance GHC.Base.Monoid Futhark.CodeGen.ImpGen.Kernels.ToOpenCL.OpenClRequirements module Futhark.CodeGen.ImpGen.OpenCL compileProg :: MonadFreshNames m => Prog ExplicitMemory -> m (Either InternalError Program) -- | C code generator. This module can convert a correct ImpCode program to -- an equivalent C program. The C code is strictly sequential, but can -- handle the full Futhark language. module Futhark.CodeGen.Backends.SequentialC compileProg :: MonadFreshNames m => Prog ExplicitMemory -> m (Either InternalError CParts) -- | The result of compilation to C is four parts, which can be put -- together in various ways. The obvious way is to concatenate all of -- them, which yields a CLI program. Another is to compile the library -- part by itself, and use the header file to call into it. data CParts CParts :: String -> String -> String -> String -> CParts [cHeader] :: CParts -> String -- | Utility definitions that must be visible to both CLI and library -- parts. [cUtils] :: CParts -> String [cCLI] :: CParts -> String [cLib] :: CParts -> String -- | Produce header and implementation files. asLibrary :: CParts -> (String, String) -- | As executable with command-line interface. asExecutable :: CParts -> String module Futhark.CodeGen.Backends.COpenCL.Boilerplate generateBoilerplate :: String -> String -> [String] -> [PrimType] -> Map VName (SizeClass, Name) -> CompilerM OpenCL () () kernelRuntime :: String -> String kernelRuns :: String -> String module Futhark.CodeGen.Backends.COpenCL compileProg :: MonadFreshNames m => Prog ExplicitMemory -> m (Either InternalError CParts) -- | The result of compilation to C is four parts, which can be put -- together in various ways. The obvious way is to concatenate all of -- them, which yields a CLI program. Another is to compile the library -- part by itself, and use the header file to call into it. data CParts CParts :: String -> String -> String -> String -> CParts [cHeader] :: CParts -> String -- | Utility definitions that must be visible to both CLI and library -- parts. [cUtils] :: CParts -> String [cCLI] :: CParts -> String [cLib] :: CParts -> String -- | Produce header and implementation files. asLibrary :: CParts -> (String, String) -- | As executable with command-line interface. asExecutable :: CParts -> String module Futhark.CodeGen.Backends.GenericPython.AST data PyExp Integer :: Integer -> PyExp Bool :: Bool -> PyExp Float :: Double -> PyExp String :: String -> PyExp RawStringLiteral :: String -> PyExp Var :: String -> PyExp BinOp :: String -> PyExp -> PyExp -> PyExp UnOp :: String -> PyExp -> PyExp Cond :: PyExp -> PyExp -> PyExp -> PyExp Index :: PyExp -> PyIdx -> PyExp Call :: PyExp -> [PyArg] -> PyExp Cast :: PyExp -> String -> PyExp Tuple :: [PyExp] -> PyExp List :: [PyExp] -> PyExp Field :: PyExp -> String -> PyExp Dict :: [(PyExp, PyExp)] -> PyExp None :: PyExp data PyIdx IdxRange :: PyExp -> PyExp -> PyIdx IdxExp :: PyExp -> PyIdx data PyArg ArgKeyword :: String -> PyExp -> PyArg Arg :: PyExp -> PyArg data PyStmt If :: PyExp -> [PyStmt] -> [PyStmt] -> PyStmt Try :: [PyStmt] -> [PyExcept] -> PyStmt While :: PyExp -> [PyStmt] -> PyStmt For :: String -> PyExp -> [PyStmt] -> PyStmt With :: PyExp -> [PyStmt] -> PyStmt Assign :: PyExp -> PyExp -> PyStmt AssignOp :: String -> PyExp -> PyExp -> PyStmt Comment :: String -> [PyStmt] -> PyStmt Assert :: PyExp -> PyExp -> PyStmt Raise :: PyExp -> PyStmt Exp :: PyExp -> PyStmt Return :: PyExp -> PyStmt Pass :: PyStmt Import :: String -> Maybe String -> PyStmt FunDef :: PyFunDef -> PyStmt ClassDef :: PyClassDef -> PyStmt Escape :: String -> PyStmt newtype PyProg PyProg :: [PyStmt] -> PyProg data PyExcept Catch :: PyExp -> [PyStmt] -> PyExcept data PyFunDef Def :: String -> [String] -> [PyStmt] -> PyFunDef data PyClassDef Class :: String -> [PyStmt] -> PyClassDef instance GHC.Show.Show Futhark.CodeGen.Backends.GenericPython.AST.PyProg instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericPython.AST.PyProg instance GHC.Show.Show Futhark.CodeGen.Backends.GenericPython.AST.PyExcept instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericPython.AST.PyExcept instance GHC.Show.Show Futhark.CodeGen.Backends.GenericPython.AST.PyFunDef instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericPython.AST.PyFunDef instance GHC.Show.Show Futhark.CodeGen.Backends.GenericPython.AST.PyStmt instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericPython.AST.PyStmt instance GHC.Show.Show Futhark.CodeGen.Backends.GenericPython.AST.PyClassDef instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericPython.AST.PyClassDef instance GHC.Show.Show Futhark.CodeGen.Backends.GenericPython.AST.PyIdx instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericPython.AST.PyIdx instance GHC.Show.Show Futhark.CodeGen.Backends.GenericPython.AST.PyExp instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericPython.AST.PyExp instance GHC.Show.Show Futhark.CodeGen.Backends.GenericPython.AST.PyArg instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericPython.AST.PyArg instance GHC.Show.Show Futhark.CodeGen.Backends.GenericPython.AST.UnOp instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericPython.AST.UnOp instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericPython.AST.PyProg instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericPython.AST.PyStmt instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericPython.AST.PyFunDef instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericPython.AST.PyClassDef instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericPython.AST.PyExcept instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericPython.AST.PyIdx instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericPython.AST.PyArg instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericPython.AST.PyExp module Futhark.CodeGen.Backends.PyOpenCL.Boilerplate -- | Python code (as a string) that calls the -- initiatialize_opencl_object procedure. Should be put in the -- class constructor. openClInit :: [PrimType] -> String -> Map VName (SizeClass, Name) -> String -- | rtspythonopencl.py embedded as a string. openClPrelude :: String -- | This module defines a generator for getopt based command line -- argument parsing. Each option is associated with arbitrary Python code -- that will perform side effects, usually by setting some global -- variables. module Futhark.CodeGen.Backends.GenericPython.Options -- | Specification if a single command line option. The option must have a -- long name, and may also have a short name. -- -- When the statement is being executed, the argument (if any) will be -- stored in the variable optarg. data Option Option :: String -> Maybe Char -> OptionArgument -> [PyStmt] -> Option [optionLongName] :: Option -> String [optionShortName] :: Option -> Maybe Char [optionArgument] :: Option -> OptionArgument [optionAction] :: Option -> [PyStmt] -- | Whether an option accepts an argument. data OptionArgument NoArgument :: OptionArgument RequiredArgument :: OptionArgument OptionalArgument :: OptionArgument -- | Generate option parsing code that accepts the given command line -- options. Will read from sys.argv. -- -- If option parsing fails for any reason, the entire process will -- terminate with error code 1. generateOptionParser :: [Option] -> [PyStmt] -- | A generic Python code generator which is polymorphic in the type of -- the operations. Concretely, we use this to handle both sequential and -- PyOpenCL Python code. module Futhark.CodeGen.Backends.GenericPython compileProg :: MonadFreshNames m => Maybe String -> Constructor -> [PyStmt] -> [PyStmt] -> Operations op s -> s -> [PyStmt] -> [Option] -> Functions op -> m String -- | The class generated by the code generator must have a constructor, -- although it can be vacuous. data Constructor Constructor :: [String] -> [PyStmt] -> Constructor -- | A constructor that takes no arguments and does nothing. emptyConstructor :: Constructor compileName :: VName -> String compileDim :: DimSize -> PyExp compileExp :: Exp -> CompilerM op s PyExp compileCode :: Code op -> CompilerM op s () compilePrimValue :: PrimValue -> PyExp -- | The ctypes type corresponding to a PrimType. compilePrimType :: PrimType -> String -- | The ctypes type corresponding to a PrimType, taking sign into -- account. compilePrimTypeExt :: PrimType -> Signedness -> String -- | The Numpy type corresponding to a PrimType. compilePrimToNp :: PrimType -> String -- | The Numpy type corresponding to a PrimType, taking sign into -- account. compilePrimToExtNp :: PrimType -> Signedness -> String data Operations op s Operations :: WriteScalar op s -> ReadScalar op s -> Allocate op s -> Copy op s -> StaticArray op s -> OpCompiler op s -> EntryOutput op s -> EntryInput op s -> Operations op s [opsWriteScalar] :: Operations op s -> WriteScalar op s [opsReadScalar] :: Operations op s -> ReadScalar op s [opsAllocate] :: Operations op s -> Allocate op s [opsCopy] :: Operations op s -> Copy op s [opsStaticArray] :: Operations op s -> StaticArray op s [opsCompiler] :: Operations op s -> OpCompiler op s [opsEntryOutput] :: Operations op s -> EntryOutput op s [opsEntryInput] :: Operations op s -> EntryInput op s -- | A set of operations that fail for every operation involving -- non-default memory spaces. Uses plain pointers and malloc for -- memory management. defaultOperations :: Operations op s unpackDim :: PyExp -> DimSize -> Int32 -> CompilerM op s () newtype CompilerM op s a CompilerM :: RWS (CompilerEnv op s) [PyStmt] (CompilerState s) a -> CompilerM op s a -- | A substitute expression compiler, tried before the main compilation -- function. type OpCompiler op s = op -> CompilerM op s () -- | Write a scalar to the given memory block with the given index and in -- the given memory space. type WriteScalar op s = VName -> PyExp -> PrimType -> SpaceId -> PyExp -> CompilerM op s () -- | Read a scalar from the given memory block with the given index and in -- the given memory space. type ReadScalar op s = VName -> PyExp -> PrimType -> SpaceId -> CompilerM op s PyExp -- | Allocate a memory block of the given size in the given memory space, -- saving a reference in the given variable name. type Allocate op s = VName -> PyExp -> SpaceId -> CompilerM op s () -- | Copy from one memory block to another. type Copy op s = VName -> PyExp -> Space -> VName -> PyExp -> Space -> PyExp -> PrimType -> CompilerM op s () -- | Create a static array of values - initialised at load time. type StaticArray op s = VName -> SpaceId -> PrimType -> [PrimValue] -> CompilerM op s () -- | Construct the Python array being returned from an entry point. type EntryOutput op s = VName -> SpaceId -> PrimType -> Signedness -> [DimSize] -> CompilerM op s PyExp -- | Unpack the array being passed to an entry point. type EntryInput op s = VName -> MemSize -> SpaceId -> PrimType -> Signedness -> [DimSize] -> PyExp -> CompilerM op s () data CompilerEnv op s CompilerEnv :: Operations op s -> Map Name [Type] -> CompilerEnv op s [envOperations] :: CompilerEnv op s -> Operations op s [envFtable] :: CompilerEnv op s -> Map Name [Type] data CompilerState s CompilerState :: VNameSource -> [PyStmt] -> s -> CompilerState s [compNameSrc] :: CompilerState s -> VNameSource [compInit] :: CompilerState s -> [PyStmt] [compUserState] :: CompilerState s -> s stm :: PyStmt -> CompilerM op s () stms :: [PyStmt] -> CompilerM op s () atInit :: PyStmt -> CompilerM op s () collect' :: CompilerM op s a -> CompilerM op s (a, [PyStmt]) collect :: CompilerM op s () -> CompilerM op s [PyStmt] -- | A Call where the function is a variable and every argument is a -- simple Arg. simpleCall :: String -> [PyExp] -> PyExp copyMemoryDefaultSpace :: VName -> PyExp -> VName -> PyExp -> PyExp -> CompilerM op s () instance Control.Monad.Writer.Class.MonadWriter [Futhark.CodeGen.Backends.GenericPython.AST.PyStmt] (Futhark.CodeGen.Backends.GenericPython.CompilerM op s) instance Control.Monad.Reader.Class.MonadReader (Futhark.CodeGen.Backends.GenericPython.CompilerEnv op s) (Futhark.CodeGen.Backends.GenericPython.CompilerM op s) instance Control.Monad.State.Class.MonadState (Futhark.CodeGen.Backends.GenericPython.CompilerState s) (Futhark.CodeGen.Backends.GenericPython.CompilerM op s) instance GHC.Base.Monad (Futhark.CodeGen.Backends.GenericPython.CompilerM op s) instance GHC.Base.Applicative (Futhark.CodeGen.Backends.GenericPython.CompilerM op s) instance GHC.Base.Functor (Futhark.CodeGen.Backends.GenericPython.CompilerM op s) instance Futhark.MonadFreshNames.MonadFreshNames (Futhark.CodeGen.Backends.GenericPython.CompilerM op s) module Futhark.CodeGen.Backends.SequentialPython compileProg :: MonadFreshNames m => Maybe String -> Prog ExplicitMemory -> m (Either InternalError String) module Futhark.CodeGen.Backends.PyOpenCL compileProg :: MonadFreshNames m => Maybe String -> Prog ExplicitMemory -> m (Either InternalError String) module Futhark.CodeGen.Backends.GenericCSharp.AST data CSExp Integer :: Integer -> CSExp Bool :: Bool -> CSExp Float :: Double -> CSExp String :: String -> CSExp RawStringLiteral :: String -> CSExp Var :: String -> CSExp Addr :: CSExp -> CSExp Ref :: CSExp -> CSExp Out :: CSExp -> CSExp Deref :: String -> CSExp BinOp :: String -> CSExp -> CSExp -> CSExp PreUnOp :: String -> CSExp -> CSExp PostUnOp :: String -> CSExp -> CSExp Ternary :: CSExp -> CSExp -> CSExp -> CSExp Cond :: CSExp -> CSExp -> CSExp -> CSExp Index :: CSExp -> CSIdx -> CSExp Pair :: CSExp -> CSExp -> CSExp Call :: CSExp -> [CSArg] -> CSExp CallMethod :: CSExp -> CSExp -> [CSArg] -> CSExp CreateObject :: CSExp -> [CSArg] -> CSExp CreateArray :: CSType -> [CSExp] -> CSExp CreateSystemTuple :: [CSExp] -> CSExp AllocArray :: CSType -> CSExp -> CSExp Cast :: CSType -> CSExp -> CSExp Tuple :: [CSExp] -> CSExp Array :: [CSExp] -> CSExp Field :: CSExp -> String -> CSExp Lambda :: CSExp -> [CSStmt] -> CSExp Collection :: String -> [CSExp] -> CSExp This :: CSExp -> CSExp Null :: CSExp data CSType Composite :: CSComp -> CSType PointerT :: CSType -> CSType Primitive :: CSPrim -> CSType CustomT :: String -> CSType StaticT :: CSType -> CSType OutT :: CSType -> CSType RefT :: CSType -> CSType VoidT :: CSType data CSComp ArrayT :: CSType -> CSComp TupleT :: [CSType] -> CSComp SystemTupleT :: [CSType] -> CSComp data CSPrim CSInt :: CSInt -> CSPrim CSUInt :: CSUInt -> CSPrim CSFloat :: CSFloat -> CSPrim BoolT :: CSPrim ByteT :: CSPrim StringT :: CSPrim IntPtrT :: CSPrim data CSInt Int8T :: CSInt Int16T :: CSInt Int32T :: CSInt Int64T :: CSInt data CSUInt UInt8T :: CSUInt UInt16T :: CSUInt UInt32T :: CSUInt UInt64T :: CSUInt data CSFloat FloatT :: CSFloat DoubleT :: CSFloat data CSIdx IdxRange :: CSExp -> CSExp -> CSIdx IdxExp :: CSExp -> CSIdx data CSArg ArgKeyword :: String -> CSArg -> CSArg Arg :: Maybe ArgMemType -> CSExp -> CSArg data CSStmt If :: CSExp -> [CSStmt] -> [CSStmt] -> CSStmt Try :: [CSStmt] -> [CSExcept] -> CSStmt While :: CSExp -> [CSStmt] -> CSStmt For :: String -> CSExp -> [CSStmt] -> CSStmt ForEach :: String -> CSExp -> [CSStmt] -> CSStmt UsingWith :: CSStmt -> [CSStmt] -> CSStmt Unsafe :: [CSStmt] -> CSStmt Fixed :: CSExp -> CSExp -> [CSStmt] -> CSStmt Assign :: CSExp -> CSExp -> CSStmt Reassign :: CSExp -> CSExp -> CSStmt AssignOp :: String -> CSExp -> CSExp -> CSStmt AssignTyped :: CSType -> CSExp -> Maybe CSExp -> CSStmt Comment :: String -> [CSStmt] -> CSStmt Assert :: CSExp -> [CSExp] -> CSStmt Throw :: CSExp -> CSStmt Exp :: CSExp -> CSStmt Return :: CSExp -> CSStmt Pass :: CSStmt Using :: Maybe String -> String -> CSStmt StaticFunDef :: CSFunDef -> CSStmt PublicFunDef :: CSFunDef -> CSStmt PrivateFunDef :: CSFunDef -> CSStmt Namespace :: String -> [CSStmt] -> CSStmt ClassDef :: CSClassDef -> CSStmt ConstructorDef :: CSConstructorDef -> CSStmt StructDef :: String -> [(CSType, String)] -> CSStmt Escape :: String -> CSStmt newtype CSProg CSProg :: [CSStmt] -> CSProg data CSExcept Catch :: CSExp -> [CSStmt] -> CSExcept data CSFunDef Def :: String -> CSType -> [CSFunDefArg] -> [CSStmt] -> CSFunDef type CSFunDefArg = (CSType, String) data CSClassDef Class :: String -> [CSStmt] -> CSClassDef PublicClass :: String -> [CSStmt] -> CSClassDef data CSConstructorDef ClassConstructor :: String -> [CSFunDefArg] -> [CSStmt] -> CSConstructorDef instance GHC.Show.Show Futhark.CodeGen.Backends.GenericCSharp.AST.CSProg instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericCSharp.AST.CSProg instance GHC.Show.Show Futhark.CodeGen.Backends.GenericCSharp.AST.CSIdx instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericCSharp.AST.CSIdx instance GHC.Show.Show Futhark.CodeGen.Backends.GenericCSharp.AST.CSArg instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericCSharp.AST.CSArg instance GHC.Show.Show Futhark.CodeGen.Backends.GenericCSharp.AST.CSExp instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericCSharp.AST.CSExp instance GHC.Show.Show Futhark.CodeGen.Backends.GenericCSharp.AST.CSExcept instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericCSharp.AST.CSExcept instance GHC.Show.Show Futhark.CodeGen.Backends.GenericCSharp.AST.CSFunDef instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericCSharp.AST.CSFunDef instance GHC.Show.Show Futhark.CodeGen.Backends.GenericCSharp.AST.CSClassDef instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericCSharp.AST.CSClassDef instance GHC.Show.Show Futhark.CodeGen.Backends.GenericCSharp.AST.CSStmt instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericCSharp.AST.CSStmt instance GHC.Show.Show Futhark.CodeGen.Backends.GenericCSharp.AST.CSConstructorDef instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericCSharp.AST.CSConstructorDef instance GHC.Show.Show Futhark.CodeGen.Backends.GenericCSharp.AST.UnOp instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericCSharp.AST.UnOp instance GHC.Show.Show Futhark.CodeGen.Backends.GenericCSharp.AST.CSComp instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericCSharp.AST.CSComp instance GHC.Show.Show Futhark.CodeGen.Backends.GenericCSharp.AST.CSType instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericCSharp.AST.CSType instance GHC.Show.Show Futhark.CodeGen.Backends.GenericCSharp.AST.CSPrim instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericCSharp.AST.CSPrim instance GHC.Show.Show Futhark.CodeGen.Backends.GenericCSharp.AST.CSFloat instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericCSharp.AST.CSFloat instance GHC.Show.Show Futhark.CodeGen.Backends.GenericCSharp.AST.CSUInt instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericCSharp.AST.CSUInt instance GHC.Show.Show Futhark.CodeGen.Backends.GenericCSharp.AST.CSInt instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericCSharp.AST.CSInt instance GHC.Show.Show Futhark.CodeGen.Backends.GenericCSharp.AST.ArgMemType instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericCSharp.AST.ArgMemType instance GHC.Show.Show Futhark.CodeGen.Backends.GenericCSharp.AST.MemT instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericCSharp.AST.MemT instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericCSharp.AST.CSProg instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericCSharp.AST.CSExp instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericCSharp.AST.CSArg instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericCSharp.AST.CSStmt instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericCSharp.AST.CSFunDef instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericCSharp.AST.CSClassDef instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericCSharp.AST.CSConstructorDef instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericCSharp.AST.CSExcept instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericCSharp.AST.CSComp instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericCSharp.AST.CSType instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericCSharp.AST.CSPrim instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericCSharp.AST.CSFloat instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericCSharp.AST.CSUInt instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericCSharp.AST.CSInt instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericCSharp.AST.ArgMemType -- | This module defines a generator for getopt based command line -- argument parsing. Each option is associated with arbitrary Python code -- that will perform side effects, usually by setting some global -- variables. module Futhark.CodeGen.Backends.GenericCSharp.Options -- | Specification if a single command line option. The option must have a -- long name, and may also have a short name. -- -- When the statement is being executed, the argument (if any) will be -- stored in the variable optarg. data Option Option :: String -> Maybe Char -> OptionArgument -> [CSStmt] -> Option [optionLongName] :: Option -> String [optionShortName] :: Option -> Maybe Char [optionArgument] :: Option -> OptionArgument [optionAction] :: Option -> [CSStmt] -- | Whether an option accepts an argument. data OptionArgument NoArgument :: OptionArgument RequiredArgument :: OptionArgument OptionalArgument :: OptionArgument -- | Generate option parsing code that accepts the given command line -- options. Will read from sys.argv. -- -- If option parsing fails for any reason, the entire process will -- terminate with error code 1. generateOptionParser :: [Option] -> [CSStmt] -- | A generic C# code generator which is polymorphic in the type of the -- operations. Concretely, we use this to handle both sequential and -- OpenCL C# code. module Futhark.CodeGen.Backends.GenericCSharp compileProg :: MonadFreshNames m => Maybe String -> Constructor -> [CSStmt] -> [CSStmt] -> Operations op s -> s -> CompilerM op s () -> [CSStmt] -> [Space] -> [Option] -> Functions op -> m String -- | The class generated by the code generator must have a constructor, -- although it can be vacuous. data Constructor Constructor :: [CSFunDefArg] -> [CSStmt] -> Constructor -- | A constructor that takes no arguments and does nothing. emptyConstructor :: Constructor assignScalarPointer :: CSExp -> CSExp -> CSStmt toIntPtr :: CSExp -> CSExp compileName :: VName -> String compileDim :: DimSize -> CSExp compileExp :: Exp -> CompilerM op s CSExp compileCode :: Code op -> CompilerM op s () -- | The ctypes type corresponding to a PrimType. compilePrimValue :: PrimValue -> CSExp -- | The ctypes type corresponding to a PrimType. compilePrimType :: PrimType -> String -- | The ctypes type corresponding to a PrimType, taking sign into -- account. compilePrimTypeExt :: PrimType -> Signedness -> String compilePrimTypeToAST :: PrimType -> CSType compilePrimTypeToASText :: PrimType -> Signedness -> CSType contextFinalInits :: CompilerM op s [CSStmt] debugReport :: CSStmt -> CompilerM op s () data Operations op s Operations :: WriteScalar op s -> ReadScalar op s -> Allocate op s -> Copy op s -> StaticArray op s -> OpCompiler op s -> EntryOutput op s -> EntryInput op s -> CSStmt -> Operations op s [opsWriteScalar] :: Operations op s -> WriteScalar op s [opsReadScalar] :: Operations op s -> ReadScalar op s [opsAllocate] :: Operations op s -> Allocate op s [opsCopy] :: Operations op s -> Copy op s [opsStaticArray] :: Operations op s -> StaticArray op s [opsCompiler] :: Operations op s -> OpCompiler op s [opsEntryOutput] :: Operations op s -> EntryOutput op s [opsEntryInput] :: Operations op s -> EntryInput op s [opsSyncRun] :: Operations op s -> CSStmt -- | A set of operations that fail for every operation involving -- non-default memory spaces. Uses plain pointers and malloc for -- memory management. defaultOperations :: Operations op s unpackDim :: CSExp -> DimSize -> Int32 -> CompilerM op s () newtype CompilerM op s a CompilerM :: RWS (CompilerEnv op s) (CompilerAcc op s) (CompilerState s) a -> CompilerM op s a -- | A substitute expression compiler, tried before the main compilation -- function. type OpCompiler op s = op -> CompilerM op s () -- | Write a scalar to the given memory block with the given index and in -- the given memory space. type WriteScalar op s = VName -> CSExp -> PrimType -> SpaceId -> CSExp -> CompilerM op s () -- | Read a scalar from the given memory block with the given index and in -- the given memory space. type ReadScalar op s = VName -> CSExp -> PrimType -> SpaceId -> CompilerM op s CSExp -- | Allocate a memory block of the given size in the given memory space, -- saving a reference in the given variable name. type Allocate op s = VName -> CSExp -> SpaceId -> CompilerM op s () -- | Copy from one memory block to another. type Copy op s = VName -> CSExp -> Space -> VName -> CSExp -> Space -> CSExp -> PrimType -> CompilerM op s () -- | Create a static array of values - initialised at load time. type StaticArray op s = VName -> SpaceId -> PrimType -> [PrimValue] -> CompilerM op s () -- | Construct the C# array being returned from an entry point. type EntryOutput op s = VName -> SpaceId -> PrimType -> Signedness -> [DimSize] -> CompilerM op s CSExp -- | Unpack the array being passed to an entry point. type EntryInput op s = VName -> MemSize -> SpaceId -> PrimType -> Signedness -> [DimSize] -> CSExp -> CompilerM op s () data CompilerEnv op s CompilerEnv :: Operations op s -> Map Name [Type] -> CompilerEnv op s [envOperations] :: CompilerEnv op s -> Operations op s [envFtable] :: CompilerEnv op s -> Map Name [Type] data CompilerState s CompilerState :: VNameSource -> [CSStmt] -> [CSStmt] -> [CSStmt] -> [CSStmt] -> [CSStmt] -> s -> [CSStmt] -> [VName] -> [(VName, Space)] -> CompilerState s [compNameSrc] :: CompilerState s -> VNameSource [compBeforeParse] :: CompilerState s -> [CSStmt] [compInit] :: CompilerState s -> [CSStmt] [compStaticMemDecls] :: CompilerState s -> [CSStmt] [compStaticMemAllocs] :: CompilerState s -> [CSStmt] [compDebugItems] :: CompilerState s -> [CSStmt] [compUserState] :: CompilerState s -> s [compMemberDecls] :: CompilerState s -> [CSStmt] [compAssignedVars] :: CompilerState s -> [VName] [compDeclaredMem] :: CompilerState s -> [(VName, Space)] stm :: CSStmt -> CompilerM op s () stms :: [CSStmt] -> CompilerM op s () atInit :: CSStmt -> CompilerM op s () staticMemDecl :: CSStmt -> CompilerM op s () staticMemAlloc :: CSStmt -> CompilerM op s () addMemberDecl :: CSStmt -> CompilerM op s () beforeParse :: CSStmt -> CompilerM op s () collect' :: CompilerM op s a -> CompilerM op s (a, [CSStmt]) collect :: CompilerM op s () -> CompilerM op s [CSStmt] -- | A Call where the function is a variable and every argument is a -- simple Arg. simpleCall :: String -> [CSExp] -> CSExp -- | A CallMethod callMethod :: CSExp -> String -> [CSExp] -> CSExp simpleInitClass :: String -> [CSExp] -> CSExp -- | A Call where the function is a variable and every argument is a -- simple Arg. parametrizedCall :: String -> String -> [CSExp] -> CSExp copyMemoryDefaultSpace :: VName -> CSExp -> VName -> CSExp -> CSExp -> CompilerM op s () consoleErrorWrite :: String -> [CSExp] -> CSExp consoleErrorWriteLine :: String -> [CSExp] -> CSExp consoleWrite :: String -> [CSExp] -> CSExp consoleWriteLine :: String -> [CSExp] -> CSExp -- | Public names must have a consistent prefix. publicName :: String -> String sizeOf :: CSType -> CSExp privateFunDef :: String -> CSType -> [(CSType, String)] -> [CSStmt] -> CSStmt publicFunDef :: String -> CSType -> [(CSType, String)] -> [CSStmt] -> CSStmt getDefaultDecl :: Param -> CSStmt instance Control.Monad.Writer.Class.MonadWriter (Futhark.CodeGen.Backends.GenericCSharp.CompilerAcc op s) (Futhark.CodeGen.Backends.GenericCSharp.CompilerM op s) instance Control.Monad.Reader.Class.MonadReader (Futhark.CodeGen.Backends.GenericCSharp.CompilerEnv op s) (Futhark.CodeGen.Backends.GenericCSharp.CompilerM op s) instance Control.Monad.State.Class.MonadState (Futhark.CodeGen.Backends.GenericCSharp.CompilerState s) (Futhark.CodeGen.Backends.GenericCSharp.CompilerM op s) instance GHC.Base.Monad (Futhark.CodeGen.Backends.GenericCSharp.CompilerM op s) instance GHC.Base.Applicative (Futhark.CodeGen.Backends.GenericCSharp.CompilerM op s) instance GHC.Base.Functor (Futhark.CodeGen.Backends.GenericCSharp.CompilerM op s) instance Futhark.MonadFreshNames.MonadFreshNames (Futhark.CodeGen.Backends.GenericCSharp.CompilerM op s) instance GHC.Base.Semigroup (Futhark.CodeGen.Backends.GenericCSharp.CompilerAcc op s) instance GHC.Base.Monoid (Futhark.CodeGen.Backends.GenericCSharp.CompilerAcc op s) module Futhark.CodeGen.Backends.SequentialCSharp compileProg :: MonadFreshNames m => Maybe String -> Prog ExplicitMemory -> m (Either InternalError String) module Futhark.CodeGen.Backends.CSOpenCL.Boilerplate generateBoilerplate :: String -> String -> [String] -> [PrimType] -> Map VName (SizeClass, Name) -> CompilerM OpenCL () () kernelRuntime :: String -> String kernelRuns :: String -> String module Futhark.CodeGen.Backends.CSOpenCL compileProg :: MonadFreshNames m => Maybe String -> Prog ExplicitMemory -> m (Either InternalError String) -- | The Futhark basis library embedded embedded as strings read during -- compilation of the Futhark compiler. The advantage is that the -- standard library can be accessed without reading it from disk, thus -- saving users from include path headaches. module Language.Futhark.Futlib -- | Futlib embedded as Text values, one for every file. futlib :: [(FilePath, Text)] prelude :: [String] -- | This is an ever-changing syntax representation for Futhark. Some -- types, such as Exp, are parametrised by type and name -- representation. See the -- https://futhark.readthedocs.org for a language -- reference, or this module may be a little hard to understand. module Language.Futhark.Syntax -- | The uniqueness attribute of a type. This essentially indicates whether -- or not in-place modifications are acceptable. With respect to -- ordering, Unique is greater than Nonunique. data Uniqueness -- | May have references outside current function. Nonunique :: Uniqueness -- | No references outside current function. Unique :: Uniqueness -- | An integer type, ordered by size. Note that signedness is not a -- property of the type, but a property of the operations performed on -- values of these types. data IntType Int8 :: IntType Int16 :: IntType Int32 :: IntType Int64 :: IntType -- | A floating point type. data FloatType Float32 :: FloatType Float64 :: FloatType -- | Low-level primitive types. data PrimType Signed :: IntType -> PrimType Unsigned :: IntType -> PrimType FloatType :: FloatType -> PrimType Bool :: PrimType class (Eq dim, Ord dim) => ArrayDim dim -- | unifyDims x y combines x and y to contain -- their maximum common information, and fails if they conflict. unifyDims :: ArrayDim dim => dim -> dim -> Maybe dim -- | Declaration of a dimension size. data DimDecl vn -- | The size of the dimension is this name, which must be in scope. In a -- return type, this will give rise to an assertion. NamedDim :: QualName vn -> DimDecl vn -- | The size is a constant. ConstDim :: Int -> DimDecl vn -- | No dimension declaration. AnyDim :: DimDecl vn -- | The size of an array type is a list of its dimension sizes. If -- Nothing, that dimension is of a (statically) unknown size. newtype ShapeDecl dim ShapeDecl :: [dim] -> ShapeDecl dim [shapeDims] :: ShapeDecl dim -> [dim] -- | The number of dimensions contained in a shape. shapeRank :: ShapeDecl dim -> Int -- | stripDims n shape strips the outer n dimensions from -- shape, returning Nothing if this would result in zero -- or fewer dimensions. stripDims :: Int -> ShapeDecl dim -> Maybe (ShapeDecl dim) -- | unifyShapes x y combines x and y to contain -- their maximum common information, and fails if they conflict. unifyShapes :: ArrayDim dim => ShapeDecl dim -> ShapeDecl dim -> Maybe (ShapeDecl dim) -- | A type name consists of qualifiers (for error messages) and a -- VName (for equality checking). data TypeName TypeName :: [VName] -> VName -> TypeName [typeQuals] :: TypeName -> [VName] [typeLeaf] :: TypeName -> VName typeNameFromQualName :: QualName VName -> TypeName qualNameFromTypeName :: TypeName -> QualName VName -- | An expanded Futhark type is either an array, a prim type, a tuple, or -- a type variable. When comparing types for equality with ==, -- aliases are ignored, but dimensions much match. Function parameter -- names are ignored. data TypeBase dim as Prim :: PrimType -> TypeBase dim as Array :: ArrayElemTypeBase dim as -> ShapeDecl dim -> Uniqueness -> TypeBase dim as Record :: Map Name (TypeBase dim as) -> TypeBase dim as TypeVar :: as -> Uniqueness -> TypeName -> [TypeArg dim as] -> TypeBase dim as -- | The aliasing corresponds to the lexical closure of the function. Arrow :: as -> Maybe VName -> TypeBase dim as -> TypeBase dim as -> TypeBase dim as data TypeArg dim as TypeArgDim :: dim -> SrcLoc -> TypeArg dim as TypeArgType :: TypeBase dim as -> SrcLoc -> TypeArg dim as -- | An unstructured type with type variables and possibly shape -- declarations - this is what the user types in the source program. data TypeExp vn TEVar :: QualName vn -> SrcLoc -> TypeExp vn TETuple :: [TypeExp vn] -> SrcLoc -> TypeExp vn TERecord :: [(Name, TypeExp vn)] -> SrcLoc -> TypeExp vn TEArray :: TypeExp vn -> DimDecl vn -> SrcLoc -> TypeExp vn TEUnique :: TypeExp vn -> SrcLoc -> TypeExp vn TEApply :: TypeExp vn -> TypeArgExp vn -> SrcLoc -> TypeExp vn TEArrow :: Maybe vn -> TypeExp vn -> TypeExp vn -> SrcLoc -> TypeExp vn data TypeArgExp vn TypeArgExpDim :: DimDecl vn -> SrcLoc -> TypeArgExp vn TypeArgExpType :: TypeExp vn -> TypeArgExp vn -- | Types that can be elements of tuple-arrays. data RecordArrayElemTypeBase dim as RecordArrayElem :: ArrayElemTypeBase dim as -> RecordArrayElemTypeBase dim as RecordArrayArrayElem :: ArrayElemTypeBase dim as -> ShapeDecl dim -> Uniqueness -> RecordArrayElemTypeBase dim as data ArrayElemTypeBase dim as ArrayPrimElem :: PrimType -> as -> ArrayElemTypeBase dim as ArrayPolyElem :: TypeName -> [TypeArg dim as] -> as -> ArrayElemTypeBase dim as ArrayRecordElem :: Map Name (RecordArrayElemTypeBase dim as) -> ArrayElemTypeBase dim as -- | A type with aliasing information and no shape annotations, used for -- describing the type of a computation. type CompType = TypeBase () Names -- | A type with aliasing information and shape annotations, used for -- describing the type of a pattern. type PatternType = TypeBase (DimDecl VName) Names -- | A "structural" type with shape annotations and no aliasing -- information, used for declarations. type StructType = TypeBase (DimDecl VName) () -- | Information about which parts of a value/type are consumed. data Diet -- | Consumes these fields in the record. RecordDiet :: Map Name Diet -> Diet -- | A function that consumes its argument(s) like this. The final -- Diet should always be Observe, as there is no way for a -- function to consume its return value. FuncDiet :: Diet -> Diet -> Diet -- | Consumes this value. Consume :: Diet -- | Only observes value in this position, does not consume. Observe :: Diet -- | A declaration of the type of something. data TypeDeclBase f vn TypeDecl :: TypeExp vn -> f StructType -> TypeDeclBase f vn -- | The type declared by the user. [declaredType] :: TypeDeclBase f vn -> TypeExp vn -- | The type deduced by the type checker. [expandedType] :: TypeDeclBase f vn -> f StructType -- | An integer value. data IntValue Int8Value :: !Int8 -> IntValue Int16Value :: !Int16 -> IntValue Int32Value :: !Int32 -> IntValue Int64Value :: !Int64 -> IntValue -- | A floating-point value. data FloatValue Float32Value :: !Float -> FloatValue Float64Value :: !Double -> FloatValue -- | Non-array values. data PrimValue SignedValue :: !IntValue -> PrimValue UnsignedValue :: !IntValue -> PrimValue FloatValue :: !FloatValue -> PrimValue BoolValue :: !Bool -> PrimValue class IsPrimValue v primValue :: IsPrimValue v => v -> PrimValue -- | Simple Futhark values. Values are fully evaluated and their type is -- always unambiguous. data Value PrimValue :: !PrimValue -> Value -- | It is assumed that the array is 0-indexed. The type is the full type. ArrayValue :: !Array Int Value -> TypeBase () () -> Value -- | Default binary operators. data BinOp -- | A pseudo-operator standing in for any normal identifier used as an -- operator (they all have the same fixity). Binary Ops for Numbers Backtick :: BinOp Plus :: BinOp Minus :: BinOp Pow :: BinOp Times :: BinOp Divide :: BinOp Mod :: BinOp Quot :: BinOp Rem :: BinOp ShiftR :: BinOp ShiftL :: BinOp Band :: BinOp Xor :: BinOp Bor :: BinOp LogAnd :: BinOp LogOr :: BinOp Equal :: BinOp NotEqual :: BinOp Less :: BinOp Leq :: BinOp Greater :: BinOp Geq :: BinOp -- |
-- |> --PipeRight :: BinOp -- | <| Misc PipeLeft :: BinOp -- | An identifier consists of its name and the type of the value bound to -- the identifier. data IdentBase f vn Ident :: vn -> f CompType -> SrcLoc -> IdentBase f vn [identName] :: IdentBase f vn -> vn [identType] :: IdentBase f vn -> f CompType [identSrcLoc] :: IdentBase f vn -> SrcLoc -- | Whether a bound for an end-point of a DimSlice or a range -- literal is inclusive or exclusive. data Inclusiveness a DownToExclusive :: a -> Inclusiveness a -- | May be "down to" if step is negative. ToInclusive :: a -> Inclusiveness a UpToExclusive :: a -> Inclusiveness a -- | An indexing of a single dimension. data DimIndexBase f vn DimFix :: ExpBase f vn -> DimIndexBase f vn DimSlice :: Maybe (ExpBase f vn) -> Maybe (ExpBase f vn) -> Maybe (ExpBase f vn) -> DimIndexBase f vn -- | The Futhark expression language. -- -- In a value of type Exp f vn, annotations are wrapped in the -- functor f, and all names are of type vn. -- -- This allows us to encode whether or not the expression has been -- type-checked in the Haskell type of the expression. Specifically, the -- parser will produce expressions of type Exp NoInfo -- Name, and the type checker will convert these to Exp -- Info VName, in which type information is always -- present and all names are unique. data ExpBase f vn Literal :: PrimValue -> SrcLoc -> ExpBase f vn -- | A polymorphic integral literal. IntLit :: Integer -> f (TypeBase () ()) -> SrcLoc -> ExpBase f vn -- | A polymorphic decimal literal. FloatLit :: Double -> f (TypeBase () ()) -> SrcLoc -> ExpBase f vn -- | A parenthesized expression. Parens :: ExpBase f vn -> SrcLoc -> ExpBase f vn QualParens :: QualName vn -> ExpBase f vn -> SrcLoc -> ExpBase f vn -- | Tuple literals, e.g., {1+3, {x, y+z}}. TupLit :: [ExpBase f vn] -> SrcLoc -> ExpBase f vn -- | Record literals, e.g. {x=2,y=3,z}. RecordLit :: [FieldBase f vn] -> SrcLoc -> ExpBase f vn -- | Array literals, e.g., [ [1+x, 3], [2, 1+4] ]. Second arg is -- the row type of the rows of the array. ArrayLit :: [ExpBase f vn] -> f CompType -> SrcLoc -> ExpBase f vn Range :: ExpBase f vn -> Maybe (ExpBase f vn) -> Inclusiveness (ExpBase f vn) -> f CompType -> SrcLoc -> ExpBase f vn Var :: QualName vn -> f PatternType -> SrcLoc -> ExpBase f vn -- | Type ascription: e : t. Ascript :: ExpBase f vn -> TypeDeclBase f vn -> SrcLoc -> ExpBase f vn LetPat :: [TypeParamBase vn] -> PatternBase f vn -> ExpBase f vn -> ExpBase f vn -> SrcLoc -> ExpBase f vn LetFun :: vn -> ([TypeParamBase vn], [PatternBase f vn], Maybe (TypeExp vn), f StructType, ExpBase f vn) -> ExpBase f vn -> SrcLoc -> ExpBase f vn If :: ExpBase f vn -> ExpBase f vn -> ExpBase f vn -> f CompType -> SrcLoc -> ExpBase f vn Apply :: ExpBase f vn -> ExpBase f vn -> f Diet -> f PatternType -> SrcLoc -> ExpBase f vn -- | Numeric negation (ugly special case; Haskell did it first). Negate :: ExpBase f vn -> SrcLoc -> ExpBase f vn Lambda :: [TypeParamBase vn] -> [PatternBase f vn] -> ExpBase f vn -> Maybe (TypeDeclBase f vn) -> f (Names, StructType) -> SrcLoc -> ExpBase f vn -- | +; first two types are operands, third is result. OpSection :: QualName vn -> f PatternType -> SrcLoc -> ExpBase f vn -- | 2+; first type is operand, second is result. OpSectionLeft :: QualName vn -> f PatternType -> ExpBase f vn -> (f StructType, f StructType) -> f PatternType -> SrcLoc -> ExpBase f vn -- | +2; first type is operand, second is result. OpSectionRight :: QualName vn -> f PatternType -> ExpBase f vn -> (f StructType, f StructType) -> f PatternType -> SrcLoc -> ExpBase f vn -- | Field projection as a section: (.x.y.z). ProjectSection :: [Name] -> f PatternType -> SrcLoc -> ExpBase f vn -- | Array indexing as a section: (.[i,j]). IndexSection :: [DimIndexBase f vn] -> f PatternType -> SrcLoc -> ExpBase f vn DoLoop :: [TypeParamBase vn] -> PatternBase f vn -> ExpBase f vn -> LoopFormBase f vn -> ExpBase f vn -> SrcLoc -> ExpBase f vn BinOp :: QualName vn -> f PatternType -> (ExpBase f vn, f StructType) -> (ExpBase f vn, f StructType) -> f PatternType -> SrcLoc -> ExpBase f vn Project :: Name -> ExpBase f vn -> f CompType -> SrcLoc -> ExpBase f vn LetWith :: IdentBase f vn -> IdentBase f vn -> [DimIndexBase f vn] -> ExpBase f vn -> ExpBase f vn -> SrcLoc -> ExpBase f vn Index :: ExpBase f vn -> [DimIndexBase f vn] -> f CompType -> SrcLoc -> ExpBase f vn Update :: ExpBase f vn -> [DimIndexBase f vn] -> ExpBase f vn -> SrcLoc -> ExpBase f vn RecordUpdate :: ExpBase f vn -> [Name] -> ExpBase f vn -> f PatternType -> SrcLoc -> ExpBase f vn -- | map (+1) [1, 2, ..., n] = [2, 3, ..., n+1]. Map :: ExpBase f vn -> ExpBase f vn -> f CompType -> SrcLoc -> ExpBase f vn -- | reduce (+) 0 ([1,2,...,n]) = (0+1+2+...+n). Reduce :: Commutativity -> ExpBase f vn -> ExpBase f vn -> ExpBase f vn -> SrcLoc -> ExpBase f vn -- |
-- gen_reduce 1,1,1 0 [1,1,1] [1,1,1] = [4,1,1] --GenReduce :: ExpBase f vn -> ExpBase f vn -> ExpBase f vn -> ExpBase f vn -> ExpBase f vn -> SrcLoc -> ExpBase f vn -- | scan (+) 0 ([ 1, 2, 3 ]) = [ 1, 3, 6 ]. Scan :: ExpBase f vn -> ExpBase f vn -> ExpBase f vn -> SrcLoc -> ExpBase f vn -- | Return those elements of the array that satisfy the predicate. Filter :: ExpBase f vn -> ExpBase f vn -> SrcLoc -> ExpBase f vn -- | partition k f a, where f returns an integer, returns -- a tuple (a', is) that describes a partitioning of a -- into n equivalence classes. Here, a' is a -- re-ordering of a, and is is an array of k -- offsets into a'. Partition :: Int -> ExpBase f vn -> ExpBase f vn -> SrcLoc -> ExpBase f vn -- | Streaming: intuitively, this gives a size-parameterized composition -- for SOACs that cannot be fused, e.g., due to scan. For example, -- assuming A : [int], f : int->int, g : real->real, the -- code: let x = map(f,A) in let y = scan(op+,0,x) in map(g,y) -- can be re-written (streamed) in the source-Futhark language as: -- let (acc, z) = stream (fn (int,[real]) (real chunk, real -- acc, [int] a) => let x = map (f, A ) let y0= -- scan(op +, 0, x ) let y = map (op +(acc), y0) ( -- acc+y0[chunk-1], map(g, y) ) ) 0 A where (i) -- chunk is a symbolic int denoting the chunk size, (ii) -- 0 is the initial value of the accumulator, which allows the -- streaming of scan. Finally, the unnamed function -- (fn...) implements the a fold that: computes the accumulator -- of scan, as defined inside its body, AND implicitly -- concatenates each of the result arrays across the iteration space. In -- essence, sequential codegen can choose chunk = 1 and thus eliminate -- the SOACs on the outermost level, while parallel codegen may choose -- the maximal chunk size that still satisfies the memory requirements of -- the device. Stream :: StreamForm f vn -> ExpBase f vn -> ExpBase f vn -> SrcLoc -> ExpBase f vn -- | Conventional zip taking nonzero arrays as arguments. All arrays must -- have the exact same length. Zip :: Int -> ExpBase f vn -> [ExpBase f vn] -> f CompType -> SrcLoc -> ExpBase f vn -- | Unzip that can unzip to tuples of arbitrary size. The types are the -- elements of the tuple. Unzip :: ExpBase f vn -> [f CompType] -> SrcLoc -> ExpBase f vn -- | Explore the Danger Zone and elide safety checks on array operations -- and other assertions during execution of this expression. Make really -- sure the code is correct. Unsafe :: ExpBase f vn -> SrcLoc -> ExpBase f vn -- | Fail if the first expression does not return true, and return the -- value of the second expression if it does. Assert :: ExpBase f vn -> ExpBase f vn -> f String -> SrcLoc -> ExpBase f vn -- | An entry in a record literal. data FieldBase f vn RecordFieldExplicit :: Name -> ExpBase f vn -> SrcLoc -> FieldBase f vn RecordFieldImplicit :: vn -> f CompType -> SrcLoc -> FieldBase f vn -- | Whether the loop is a for-loop or a while-loop. data LoopFormBase f vn For :: IdentBase f vn -> ExpBase f vn -> LoopFormBase f vn ForIn :: PatternBase f vn -> ExpBase f vn -> LoopFormBase f vn While :: ExpBase f vn -> LoopFormBase f vn -- | A pattern as used most places where variables are bound (function -- parameters, let expressions, etc). data PatternBase f vn TuplePattern :: [PatternBase f vn] -> SrcLoc -> PatternBase f vn RecordPattern :: [(Name, PatternBase f vn)] -> SrcLoc -> PatternBase f vn PatternParens :: PatternBase f vn -> SrcLoc -> PatternBase f vn Id :: vn -> f PatternType -> SrcLoc -> PatternBase f vn Wildcard :: f PatternType -> SrcLoc -> PatternBase f vn PatternAscription :: PatternBase f vn -> TypeDeclBase f vn -> SrcLoc -> PatternBase f vn data StreamForm f vn MapLike :: StreamOrd -> StreamForm f vn RedLike :: StreamOrd -> Commutativity -> ExpBase f vn -> StreamForm f vn data SpecBase f vn ValSpec :: vn -> [TypeParamBase vn] -> TypeDeclBase f vn -> Maybe DocComment -> SrcLoc -> SpecBase f vn [specName] :: SpecBase f vn -> vn [specTypeParams] :: SpecBase f vn -> [TypeParamBase vn] [specType] :: SpecBase f vn -> TypeDeclBase f vn [specDoc] :: SpecBase f vn -> Maybe DocComment [specLocation] :: SpecBase f vn -> SrcLoc TypeAbbrSpec :: TypeBindBase f vn -> SpecBase f vn -- | Abstract type. TypeSpec :: Liftedness -> vn -> [TypeParamBase vn] -> Maybe DocComment -> SrcLoc -> SpecBase f vn ModSpec :: vn -> SigExpBase f vn -> Maybe DocComment -> SrcLoc -> SpecBase f vn IncludeSpec :: SigExpBase f vn -> SrcLoc -> SpecBase f vn data SigExpBase f vn SigVar :: QualName vn -> SrcLoc -> SigExpBase f vn SigParens :: SigExpBase f vn -> SrcLoc -> SigExpBase f vn SigSpecs :: [SpecBase f vn] -> SrcLoc -> SigExpBase f vn SigWith :: SigExpBase f vn -> TypeRefBase f vn -> SrcLoc -> SigExpBase f vn SigArrow :: Maybe vn -> SigExpBase f vn -> SigExpBase f vn -> SrcLoc -> SigExpBase f vn -- | A type refinement. data TypeRefBase f vn TypeRef :: QualName vn -> [TypeParamBase vn] -> TypeDeclBase f vn -> SrcLoc -> TypeRefBase f vn data SigBindBase f vn SigBind :: vn -> SigExpBase f vn -> Maybe DocComment -> SrcLoc -> SigBindBase f vn [sigName] :: SigBindBase f vn -> vn [sigExp] :: SigBindBase f vn -> SigExpBase f vn [sigDoc] :: SigBindBase f vn -> Maybe DocComment [sigLoc] :: SigBindBase f vn -> SrcLoc data ModExpBase f vn ModVar :: QualName vn -> SrcLoc -> ModExpBase f vn ModParens :: ModExpBase f vn -> SrcLoc -> ModExpBase f vn -- | The contents of another file as a module. ModImport :: FilePath -> f FilePath -> SrcLoc -> ModExpBase f vn ModDecs :: [DecBase f vn] -> SrcLoc -> ModExpBase f vn -- | Functor application. ModApply :: ModExpBase f vn -> ModExpBase f vn -> f (Map VName VName) -> f (Map VName VName) -> SrcLoc -> ModExpBase f vn ModAscript :: ModExpBase f vn -> SigExpBase f vn -> f (Map VName VName) -> SrcLoc -> ModExpBase f vn ModLambda :: ModParamBase f vn -> Maybe (SigExpBase f vn, f (Map VName VName)) -> ModExpBase f vn -> SrcLoc -> ModExpBase f vn data ModBindBase f vn ModBind :: vn -> [ModParamBase f vn] -> Maybe (SigExpBase f vn, f (Map VName VName)) -> ModExpBase f vn -> Maybe DocComment -> SrcLoc -> ModBindBase f vn [modName] :: ModBindBase f vn -> vn [modParams] :: ModBindBase f vn -> [ModParamBase f vn] [modSignature] :: ModBindBase f vn -> Maybe (SigExpBase f vn, f (Map VName VName)) [modExp] :: ModBindBase f vn -> ModExpBase f vn [modDoc] :: ModBindBase f vn -> Maybe DocComment [modLocation] :: ModBindBase f vn -> SrcLoc data ModParamBase f vn ModParam :: vn -> SigExpBase f vn -> f [VName] -> SrcLoc -> ModParamBase f vn [modParamName] :: ModParamBase f vn -> vn [modParamType] :: ModParamBase f vn -> SigExpBase f vn [modParamAbs] :: ModParamBase f vn -> f [VName] [modParamLocation] :: ModParamBase f vn -> SrcLoc -- | Documentation strings, including source location. data DocComment DocComment :: String -> SrcLoc -> DocComment -- | Function Declarations data ValBindBase f vn ValBind :: Bool -> vn -> Maybe (TypeExp vn) -> f StructType -> [TypeParamBase vn] -> [PatternBase f vn] -> ExpBase f vn -> Maybe DocComment -> SrcLoc -> ValBindBase f vn -- | True if this function is an entry point. [valBindEntryPoint] :: ValBindBase f vn -> Bool [valBindName] :: ValBindBase f vn -> vn [valBindRetDecl] :: ValBindBase f vn -> Maybe (TypeExp vn) [valBindRetType] :: ValBindBase f vn -> f StructType [valBindTypeParams] :: ValBindBase f vn -> [TypeParamBase vn] [valBindParams] :: ValBindBase f vn -> [PatternBase f vn] [valBindBody] :: ValBindBase f vn -> ExpBase f vn [valBindDoc] :: ValBindBase f vn -> Maybe DocComment [valBindLocation] :: ValBindBase f vn -> SrcLoc -- | The liftedness of a type parameter. By the Ord instance, -- Unlifted is less than Lifted. data Liftedness -- | May only be instantiated with a zero-order type. Unlifted :: Liftedness -- | May be instantiated to a functional type. Lifted :: Liftedness -- | Type Declarations data TypeBindBase f vn TypeBind :: vn -> [TypeParamBase vn] -> TypeDeclBase f vn -> Maybe DocComment -> SrcLoc -> TypeBindBase f vn [typeAlias] :: TypeBindBase f vn -> vn [typeParams] :: TypeBindBase f vn -> [TypeParamBase vn] [typeExp] :: TypeBindBase f vn -> TypeDeclBase f vn [typeDoc] :: TypeBindBase f vn -> Maybe DocComment [typeBindLocation] :: TypeBindBase f vn -> SrcLoc data TypeParamBase vn -- | A type parameter that must be a size. TypeParamDim :: vn -> SrcLoc -> TypeParamBase vn -- | A type parameter that must be a type. TypeParamType :: Liftedness -> vn -> SrcLoc -> TypeParamBase vn typeParamName :: TypeParamBase vn -> vn -- | The program described by a single Futhark file. May depend on other -- files. data ProgBase f vn Prog :: Maybe DocComment -> [DecBase f vn] -> ProgBase f vn [progDoc] :: ProgBase f vn -> Maybe DocComment [progDecs] :: ProgBase f vn -> [DecBase f vn] -- | A top-level binding. data DecBase f vn ValDec :: ValBindBase f vn -> DecBase f vn TypeDec :: TypeBindBase f vn -> DecBase f vn SigDec :: SigBindBase f vn -> DecBase f vn ModDec :: ModBindBase f vn -> DecBase f vn OpenDec :: ModExpBase f vn -> f [VName] -> SrcLoc -> DecBase f vn LocalDec :: DecBase f vn -> SrcLoc -> DecBase f vn -- | No information functor. Usually used for placeholder type- or aliasing -- information. data NoInfo a NoInfo :: NoInfo a -- | Some information. The dual to NoInfo newtype Info a Info :: a -> Info a [unInfo] :: Info a -> a -- | A set of names. type Names = Set VName -- | A name qualified with a breadcrumb of module accesses. data QualName vn QualName :: ![vn] -> !vn -> QualName vn [qualQuals] :: QualName vn -> ![vn] [qualLeaf] :: QualName vn -> !vn instance GHC.Show.Show vn => GHC.Show.Show (Language.Futhark.Syntax.TypeParamBase vn) instance GHC.Classes.Eq vn => GHC.Classes.Eq (Language.Futhark.Syntax.TypeParamBase vn) instance GHC.Show.Show Language.Futhark.Syntax.Liftedness instance GHC.Classes.Ord Language.Futhark.Syntax.Liftedness instance GHC.Classes.Eq Language.Futhark.Syntax.Liftedness instance GHC.Show.Show Language.Futhark.Syntax.DocComment instance GHC.Show.Show vn => GHC.Show.Show (Language.Futhark.Syntax.TypeArgExp vn) instance GHC.Classes.Eq vn => GHC.Classes.Eq (Language.Futhark.Syntax.TypeArgExp vn) instance GHC.Show.Show vn => GHC.Show.Show (Language.Futhark.Syntax.TypeExp vn) instance GHC.Classes.Eq vn => GHC.Classes.Eq (Language.Futhark.Syntax.TypeExp vn) instance GHC.Show.Show vn => GHC.Show.Show (Language.Futhark.Syntax.DimDecl vn) instance GHC.Classes.Ord vn => GHC.Classes.Ord (Language.Futhark.Syntax.DimDecl vn) instance GHC.Classes.Eq vn => GHC.Classes.Eq (Language.Futhark.Syntax.DimDecl vn) instance GHC.Show.Show vn => GHC.Show.Show (Language.Futhark.Syntax.QualName vn) instance GHC.Classes.Ord vn => GHC.Classes.Ord (Language.Futhark.Syntax.QualName vn) instance GHC.Classes.Eq vn => GHC.Classes.Eq (Language.Futhark.Syntax.QualName vn) instance GHC.Show.Show a => GHC.Show.Show (Language.Futhark.Syntax.Inclusiveness a) instance GHC.Classes.Ord a => GHC.Classes.Ord (Language.Futhark.Syntax.Inclusiveness a) instance GHC.Classes.Eq a => GHC.Classes.Eq (Language.Futhark.Syntax.Inclusiveness a) instance GHC.Enum.Bounded Language.Futhark.Syntax.BinOp instance GHC.Enum.Enum Language.Futhark.Syntax.BinOp instance GHC.Show.Show Language.Futhark.Syntax.BinOp instance GHC.Classes.Ord Language.Futhark.Syntax.BinOp instance GHC.Classes.Eq Language.Futhark.Syntax.BinOp instance GHC.Show.Show Language.Futhark.Syntax.Value instance GHC.Classes.Eq Language.Futhark.Syntax.Value instance GHC.Show.Show Language.Futhark.Syntax.Diet instance GHC.Classes.Eq Language.Futhark.Syntax.Diet instance (GHC.Show.Show as, GHC.Show.Show dim) => GHC.Show.Show (Language.Futhark.Syntax.RecordArrayElemTypeBase dim as) instance (GHC.Classes.Eq as, GHC.Classes.Eq dim) => GHC.Classes.Eq (Language.Futhark.Syntax.RecordArrayElemTypeBase dim as) instance (GHC.Show.Show as, GHC.Show.Show dim) => GHC.Show.Show (Language.Futhark.Syntax.ArrayElemTypeBase dim as) instance (GHC.Classes.Eq as, GHC.Classes.Eq dim) => GHC.Classes.Eq (Language.Futhark.Syntax.ArrayElemTypeBase dim as) instance (GHC.Show.Show as, GHC.Show.Show dim) => GHC.Show.Show (Language.Futhark.Syntax.TypeBase dim as) instance (GHC.Show.Show dim, GHC.Show.Show as) => GHC.Show.Show (Language.Futhark.Syntax.TypeArg dim as) instance (GHC.Classes.Eq dim, GHC.Classes.Eq as) => GHC.Classes.Eq (Language.Futhark.Syntax.TypeArg dim as) instance GHC.Show.Show Language.Futhark.Syntax.TypeName instance GHC.Show.Show dim => GHC.Show.Show (Language.Futhark.Syntax.ShapeDecl dim) instance GHC.Classes.Ord dim => GHC.Classes.Ord (Language.Futhark.Syntax.ShapeDecl dim) instance GHC.Classes.Eq dim => GHC.Classes.Eq (Language.Futhark.Syntax.ShapeDecl dim) instance GHC.Show.Show Language.Futhark.Syntax.PrimValue instance GHC.Classes.Ord Language.Futhark.Syntax.PrimValue instance GHC.Classes.Eq Language.Futhark.Syntax.PrimValue instance GHC.Show.Show Language.Futhark.Syntax.PrimType instance GHC.Classes.Ord Language.Futhark.Syntax.PrimType instance GHC.Classes.Eq Language.Futhark.Syntax.PrimType instance GHC.Show.Show a => GHC.Show.Show (Language.Futhark.Syntax.Info a) instance GHC.Classes.Ord a => GHC.Classes.Ord (Language.Futhark.Syntax.Info a) instance GHC.Classes.Eq a => GHC.Classes.Eq (Language.Futhark.Syntax.Info a) instance GHC.Show.Show (Language.Futhark.Syntax.NoInfo a) instance GHC.Classes.Ord (Language.Futhark.Syntax.NoInfo a) instance GHC.Classes.Eq (Language.Futhark.Syntax.NoInfo a) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.TypeDeclBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.IdentBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.DimIndexBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.ExpBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.StreamForm f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.FieldBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.LoopFormBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.PatternBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.ValBindBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.TypeBindBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.SpecBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.SigExpBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.TypeRefBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.SigBindBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.ModExpBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.ModBindBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.ModParamBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.DecBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.ProgBase f vn) instance GHC.Show.Show vn => Language.Futhark.Syntax.Showable Language.Futhark.Syntax.NoInfo vn instance GHC.Show.Show vn => Language.Futhark.Syntax.Showable Language.Futhark.Syntax.Info vn instance Data.Loc.Located (Language.Futhark.Syntax.ModExpBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.ModBindBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.DecBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.ValBindBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.ExpBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.FieldBase f vn) instance GHC.Classes.Eq vn => GHC.Classes.Eq (Language.Futhark.Syntax.IdentBase ty vn) instance GHC.Classes.Ord vn => GHC.Classes.Ord (Language.Futhark.Syntax.IdentBase ty vn) instance Data.Loc.Located (Language.Futhark.Syntax.IdentBase ty vn) instance Data.Loc.Located (Language.Futhark.Syntax.PatternBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.ModParamBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.SigBindBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.SpecBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.SigExpBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.TypeRefBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.TypeBindBase f vn) instance GHC.Base.Functor Language.Futhark.Syntax.TypeParamBase instance Data.Foldable.Foldable Language.Futhark.Syntax.TypeParamBase instance Data.Traversable.Traversable Language.Futhark.Syntax.TypeParamBase instance Data.Loc.Located (Language.Futhark.Syntax.TypeParamBase vn) instance Data.Loc.Located Language.Futhark.Syntax.DocComment instance Data.Loc.Located (Language.Futhark.Syntax.TypeDeclBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.TypeExp vn) instance Data.Loc.Located (Language.Futhark.Syntax.TypeArgExp vn) instance GHC.Base.Functor Language.Futhark.Syntax.DimDecl instance Data.Foldable.Foldable Language.Futhark.Syntax.DimDecl instance Data.Traversable.Traversable Language.Futhark.Syntax.DimDecl instance (GHC.Classes.Eq vn, GHC.Classes.Ord vn) => Language.Futhark.Syntax.ArrayDim (Language.Futhark.Syntax.DimDecl vn) instance GHC.Base.Functor Language.Futhark.Syntax.QualName instance Data.Foldable.Foldable Language.Futhark.Syntax.QualName instance Data.Traversable.Traversable Language.Futhark.Syntax.QualName instance Data.Loc.Located a => Data.Loc.Located (Language.Futhark.Syntax.Inclusiveness a) instance GHC.Base.Functor Language.Futhark.Syntax.Inclusiveness instance Data.Foldable.Foldable Language.Futhark.Syntax.Inclusiveness instance Data.Traversable.Traversable Language.Futhark.Syntax.Inclusiveness instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Syntax.BinOp instance Data.Bitraversable.Bitraversable Language.Futhark.Syntax.RecordArrayElemTypeBase instance Data.Bifunctor.Bifunctor Language.Futhark.Syntax.RecordArrayElemTypeBase instance Data.Bifoldable.Bifoldable Language.Futhark.Syntax.RecordArrayElemTypeBase instance Data.Bitraversable.Bitraversable Language.Futhark.Syntax.ArrayElemTypeBase instance Data.Bifunctor.Bifunctor Language.Futhark.Syntax.ArrayElemTypeBase instance Data.Bifoldable.Bifoldable Language.Futhark.Syntax.ArrayElemTypeBase instance (GHC.Classes.Eq dim, GHC.Classes.Eq as) => GHC.Classes.Eq (Language.Futhark.Syntax.TypeBase dim as) instance Data.Bitraversable.Bitraversable Language.Futhark.Syntax.TypeBase instance Data.Bifunctor.Bifunctor Language.Futhark.Syntax.TypeBase instance Data.Bifoldable.Bifoldable Language.Futhark.Syntax.TypeBase instance Data.Bitraversable.Bitraversable Language.Futhark.Syntax.TypeArg instance Data.Bifunctor.Bifunctor Language.Futhark.Syntax.TypeArg instance Data.Bifoldable.Bifoldable Language.Futhark.Syntax.TypeArg instance GHC.Classes.Eq Language.Futhark.Syntax.TypeName instance GHC.Classes.Ord Language.Futhark.Syntax.TypeName instance Data.Foldable.Foldable Language.Futhark.Syntax.ShapeDecl instance Data.Traversable.Traversable Language.Futhark.Syntax.ShapeDecl instance GHC.Base.Functor Language.Futhark.Syntax.ShapeDecl instance GHC.Base.Semigroup (Language.Futhark.Syntax.ShapeDecl dim) instance GHC.Base.Monoid (Language.Futhark.Syntax.ShapeDecl dim) instance Language.Futhark.Syntax.ArrayDim () instance Language.Futhark.Syntax.IsPrimValue GHC.Types.Int instance Language.Futhark.Syntax.IsPrimValue GHC.Int.Int8 instance Language.Futhark.Syntax.IsPrimValue GHC.Int.Int16 instance Language.Futhark.Syntax.IsPrimValue GHC.Int.Int32 instance Language.Futhark.Syntax.IsPrimValue GHC.Int.Int64 instance Language.Futhark.Syntax.IsPrimValue GHC.Word.Word8 instance Language.Futhark.Syntax.IsPrimValue GHC.Word.Word16 instance Language.Futhark.Syntax.IsPrimValue GHC.Word.Word32 instance Language.Futhark.Syntax.IsPrimValue GHC.Word.Word64 instance Language.Futhark.Syntax.IsPrimValue GHC.Types.Float instance Language.Futhark.Syntax.IsPrimValue GHC.Types.Double instance Language.Futhark.Syntax.IsPrimValue GHC.Types.Bool instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Syntax.PrimType instance GHC.Base.Functor Language.Futhark.Syntax.Info instance Data.Foldable.Foldable Language.Futhark.Syntax.Info instance Data.Traversable.Traversable Language.Futhark.Syntax.Info instance GHC.Base.Functor Language.Futhark.Syntax.NoInfo instance Data.Foldable.Foldable Language.Futhark.Syntax.NoInfo instance Data.Traversable.Traversable Language.Futhark.Syntax.NoInfo -- | This module provides various simple ways to query and manipulate -- fundamental Futhark terms, such as types and values. The intent is to -- keep Futhark.Language.Syntax simple, and put whatever -- embellishments we need here. module Language.Futhark.Attributes -- | The nature of something predefined. These can either be monomorphic or -- overloaded. An overloaded builtin is a list valid types it can be -- instantiated with, to the parameter and result type, with -- Nothing representing the overloaded parameter type. data Intrinsic IntrinsicMonoFun :: [PrimType] -> PrimType -> Intrinsic IntrinsicOverloadedFun :: [PrimType] -> [Maybe PrimType] -> Maybe PrimType -> Intrinsic IntrinsicPolyFun :: [TypeParamBase VName] -> [TypeBase () ()] -> TypeBase () () -> Intrinsic IntrinsicType :: PrimType -> Intrinsic IntrinsicEquality :: Intrinsic IntrinsicOpaque :: Intrinsic -- | A map of all built-ins. intrinsics :: Map VName Intrinsic -- | The largest tag used by an intrinsic - this can be used to determine -- whether a VName refers to an intrinsic or a user-defined name. maxIntrinsicTag :: Int -- | Names of primitive types to types. This is only valid if no shadowing -- is going on, but useful for tools. namesToPrimTypes :: Map Name PrimType -- | Create a name with no qualifiers from a name. qualName :: v -> QualName v -- | Add another qualifier (at the head) to a qualified name. qualify :: v -> QualName v -> QualName v -- | Create a type name name with no qualifiers from a VName. typeName :: VName -> TypeName valueType :: Value -> TypeBase () () -- | Given an operator name, return the operator that determines its -- syntactical properties. leadingOperator :: Name -> BinOp -- | The modules imported by a Futhark program. progImports :: ProgBase f vn -> [(String, SrcLoc)] -- | The modules imported by a single declaration. decImports :: DecBase f vn -> [(String, SrcLoc)] -- | The set of module types used in any exported (non-local) declaration. progModuleTypes :: Ord vn => ProgBase f vn -> Set vn -- | Extract a leading ((name, namespace, file), remainder) from a -- documentation comment string. These are formatted as -- `name`@namespace[@file]. Let us hope that this pattern does not occur -- anywhere else. identifierReference :: String -> Maybe ((String, String, Maybe FilePath), String) -- | Find all the identifier references in a string. identifierReferences :: String -> [(String, String, Maybe FilePath)] -- | The type of an Futhark term. The aliasing will refer to itself, if the -- term is a non-tuple-typed variable. typeOf :: ExpBase Info VName -> CompType -- | The set of identifiers bound in a pattern. patIdentSet :: (Functor f, Ord vn) => PatternBase f vn -> Set (IdentBase f vn) -- | The type of values bound by the pattern. patternType :: PatternBase Info VName -> CompType -- | The type matched by the pattern, including shape declarations if -- present. patternStructType :: PatternBase Info VName -> StructType -- | When viewed as a function parameter, does this pattern correspond to a -- named parameter of some type? patternParam :: PatternBase Info VName -> (Maybe VName, StructType) -- | Remove all shape annotations from a pattern, leaving them unnamed -- instead. patternNoShapeAnnotations :: PatternBase Info VName -> PatternBase Info VName -- | patternOrderZero pat is True if all of the types in -- the given pattern have order 0. patternOrderZero :: PatternBase Info vn -> Bool -- | Extract all the shape names that occur in a given pattern. patternDimNames :: PatternBase Info VName -> Names -- | Return the uniqueness of a type. uniqueness :: TypeBase shape as -> Uniqueness -- | unique t is True if the type of the argument is -- unique. unique :: TypeBase shape as -> Bool recordArrayElemUniqueness :: RecordArrayElemTypeBase shape as -> Uniqueness -- | Return the set of all variables mentioned in the aliasing of a type. aliases :: Monoid as => TypeBase shape as -> as -- | diet t returns a description of how a function parameter of -- type t might consume its argument. diet :: TypeBase shape as -> Diet -- | Return the dimensionality of a type. For non-arrays, this is zero. For -- a one-dimensional array it is one, for a two-dimensional it is two, -- and so forth. arrayRank :: TypeBase dim as -> Int -- | Return any shape declarations in the type, with duplicates removed. nestedDims :: TypeBase (DimDecl VName) as -> [DimDecl VName] -- | The result of applying the arguments of the given types to a function -- with the given return type, consuming its parameters with the given -- diets. returnType :: TypeBase dim () -> [Diet] -> [CompType] -> TypeBase dim Names -- | Is the type concrete, i.e, without any type variables or function -- arrows? concreteType :: TypeBase f vn -> Bool -- | orderZero t is True if the argument type has order 0, -- i.e., it is not a function type, does not contain a function type as a -- subcomponent, and may not be instantiated with a function type. orderZero :: TypeBase dim as -> Bool -- | Extract the parameter types and return type from a type. If the type -- is not an arrow type, the list of parameter types is empty. unfoldFunType :: TypeBase dim as -> ([TypeBase dim as], TypeBase dim as) foldFunType :: Monoid as => [TypeBase dim as] -> TypeBase dim as -> TypeBase dim as -- | The type names mentioned in a type. typeVars :: Monoid as => TypeBase dim as -> Names -- | Extract all the shape names that occur in a given type. typeDimNames :: TypeBase (DimDecl VName) als -> Names -- | Construct a ShapeDecl with the given number of zero-information -- dimensions. rank :: Int -> ShapeDecl () -- | peelArray n t returns the type resulting from peeling the -- first n array dimensions from t. Returns -- Nothing if t has less than n dimensions. peelArray :: Int -> TypeBase dim as -> Maybe (TypeBase dim as) -- | stripArray n t removes the n outermost layers of the -- array. Essentially, it is the type of indexing an array of type -- t with n indexes. stripArray :: Monoid as => Int -> TypeBase dim as -> TypeBase dim as -- | arrayOf t s u constructs an array type. The convenience -- compared to using the Array constructor directly is that -- t can itself be an array. If t is an -- n-dimensional array, and s is a list of length -- n, the resulting type is of an n+m dimensions. The -- uniqueness of the new array will be u, no matter the -- uniqueness of t. The function returns Nothing in case -- an attempt is made to create an array of functions. arrayOf :: Monoid as => TypeBase dim as -> ShapeDecl dim -> Uniqueness -> Maybe (TypeBase dim as) arrayOfWithAliases :: Monoid as => TypeBase dim as -> as -> ShapeDecl dim -> Uniqueness -> Maybe (TypeBase dim as) -- | Convert any type to one that has rank information, no alias -- information, and no embedded names. toStructural :: TypeBase dim as -> TypeBase () () -- | Remove aliasing information from a type. toStruct :: TypeBase dim as -> TypeBase dim () -- | Replace no aliasing with an empty alias set. fromStruct :: TypeBase dim as -> TypeBase dim Names -- | t `setAliases` als returns t, but with als -- substituted for any already present aliasing. setAliases :: TypeBase dim asf -> ast -> TypeBase dim ast -- | t `addAliases` f returns t, but with any already -- present aliasing replaced by f applied to that aliasing. addAliases :: TypeBase dim asf -> (asf -> ast) -> TypeBase dim ast -- | Set the uniqueness attribute of a type. If the type is a tuple, the -- uniqueness of its components will be modified. setUniqueness :: TypeBase dim as -> Uniqueness -> TypeBase dim as -- | Change the size annotations of a type. modifyShapeAnnotations :: (oldshape -> newshape) -> TypeBase oldshape as -> TypeBase newshape as -- | Set the dimensions of an array. If the given type is not an array, -- return the type unchanged. setArrayShape :: TypeBase dim as -> ShapeDecl dim -> TypeBase dim as -- | Change the shape of a type to be just the Rank. removeShapeAnnotations :: TypeBase dim as -> TypeBase () as -- | Change all size annotations to be AnyDim. vacuousShapeAnnotations :: TypeBase dim as -> TypeBase (DimDecl vn) as typeToRecordArrayElem :: Monoid as => TypeBase dim as -> Maybe (RecordArrayElemTypeBase dim as) typeToRecordArrayElem' :: Monoid as => as -> TypeBase dim as -> Maybe (RecordArrayElemTypeBase dim as) recordArrayElemToType :: Monoid as => RecordArrayElemTypeBase dim as -> (TypeBase dim as, as) -- | Create a record type corresponding to a tuple with the given element -- types. tupleRecord :: [TypeBase dim as] -> TypeBase dim as isTupleRecord :: TypeBase dim as -> Maybe [TypeBase dim as] areTupleFields :: Map Name a -> Maybe [a] -- | Increasing field names for a tuple (starts at 1). tupleFieldNames :: [Name] -- | Sort fields by their name; taking care to sort numeric fields by their -- numeric value. This ensures that tuples and tuple-like records match. sortFields :: Map Name a -> [(Name, a)] isTypeParam :: TypeParamBase vn -> Bool -- | No information functor. Usually used for placeholder type- or aliasing -- information. data NoInfo a NoInfo :: NoInfo a -- | A type with no aliasing information but shape annotations. type UncheckedType = TypeBase (ShapeDecl Name) () type UncheckedTypeExp = TypeExp Name -- | An array element type with no aliasing information. type UncheckedArrayElemType = ArrayElemTypeBase (ShapeDecl Name) () -- | An identifier with no type annotations. type UncheckedIdent = IdentBase NoInfo Name -- | A type declaration with no expanded type. type UncheckedTypeDecl = TypeDeclBase NoInfo Name -- | An index with no type annotations. type UncheckedDimIndex = DimIndexBase NoInfo Name -- | An expression with no type annotations. type UncheckedExp = ExpBase NoInfo Name -- | A module expression with no type annotations. type UncheckedModExp = ModExpBase NoInfo Name -- | A module type expression with no type annotations. type UncheckedSigExp = SigExpBase NoInfo Name -- | A type parameter with no type annotations. type UncheckedTypeParam = TypeParamBase Name -- | A pattern with no type annotations. type UncheckedPattern = PatternBase NoInfo Name -- | A function declaration with no type annotations. type UncheckedValBind = ValBindBase NoInfo Name -- | A declaration with no type annotations. type UncheckedDec = DecBase NoInfo Name -- | A Futhark program with no type annotations. type UncheckedProg = ProgBase NoInfo Name -- | Futhark prettyprinter. This module defines Pretty instances for -- the AST defined in Language.Futhark.Syntax. module Language.Futhark.Pretty -- | Prettyprint a value, wrapped to 80 characters. pretty :: Pretty a => a -> String -- | Prettyprint a list enclosed in curly braces. prettyTuple :: Pretty a => [a] -> String -- | Given an operator name, return the operator that determines its -- syntactical properties. leadingOperator :: Name -> BinOp -- | A class for types that are variable names in the Futhark source -- language. This is used instead of a mere Pretty instance -- because in the compiler frontend we want to print VNames differently -- depending on whether the FUTHARK_COMPILER_DEBUGGING environment -- variable is set, yet in the backend we want to always print VNames -- with the tag. To avoid erroneously using the Pretty instance -- for VNames, we in fact only define it inside the modules for the core -- language (as an orphan instance). class IsName v pprName :: IsName v => v -> Doc prettyName :: IsName v => v -> String -- | Class for type constructors that represent annotations. Used in the -- prettyprinter to either print the original AST, or the computed -- attribute. class Annot f instance Language.Futhark.Pretty.Annot Language.Futhark.Syntax.NoInfo instance Language.Futhark.Pretty.Annot Language.Futhark.Syntax.Info instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.TypeDeclBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.DimIndexBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ExpBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.FieldBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.LoopFormBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.PatternBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ProgBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.DecBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ModExpBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.TypeBindBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ValBindBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.SpecBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.SigExpBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.SigBindBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ModParamBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ModBindBase f vn) instance Language.Futhark.Pretty.IsName Language.Futhark.Core.VName instance Language.Futhark.Pretty.IsName Language.Futhark.Core.Name instance Language.Futhark.Pretty.IsName vn => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.DimDecl vn) instance Language.Futhark.Pretty.IsName vn => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ShapeDecl (Language.Futhark.Syntax.DimDecl vn)) instance Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ShapeDecl dim) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.TypeBase dim as) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.TypeExp vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.TypeArgExp vn) instance Language.Futhark.Pretty.IsName vn => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.QualName vn) instance Language.Futhark.Pretty.IsName vn => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.IdentBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.TypeParamBase vn) instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Syntax.Value instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Syntax.PrimValue instance Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ShapeDecl ()) instance Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ShapeDecl dim) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.RecordArrayElemTypeBase dim as) instance Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ShapeDecl dim) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ArrayElemTypeBase dim as) instance Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ShapeDecl dim) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.TypeArg dim as) -- | Interface to the Futhark parser. module Language.Futhark.Parser -- | Parse an entire Futhark program from the given Text, using the -- FilePath as the source name for error messages. parseFuthark :: FilePath -> Text -> Either ParseError UncheckedProg -- | Parse an Futhark expression from the given String, using the -- FilePath as the source name for error messages. parseExp :: FilePath -> Text -> Either ParseError UncheckedExp -- | Parse an Futhark type from the given String, using the -- FilePath as the source name for error messages. parseType :: FilePath -> Text -> Either ParseError UncheckedTypeExp -- | Parse any Futhark value from the given String, using the -- FilePath as the source name for error messages. parseValue :: FilePath -> Text -> Either ParseError Value -- | Parse several Futhark values (separated by anything) from the given -- String, using the FilePath as the source name for error -- messages. parseValues :: FilePath -> Text -> Either ParseError [Value] -- | Parse either an expression or a declaration incrementally; favouring -- declarations in case of ambiguity. parseDecOrExpIncrM :: Monad m => m Text -> FilePath -> Text -> m (Either ParseError (Either UncheckedDec UncheckedExp)) -- | A parse error. Use show to get a human-readable description. data ParseError ParseError :: String -> ParseError scanTokensText :: Pos -> Text -> Either String ([L Token], Pos) -- | A value tagged with a source location. data L a L :: SrcLoc -> a -> L a -- | A lexical token. It does not itself contain position information, so -- in practice the parser will consume tokens tagged with a source -- position. data Token ID :: Name -> Token INDEXING :: Name -> Token QUALINDEXING :: [Name] -> Name -> Token QUALPAREN :: [Name] -> Name -> Token UNOP :: Name -> Token QUALUNOP :: [Name] -> Name -> Token SYMBOL :: BinOp -> [Name] -> Name -> Token INTLIT :: Integer -> Token STRINGLIT :: String -> Token I8LIT :: Int8 -> Token I16LIT :: Int16 -> Token I32LIT :: Int32 -> Token I64LIT :: Int64 -> Token U8LIT :: Word8 -> Token U16LIT :: Word16 -> Token U32LIT :: Word32 -> Token U64LIT :: Word64 -> Token FLOATLIT :: Double -> Token F32LIT :: Float -> Token F64LIT :: Double -> Token CHARLIT :: Char -> Token COLON :: Token BACKSLASH :: Token APOSTROPHE :: Token APOSTROPHE_THEN_HAT :: Token BACKTICK :: Token HASH :: Token DOT :: Token TWO_DOTS :: Token TWO_DOTS_LT :: Token TWO_DOTS_GT :: Token THREE_DOTS :: Token LPAR :: Token RPAR :: Token RPAR_THEN_LBRACKET :: Token LBRACKET :: Token RBRACKET :: Token LCURLY :: Token RCURLY :: Token COMMA :: Token UNDERSCORE :: Token RIGHT_ARROW :: Token LEFT_ARROW :: Token EQU :: Token ASTERISK :: Token NEGATE :: Token LTH :: Token HAT :: Token IF :: Token THEN :: Token ELSE :: Token LET :: Token LOOP :: Token IN :: Token FOR :: Token DO :: Token WITH :: Token UNSAFE :: Token ASSERT :: Token TRUE :: Token FALSE :: Token WHILE :: Token INCLUDE :: Token IMPORT :: Token ENTRY :: Token TYPE :: Token MODULE :: Token VAL :: Token OPEN :: Token LOCAL :: Token DOC :: String -> Token EOF :: Token -- | Re-export the external Futhark modules for convenience. module Language.Futhark -- | An identifier with type- and aliasing information. type Ident = IdentBase Info VName -- | An index with type information. type DimIndex = DimIndexBase Info VName -- | An expression with type information. type Exp = ExpBase Info VName -- | A pattern with type information. type Pattern = PatternBase Info VName -- | A type-checked module expression. type ModExp = ModExpBase Info VName -- | A type-checked module parameter. type ModParam = ModParamBase Info VName -- | A type-checked module type expression. type SigExp = SigExpBase Info VName -- | A type-checked module binding. type ModBind = ModBindBase Info VName -- | A type-checked module type binding. type SigBind = SigBindBase Info VName -- | An constant declaration with type information. type ValBind = ValBindBase Info VName -- | A type-checked declaration. type Dec = DecBase Info VName -- | A type-checked specification. type Spec = SpecBase Info VName -- | An Futhark program with type information. type Prog = ProgBase Info VName -- | A type binding with type information. type TypeBind = TypeBindBase Info VName -- | A type declaration with type information type TypeDecl = TypeDeclBase Info VName -- | A known type arg with shape annotations but no aliasing information. type StructTypeArg = TypeArg (DimDecl VName) () -- | A known array element type with no shape annotations, but aliasing -- information. type ArrayElemType = ArrayElemTypeBase () Names -- | A type-checked type parameter. type TypeParam = TypeParamBase VName -- | Definitions of various semantic objects (*not* the Futhark semantics -- themselves). module Language.Futhark.Semantic -- | Canonical reference to a Futhark code file. Does not include the -- .fut extension. This is most often a path relative to the -- current working directory of the compiler. data ImportName -- | Create an import name immediately from a file path specified by the -- user. mkInitialImport :: FilePath -> ImportName -- | We resolve '..' paths here and assume that no shenanigans are going on -- with symbolic links. If there is, too bad. Don't do that. mkImportFrom :: ImportName -> String -> SrcLoc -> ImportName -- | Create a .fut file corresponding to an ImportName. includeToFilePath :: ImportName -> FilePath -- | Produce a human-readable canonicalized string from an -- ImportName. includeToString :: ImportName -> String -- | The result of type checking some file. Can be passed to further -- invocations of the type checker. data FileModule FileModule :: TySet -> Env -> Prog -> FileModule -- | Abstract types. [fileAbs] :: FileModule -> TySet [fileEnv] :: FileModule -> Env [fileProg] :: FileModule -> Prog -- | A mapping from import names to imports. The ordering is significant. type Imports = [(String, FileModule)] -- | The space inhabited by a name. data Namespace -- | Functions and values. Term :: Namespace Type :: Namespace Signature :: Namespace -- | Modules produces environment with this representation. data Env Env :: Map VName BoundV -> Map VName TypeBinding -> Map VName MTy -> Map VName Mod -> NameMap -> Env [envVtable] :: Env -> Map VName BoundV [envTypeTable] :: Env -> Map VName TypeBinding [envSigTable] :: Env -> Map VName MTy [envModTable] :: Env -> Map VName Mod [envNameMap] :: Env -> NameMap -- | A mapping of abstract types to their liftedness. type TySet = Map (QualName VName) Liftedness -- | A parametric functor consists of a set of abstract types, the -- environment of its parameter, and the resulting module type. data FunSig FunSig :: TySet -> Mod -> MTy -> FunSig [funSigAbs] :: FunSig -> TySet [funSigMod] :: FunSig -> Mod [funSigMty] :: FunSig -> MTy type NameMap = Map (Namespace, Name) (QualName VName) -- | Type parameters, list of parameter types (optinally named), and return -- type. The type parameters are in scope in both parameter types and the -- return type. Non-functional values have only a return type. data BoundV BoundV :: [TypeParam] -> StructType -> BoundV -- | Representation of a module, which is either a plain environment, or a -- parametric module ("functor" in SML). data Mod ModEnv :: Env -> Mod ModFun :: FunSig -> Mod -- | A binding from a name to its definition as a type. data TypeBinding TypeAbbr :: Liftedness -> [TypeParam] -> StructType -> TypeBinding -- | Representation of a module type. data MTy MTy :: TySet -> Mod -> MTy -- | Abstract types in the module type. [mtyAbs] :: MTy -> TySet [mtyMod] :: MTy -> Mod instance GHC.Show.Show Language.Futhark.Semantic.FunSig instance GHC.Show.Show Language.Futhark.Semantic.Mod instance GHC.Show.Show Language.Futhark.Semantic.MTy instance GHC.Show.Show Language.Futhark.Semantic.Env instance GHC.Show.Show Language.Futhark.Semantic.BoundV instance GHC.Show.Show Language.Futhark.Semantic.TypeBinding instance GHC.Classes.Eq Language.Futhark.Semantic.TypeBinding instance GHC.Enum.Enum Language.Futhark.Semantic.Namespace instance GHC.Show.Show Language.Futhark.Semantic.Namespace instance GHC.Classes.Ord Language.Futhark.Semantic.Namespace instance GHC.Classes.Eq Language.Futhark.Semantic.Namespace instance GHC.Show.Show Language.Futhark.Semantic.ImportName instance GHC.Classes.Ord Language.Futhark.Semantic.ImportName instance GHC.Classes.Eq Language.Futhark.Semantic.ImportName instance GHC.Base.Semigroup Language.Futhark.Semantic.Env instance GHC.Base.Monoid Language.Futhark.Semantic.Env instance Data.Loc.Located Language.Futhark.Semantic.ImportName module Language.Futhark.Interpreter data Ctx Ctx :: Env -> Map FilePath Env -> Ctx [ctxEnv] :: Ctx -> Env [ctxImports] :: Ctx -> Map FilePath Env data Env Env :: Map VName TermBinding -> Map VName TypeBinding -> Env [envTerm] :: Env -> Map VName TermBinding [envType] :: Env -> Map VName TypeBinding data InterpreterError -- | The initial environment contains definitions of the various intrinsic -- functions. initialCtx :: Ctx interpretExp :: Ctx -> Exp -> F ExtOp Value interpretDec :: Ctx -> Dec -> F ExtOp Ctx interpretImport :: Ctx -> (FilePath, Prog) -> F ExtOp Ctx -- | Execute the named function on the given arguments; will fail horribly -- if these are ill-typed. interpretFunction :: Ctx -> VName -> [Value] -> F ExtOp Value data ExtOp a ExtOpTrace :: SrcLoc -> String -> a -> ExtOp a ExtOpBreak :: [SrcLoc] -> Ctx -> Env -> a -> ExtOp a ExtOpError :: InterpreterError -> ExtOp a typeEnv :: Env -> Env -- | A fully evaluated Futhark value. data Value ValuePrim :: !PrimValue -> Value ValueArray :: !Array Int Value -> Value ValueRecord :: Map Name Value -> Value -- | Create an array value; failing if that would result in an irregular -- array. mkArray :: [Value] -> Maybe Value fromTuple :: Value -> Maybe [Value] isEmptyArray :: Value -> Bool instance Control.Monad.Reader.Class.MonadReader (Language.Futhark.Interpreter.Stack, Data.Map.Internal.Map GHC.IO.FilePath Language.Futhark.Interpreter.Env) Language.Futhark.Interpreter.EvalM instance Control.Monad.Free.Class.MonadFree Language.Futhark.Interpreter.ExtOp Language.Futhark.Interpreter.EvalM instance GHC.Base.Functor Language.Futhark.Interpreter.EvalM instance GHC.Base.Applicative Language.Futhark.Interpreter.EvalM instance GHC.Base.Monad Language.Futhark.Interpreter.EvalM instance GHC.Show.Show Language.Futhark.Interpreter.Shape instance GHC.Classes.Eq Language.Futhark.Interpreter.Shape instance GHC.Base.Functor Language.Futhark.Interpreter.ExtOp instance Control.Monad.Fail.MonadFail Language.Futhark.Interpreter.EvalM instance GHC.Classes.Eq Language.Futhark.Interpreter.Value instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Interpreter.Value instance GHC.Base.Monoid Language.Futhark.Interpreter.Env instance GHC.Base.Semigroup Language.Futhark.Interpreter.Env instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Interpreter.Indexing instance GHC.Show.Show Language.Futhark.Interpreter.InterpreterError instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Interpreter.Shape module Futhark.Internalise.TypesValues -- | The names that are bound for some types, either implicitly or -- explicitly. data BoundInTypes -- | Determine the names bound for some types. boundInTypes :: [TypeParam] -> BoundInTypes internaliseReturnType :: TypeBase (DimDecl VName) () -> InternaliseM ([TypeBase ExtShape Uniqueness], ConstParams) -- | As internaliseReturnType, but returns components of a top-level -- tuple type piecemeal. internaliseEntryReturnType :: TypeBase (DimDecl VName) () -> InternaliseM ([[TypeBase ExtShape Uniqueness]], ConstParams) internaliseParamTypes :: BoundInTypes -> Map VName VName -> [TypeBase (DimDecl VName) ()] -> InternaliseM ([[TypeBase ExtShape Uniqueness]], ConstParams) internaliseType :: TypeBase () () -> InternaliseM [TypeBase ExtShape Uniqueness] -- | Convert an external primitive to an internal primitive. internalisePrimType :: PrimType -> PrimType -- | How many core language values are needed to represent one source -- language value of the given type? internalisedTypeSize :: TypeBase dim () -> InternaliseM Int -- | Convert an external primitive value to an internal primitive value. internalisePrimValue :: PrimValue -> PrimValue instance GHC.Base.Monoid Futhark.Internalise.TypesValues.BoundInTypes instance GHC.Base.Semigroup Futhark.Internalise.TypesValues.BoundInTypes module Futhark.Internalise.Lambdas -- | A function for internalising lambdas. type InternaliseLambda = Exp -> [Type] -> InternaliseM ([LParam], Body, [ExtType]) internaliseMapLambda :: InternaliseLambda -> Exp -> [SubExp] -> InternaliseM Lambda internaliseStreamMapLambda :: InternaliseLambda -> Exp -> [SubExp] -> InternaliseM Lambda internaliseFoldLambda :: InternaliseLambda -> Exp -> [Type] -> [Type] -> InternaliseM Lambda internaliseStreamLambda :: InternaliseLambda -> Exp -> [Type] -> InternaliseM ([LParam], Body) internalisePartitionLambda :: InternaliseLambda -> Int -> Exp -> [SubExp] -> InternaliseM Lambda -- | Defunctionalization of typed, monomorphic Futhark programs without -- modules. module Futhark.Internalise.Defunctionalise -- | Transform a list of top-level value bindings. May produce new lifted -- function definitions, which are placed in front of the resulting list -- of declarations. transformProg :: MonadFreshNames m => [ValBind] -> m [ValBind] instance Futhark.MonadFreshNames.MonadFreshNames Futhark.Internalise.Defunctionalise.DefM instance Control.Monad.Writer.Class.MonadWriter (Data.Sequence.Internal.Seq Language.Futhark.ValBind) Futhark.Internalise.Defunctionalise.DefM instance Control.Monad.Reader.Class.MonadReader (Language.Futhark.Syntax.Names, Futhark.Internalise.Defunctionalise.Env) Futhark.Internalise.Defunctionalise.DefM instance GHC.Base.Monad Futhark.Internalise.Defunctionalise.DefM instance GHC.Base.Applicative Futhark.Internalise.Defunctionalise.DefM instance GHC.Base.Functor Futhark.Internalise.Defunctionalise.DefM instance GHC.Show.Show Futhark.Internalise.Defunctionalise.StaticVal instance GHC.Base.Semigroup Futhark.Internalise.Defunctionalise.NameSet instance GHC.Base.Monoid Futhark.Internalise.Defunctionalise.NameSet module Futhark.Internalise.Bindings bindingParams :: [TypeParam] -> [Pattern] -> (ConstParams -> [FParam] -> [[FParam]] -> InternaliseM a) -> InternaliseM a bindingLambdaParams :: [TypeParam] -> [Pattern] -> [Type] -> (ConstParams -> [LParam] -> InternaliseM a) -> InternaliseM a stmPattern :: [TypeParam] -> Pattern -> [ExtType] -> (ConstParams -> [VName] -> MatchPattern -> InternaliseM a) -> InternaliseM a type MatchPattern = SrcLoc -> [SubExp] -> InternaliseM [SubExp] module Futhark.Doc.Html primTypeHtml :: PrimType -> Html prettyTypeName :: TypeName -> Html prettyU :: Uniqueness -> Html renderName :: Name -> Html joinBy :: Html -> [Html] -> Html commas :: [Html] -> Html brackets :: Html -> Html braces :: Html -> Html parens :: Html -> Html -- | This module defines an efficient value representation as well as -- parsing and comparison functions. This is because the standard Futhark -- parser is not able to cope with large values (like arrays that are -- tens of megabytes in size). The representation defined here does not -- support tuples, so don't use those as input/output for your test -- programs. module Futhark.Test.Values -- | An efficiently represented Futhark value. Use pretty to get a -- human-readable representation, and the instances of Get and -- Put to obtain binary representations data Value -- | A textual description of the type of a value. Follows Futhark type -- notation, and contains the exact dimension sizes if an array. valueType :: Value -> String -- | Parse Futhark values from the given bytestring. readValues :: ByteString -> Maybe [Value] -- | Compare two sets of Futhark values for equality. Shapes and types must -- also match. compareValues :: [Value] -> [Value] -> Maybe [Mismatch] -- | Two values differ in some way. data Mismatch -- | A human-readable description of how two values are not the same. explainMismatch :: (Show i, Pretty a) => i -> String -> a -> a -> String instance GHC.Show.Show Futhark.Test.Values.Value instance GHC.Show.Show Futhark.Test.Values.Mismatch instance Data.Binary.Class.Binary Futhark.Test.Values.Value instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Test.Values.Value -- | Facilities for reading Futhark test programs. A Futhark test program -- is an ordinary Futhark program where an initial comment block -- specifies input- and output-sets. module Futhark.Test -- | Read the test specification from the given Futhark program. Note: will -- call error on parse errors. testSpecFromFile :: FilePath -> IO ProgramTest -- | Read test specifications from the given paths, which can be a files or -- directories containing .fut files and further directories. -- Calls error on parse errors, or if any of the immediately -- passed path names do not name a file that exists. testSpecsFromPaths :: [FilePath] -> IO [(FilePath, ProgramTest)] -- | Try to parse a several values from a byte string. The String -- parameter is used for error messages. valuesFromByteString :: String -> ByteString -> Either String [Value] -- | Get the actual core Futhark values corresponding to a Values -- specification. The FilePath is the directory which file paths -- are read relative to. getValues :: MonadIO m => FilePath -> Values -> m [Value] -- | Extract a pretty representation of some Values. In the IO monad -- because this might involve reading from a file. There is no guarantee -- that the resulting byte string yields a readable value. getValuesBS :: MonadIO m => FilePath -> Values -> m ByteString -- | Compare two sets of Futhark values for equality. Shapes and types must -- also match. compareValues :: [Value] -> [Value] -> Maybe [Mismatch] -- | Two values differ in some way. data Mismatch -- | Description of a test to be carried out on a Futhark program. The -- Futhark program is stored separately. data ProgramTest ProgramTest :: Text -> [Text] -> TestAction -> ProgramTest [testDescription] :: ProgramTest -> Text [testTags] :: ProgramTest -> [Text] [testAction] :: ProgramTest -> TestAction -- | A structure test specifies a compilation pipeline, as well as metrics -- for the program coming out the other end. data StructureTest StructureTest :: StructurePipeline -> AstMetrics -> StructureTest -- | How a program can be transformed. data StructurePipeline KernelsPipeline :: StructurePipeline SOACSPipeline :: StructurePipeline SequentialCpuPipeline :: StructurePipeline GpuPipeline :: StructurePipeline -- | A warning test requires that a warning matching the regular expression -- is produced. The program must also compile succesfully. data WarningTest ExpectedWarning :: Text -> Regex -> WarningTest -- | How to test a program. data TestAction CompileTimeFailure :: ExpectedError -> TestAction RunCases :: [InputOutputs] -> [StructureTest] -> [WarningTest] -> TestAction -- | The error expected for a negative test. data ExpectedError AnyError :: ExpectedError ThisError :: Text -> Regex -> ExpectedError -- | Input and output pairs for some entry point(s). data InputOutputs InputOutputs :: Text -> [TestRun] -> InputOutputs [iosEntryPoint] :: InputOutputs -> Text [iosTestRuns] :: InputOutputs -> [TestRun] -- | A condition for execution, input, and expected result. data TestRun TestRun :: [String] -> Values -> ExpectedResult Values -> Int -> String -> TestRun [runTags] :: TestRun -> [String] [runInput] :: TestRun -> Values [runExpectedResult] :: TestRun -> ExpectedResult Values [runIndex] :: TestRun -> Int [runDescription] :: TestRun -> String -- | How a test case is expected to terminate. data ExpectedResult values -- | Execution suceeds, with or without expected result values. Succeeds :: Maybe values -> ExpectedResult values -- | Execution fails with this error. RunTimeFailure :: ExpectedError -> ExpectedResult values -- | Several Values - either literally, or by reference to a file. data Values Values :: [Value] -> Values InFile :: FilePath -> Values -- | An efficiently represented Futhark value. Use pretty to get a -- human-readable representation, and the instances of Get and -- Put to obtain binary representations data Value instance GHC.Show.Show Futhark.Test.ProgramTest instance GHC.Show.Show Futhark.Test.TestAction instance GHC.Show.Show Futhark.Test.InputOutputs instance GHC.Show.Show Futhark.Test.TestRun instance GHC.Show.Show values => GHC.Show.Show (Futhark.Test.ExpectedResult values) instance GHC.Show.Show Futhark.Test.Values instance GHC.Show.Show Futhark.Test.StructureTest instance GHC.Show.Show Futhark.Test.StructurePipeline instance GHC.Show.Show Futhark.Test.WarningTest instance GHC.Show.Show Futhark.Test.ExpectedError -- | Functions for generic traversals across Futhark syntax trees. The -- motivation for this module came from dissatisfaction with rewriting -- the same trivial tree recursions for every module. A possible -- alternative would be to use normal "Scrap your -- boilerplate"-techniques, but these are rejected for two reasons: -- --