We now make a show function for all default datatypes.
[matthijs/master-project/cλash.git] / cλash / CLasH / VHDL / Generate.hs
1 {-# LANGUAGE PackageImports #-}
2
3 module CLasH.VHDL.Generate where
4
5 -- Standard modules
6 import qualified Control.Monad as Monad
7 import qualified Data.Map as Map
8 import qualified Maybe
9 import qualified Data.Either as Either
10 import qualified Control.Monad.Trans.State as State
11 import qualified "transformers" Control.Monad.Identity as Identity
12 import Data.Accessor
13 import Data.Accessor.MonadState as MonadState
14 import Debug.Trace
15
16 -- ForSyDe
17 import qualified Language.VHDL.AST as AST
18
19 -- GHC API
20 import CoreSyn
21 import Type
22 import qualified Var
23 import qualified IdInfo
24 import qualified Literal
25 import qualified Name
26 import qualified TyCon
27
28 -- Local imports
29 import CLasH.VHDL.Constants
30 import CLasH.VHDL.VHDLTypes
31 import CLasH.VHDL.VHDLTools
32 import CLasH.Utils.Core.CoreTools
33 import CLasH.Utils.Pretty
34
35 -----------------------------------------------------------------------------
36 -- Functions to generate VHDL for builtin functions
37 -----------------------------------------------------------------------------
38
39 -- | A function to wrap a builder-like function that expects its arguments to
40 -- be expressions.
41 genExprArgs wrap dst func args = do
42   args' <- eitherCoreOrExprArgs args
43   wrap dst func args'
44
45 eitherCoreOrExprArgs :: [Either CoreSyn.CoreExpr AST.Expr] -> VHDLSession [AST.Expr]
46 eitherCoreOrExprArgs args = mapM (Either.either ((MonadState.lift vsType) . varToVHDLExpr . exprToVar) return) args
47
48 -- | A function to wrap a builder-like function that expects its arguments to
49 -- be variables.
50 genVarArgs ::
51   (dst -> func -> [Var.Var] -> res)
52   -> (dst -> func -> [Either CoreSyn.CoreExpr AST.Expr] -> res)
53 genVarArgs wrap dst func args = wrap dst func args'
54   where
55     args' = map exprToVar exprargs
56     -- Check (rather crudely) that all arguments are CoreExprs
57     (exprargs, []) = Either.partitionEithers args
58
59 -- | A function to wrap a builder-like function that expects its arguments to
60 -- be Literals
61 genLitArgs ::
62   (dst -> func -> [Literal.Literal] -> res)
63   -> (dst -> func -> [Either CoreSyn.CoreExpr AST.Expr] -> res)
64 genLitArgs wrap dst func args = wrap dst func args'
65   where
66     args' = map exprToLit litargs
67     -- FIXME: Check if we were passed an CoreSyn.App
68     litargs = concat (map getLiterals exprargs)
69     (exprargs, []) = Either.partitionEithers args
70
71 -- | A function to wrap a builder-like function that produces an expression
72 -- and expects it to be assigned to the destination.
73 genExprRes ::
74   ((Either CoreSyn.CoreBndr AST.VHDLName) -> func -> [arg] -> VHDLSession AST.Expr)
75   -> ((Either CoreSyn.CoreBndr AST.VHDLName) -> func -> [arg] -> VHDLSession [AST.ConcSm])
76 genExprRes wrap dst func args = do
77   expr <- wrap dst func args
78   return $ [mkUncondAssign dst expr]
79
80 -- | Generate a binary operator application. The first argument should be a
81 -- constructor from the AST.Expr type, e.g. AST.And.
82 genOperator2 :: (AST.Expr -> AST.Expr -> AST.Expr) -> BuiltinBuilder 
83 genOperator2 op = genExprArgs $ genExprRes (genOperator2' op)
84 genOperator2' :: (AST.Expr -> AST.Expr -> AST.Expr) -> dst -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
85 genOperator2' op _ f [arg1, arg2] = return $ op arg1 arg2
86
87 -- | Generate a unary operator application
88 genOperator1 :: (AST.Expr -> AST.Expr) -> BuiltinBuilder 
89 genOperator1 op = genExprArgs $ genExprRes (genOperator1' op)
90 genOperator1' :: (AST.Expr -> AST.Expr) -> dst -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
91 genOperator1' op _ f [arg] = return $ op arg
92
93 -- | Generate a unary operator application
94 genNegation :: BuiltinBuilder 
95 genNegation = genVarArgs $ genExprRes genNegation'
96 genNegation' :: dst -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession AST.Expr
97 genNegation' _ f [arg] = do
98   arg1 <- MonadState.lift vsType $ varToVHDLExpr arg
99   let ty = Var.varType arg
100   let (tycon, args) = Type.splitTyConApp ty
101   let name = Name.getOccString (TyCon.tyConName tycon)
102   case name of
103     "SizedInt" -> return $ AST.Neg arg1
104     otherwise -> error $ "\nGenerate.genNegation': Negation allowed for type: " ++ show name 
105
106 -- | Generate a function call from the destination binder, function name and a
107 -- list of expressions (its arguments)
108 genFCall :: Bool -> BuiltinBuilder 
109 genFCall switch = genExprArgs $ genExprRes (genFCall' switch)
110 genFCall' :: Bool -> Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
111 genFCall' switch (Left res) f args = do
112   let fname = varToString f
113   let el_ty = if switch then (Var.varType res) else ((tfvec_elem . Var.varType) res)
114   id <- MonadState.lift vsType $ vectorFunId el_ty fname
115   return $ AST.PrimFCall $ AST.FCall (AST.NSimple id)  $
116              map (\exp -> Nothing AST.:=>: AST.ADExpr exp) args
117 genFCall' _ (Right name) _ _ = error $ "\nGenerate.genFCall': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
118
119 genFromSizedWord :: BuiltinBuilder
120 genFromSizedWord = genExprArgs $ genExprRes genFromSizedWord'
121 genFromSizedWord' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
122 genFromSizedWord' (Left res) f args = do
123   let fname = varToString f
124   return $ AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLBasicId toIntegerId))  $
125              map (\exp -> Nothing AST.:=>: AST.ADExpr exp) args
126 genFromSizedWord' (Right name) _ _ = error $ "\nGenerate.genFromSizedWord': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
127
128 genResize :: BuiltinBuilder
129 genResize = genExprArgs $ genExprRes genResize'
130 genResize' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
131 genResize' (Left res) f [arg] = do {
132   ; let { ty = Var.varType res
133         ; (tycon, args) = Type.splitTyConApp ty
134         ; name = Name.getOccString (TyCon.tyConName tycon)
135         } ;
136   ; len <- case name of
137       "SizedInt" -> MonadState.lift vsType $ tfp_to_int (sized_int_len_ty ty)
138       "SizedWord" -> MonadState.lift vsType $ tfp_to_int (sized_word_len_ty ty)
139   ; return $ AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLBasicId resizeId))
140              [Nothing AST.:=>: AST.ADExpr arg, Nothing AST.:=>: AST.ADExpr( AST.PrimLit (show len))]
141   }
142 genResize' (Right name) _ _ = error $ "\nGenerate.genFromSizedWord': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
143
144 -- FIXME: I'm calling genLitArgs which is very specific function,
145 -- which needs to be fixed as well
146 genFromInteger :: BuiltinBuilder
147 genFromInteger = genLitArgs $ genExprRes genFromInteger'
148 genFromInteger' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [Literal.Literal] -> VHDLSession AST.Expr
149 genFromInteger' (Left res) f lits = do {
150   ; let { ty = Var.varType res
151         ; (tycon, args) = Type.splitTyConApp ty
152         ; name = Name.getOccString (TyCon.tyConName tycon)
153         } ;
154   ; len <- case name of
155     "SizedInt" -> MonadState.lift vsType $ tfp_to_int (sized_int_len_ty ty)
156     "SizedWord" -> MonadState.lift vsType $ tfp_to_int (sized_word_len_ty ty)
157   ; let fname = case name of "SizedInt" -> toSignedId ; "SizedWord" -> toUnsignedId
158   ; return $ AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLBasicId fname)) 
159             [Nothing AST.:=>: AST.ADExpr (AST.PrimLit (show (last lits))), Nothing AST.:=>: AST.ADExpr( AST.PrimLit (show len))]
160   }
161
162 genFromInteger' (Right name) _ _ = error $ "\nGenerate.genFromInteger': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
163
164
165 -- | Generate a generate statement for the builtin function "map"
166 genMap :: BuiltinBuilder
167 genMap (Left res) f [Left mapped_f, Left (Var arg)] = do {
168   -- mapped_f must be a CoreExpr (since we can't represent functions as VHDL
169   -- expressions). arg must be a CoreExpr (and should be a CoreSyn.Var), since
170   -- we must index it (which we couldn't if it was a VHDL Expr, since only
171   -- VHDLNames can be indexed).
172   -- Setup the generate scheme
173   ; len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) res
174           -- TODO: Use something better than varToString
175   ; let { label       = mkVHDLExtId ("mapVector" ++ (varToString res))
176         ; n_id        = mkVHDLBasicId "n"
177         ; n_expr      = idToVHDLExpr n_id
178         ; range       = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
179         ; genScheme   = AST.ForGn n_id range
180           -- Create the content of the generate statement: Applying the mapped_f to
181           -- each of the elements in arg, storing to each element in res
182         ; resname     = mkIndexedName (varToVHDLName res) n_expr
183         ; argexpr     = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg) n_expr
184         ; (CoreSyn.Var real_f, already_mapped_args) = CoreSyn.collectArgs mapped_f
185         ; valargs = get_val_args (Var.varType real_f) already_mapped_args
186         } ;
187   ; app_concsms <- genApplication (Right resname) real_f (map Left valargs ++ [Right argexpr])
188     -- Return the generate statement
189   ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms]
190   }
191
192 genMap' (Right name) _ _ = error $ "\nGenerate.genMap': Cannot generate map function call assigned to a VHDLName: " ++ show name
193     
194 genZipWith :: BuiltinBuilder
195 genZipWith = genVarArgs genZipWith'
196 genZipWith' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
197 genZipWith' (Left res) f args@[zipped_f, arg1, arg2] = do {
198   -- Setup the generate scheme
199   ; len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) res
200           -- TODO: Use something better than varToString
201   ; let { label       = mkVHDLExtId ("zipWithVector" ++ (varToString res))
202         ; n_id        = mkVHDLBasicId "n"
203         ; n_expr      = idToVHDLExpr n_id
204         ; range       = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
205         ; genScheme   = AST.ForGn n_id range
206           -- Create the content of the generate statement: Applying the zipped_f to
207           -- each of the elements in arg1 and arg2, storing to each element in res
208         ; resname     = mkIndexedName (varToVHDLName res) n_expr
209         ; argexpr1    = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg1) n_expr
210         ; argexpr2    = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg2) n_expr
211         } ;
212   ; app_concsms <- genApplication (Right resname) zipped_f [Right argexpr1, Right argexpr2]
213     -- Return the generate functions
214   ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms]
215   }
216
217 genFoldl :: BuiltinBuilder
218 genFoldl = genFold True
219
220 genFoldr :: BuiltinBuilder
221 genFoldr = genFold False
222
223 genFold :: Bool -> BuiltinBuilder
224 genFold left = genVarArgs (genFold' left)
225
226 genFold' :: Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
227 genFold' left res f args@[folded_f , start ,vec]= do
228   len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty (Var.varType vec))
229   genFold'' len left res f args
230
231 genFold'' :: Int -> Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
232 -- Special case for an empty input vector, just assign start to res
233 genFold'' len left (Left res) _ [_, start, vec] | len == 0 = do
234   arg <- MonadState.lift vsType $ varToVHDLExpr start
235   return [mkUncondAssign (Left res) arg]
236     
237 genFold'' len left (Left res) f [folded_f, start, vec] = do
238   -- The vector length
239   --len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) vec
240   -- An expression for len-1
241   let len_min_expr = (AST.PrimLit $ show (len-1))
242   -- evec is (TFVec n), so it still needs an element type
243   let (nvec, _) = splitAppTy (Var.varType vec)
244   -- Put the type of the start value in nvec, this will be the type of our
245   -- temporary vector
246   let tmp_ty = Type.mkAppTy nvec (Var.varType start)
247   let error_msg = "\nGenerate.genFold': Can not construct temp vector for element type: " ++ pprString tmp_ty 
248   tmp_vhdl_ty <- MonadState.lift vsType $ vhdl_ty error_msg tmp_ty
249   -- Setup the generate scheme
250   let gen_label = mkVHDLExtId ("foldlVector" ++ (varToString vec))
251   let block_label = mkVHDLExtId ("foldlVector" ++ (varToString res))
252   let gen_range = if left then AST.ToRange (AST.PrimLit "0") len_min_expr
253                   else AST.DownRange len_min_expr (AST.PrimLit "0")
254   let gen_scheme   = AST.ForGn n_id gen_range
255   -- Make the intermediate vector
256   let  tmp_dec     = AST.BDISD $ AST.SigDec tmp_id tmp_vhdl_ty Nothing
257   -- Create the generate statement
258   cells <- sequence [genFirstCell, genOtherCell]
259   let gen_sm = AST.GenerateSm gen_label gen_scheme [] (map AST.CSGSm cells)
260   -- Assign tmp[len-1] or tmp[0] to res
261   let out_assign = mkUncondAssign (Left res) $ vhdlNameToVHDLExpr (if left then
262                     (mkIndexedName tmp_name (AST.PrimLit $ show (len-1))) else
263                     (mkIndexedName tmp_name (AST.PrimLit "0")))      
264   let block = AST.BlockSm block_label [] (AST.PMapAspect []) [tmp_dec] [AST.CSGSm gen_sm, out_assign]
265   return [AST.CSBSm block]
266   where
267     -- An id for the counter
268     n_id = mkVHDLBasicId "n"
269     n_cur = idToVHDLExpr n_id
270     -- An expression for previous n
271     n_prev = if left then (n_cur AST.:-: (AST.PrimLit "1"))
272                      else (n_cur AST.:+: (AST.PrimLit "1"))
273     -- An id for the tmp result vector
274     tmp_id = mkVHDLBasicId "tmp"
275     tmp_name = AST.NSimple tmp_id
276     -- Generate parts of the fold
277     genFirstCell, genOtherCell :: VHDLSession AST.GenerateSm
278     genFirstCell = do
279       len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) vec
280       let cond_label = mkVHDLExtId "firstcell"
281       -- if n == 0 or n == len-1
282       let cond_scheme = AST.IfGn $ n_cur AST.:=: (if left then (AST.PrimLit "0")
283                                                   else (AST.PrimLit $ show (len-1)))
284       -- Output to tmp[current n]
285       let resname = mkIndexedName tmp_name n_cur
286       -- Input from start
287       argexpr1 <- MonadState.lift vsType $ varToVHDLExpr start
288       -- Input from vec[current n]
289       let argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName vec) n_cur
290       app_concsms <- genApplication (Right resname) folded_f  ( if left then
291                                                                   [Right argexpr1, Right argexpr2]
292                                                                 else
293                                                                   [Right argexpr2, Right argexpr1]
294                                                               )
295       -- Return the conditional generate part
296       return $ AST.GenerateSm cond_label cond_scheme [] app_concsms
297
298     genOtherCell = do
299       len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) vec
300       let cond_label = mkVHDLExtId "othercell"
301       -- if n > 0 or n < len-1
302       let cond_scheme = AST.IfGn $ n_cur AST.:/=: (if left then (AST.PrimLit "0")
303                                                    else (AST.PrimLit $ show (len-1)))
304       -- Output to tmp[current n]
305       let resname = mkIndexedName tmp_name n_cur
306       -- Input from tmp[previous n]
307       let argexpr1 = vhdlNameToVHDLExpr $ mkIndexedName tmp_name n_prev
308       -- Input from vec[current n]
309       let argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName vec) n_cur
310       app_concsms <- genApplication (Right resname) folded_f  ( if left then
311                                                                   [Right argexpr1, Right argexpr2]
312                                                                 else
313                                                                   [Right argexpr2, Right argexpr1]
314                                                               )
315       -- Return the conditional generate part
316       return $ AST.GenerateSm cond_label cond_scheme [] app_concsms
317
318 -- | Generate a generate statement for the builtin function "zip"
319 genZip :: BuiltinBuilder
320 genZip = genVarArgs genZip'
321 genZip' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
322 genZip' (Left res) f args@[arg1, arg2] = do {
323     -- Setup the generate scheme
324   ; len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) res
325           -- TODO: Use something better than varToString
326   ; let { label           = mkVHDLExtId ("zipVector" ++ (varToString res))
327         ; n_id            = mkVHDLBasicId "n"
328         ; n_expr          = idToVHDLExpr n_id
329         ; range           = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
330         ; genScheme       = AST.ForGn n_id range
331         ; resname'        = mkIndexedName (varToVHDLName res) n_expr
332         ; argexpr1        = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg1) n_expr
333         ; argexpr2        = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg2) n_expr
334         } ; 
335   ; labels <- MonadState.lift vsType $ getFieldLabels (tfvec_elem (Var.varType res))
336   ; let { resnameA    = mkSelectedName resname' (labels!!0)
337         ; resnameB    = mkSelectedName resname' (labels!!1)
338         ; resA_assign = mkUncondAssign (Right resnameA) argexpr1
339         ; resB_assign = mkUncondAssign (Right resnameB) argexpr2
340         } ;
341     -- Return the generate functions
342   ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] [resA_assign,resB_assign]]
343   }
344     
345 -- | Generate a generate statement for the builtin function "unzip"
346 genUnzip :: BuiltinBuilder
347 genUnzip = genVarArgs genUnzip'
348 genUnzip' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
349 genUnzip' (Left res) f args@[arg] = do {
350     -- Setup the generate scheme
351   ; len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) arg
352     -- TODO: Use something better than varToString
353   ; let { label           = mkVHDLExtId ("unzipVector" ++ (varToString res))
354         ; n_id            = mkVHDLBasicId "n"
355         ; n_expr          = idToVHDLExpr n_id
356         ; range           = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
357         ; genScheme       = AST.ForGn n_id range
358         ; resname'        = varToVHDLName res
359         ; argexpr'        = mkIndexedName (varToVHDLName arg) n_expr
360         } ;
361   ; reslabels <- MonadState.lift vsType $ getFieldLabels (Var.varType res)
362   ; arglabels <- MonadState.lift vsType $ getFieldLabels (tfvec_elem (Var.varType arg))
363   ; let { resnameA    = mkIndexedName (mkSelectedName resname' (reslabels!!0)) n_expr
364         ; resnameB    = mkIndexedName (mkSelectedName resname' (reslabels!!1)) n_expr
365         ; argexprA    = vhdlNameToVHDLExpr $ mkSelectedName argexpr' (arglabels!!0)
366         ; argexprB    = vhdlNameToVHDLExpr $ mkSelectedName argexpr' (arglabels!!1)
367         ; resA_assign = mkUncondAssign (Right resnameA) argexprA
368         ; resB_assign = mkUncondAssign (Right resnameB) argexprB
369         } ;
370     -- Return the generate functions
371   ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] [resA_assign,resB_assign]]
372   }
373
374 genCopy :: BuiltinBuilder 
375 genCopy = genVarArgs genCopy'
376 genCopy' :: (Either CoreSyn.CoreBndr AST.VHDLName ) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
377 genCopy' (Left res) f args@[arg] =
378   let
379     resExpr = AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
380                 (AST.PrimName $ (varToVHDLName arg))]
381     out_assign = mkUncondAssign (Left res) resExpr
382   in 
383     return [out_assign]
384     
385 genConcat :: BuiltinBuilder
386 genConcat = genVarArgs genConcat'
387 genConcat' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
388 genConcat' (Left res) f args@[arg] = do {
389     -- Setup the generate scheme
390   ; len1 <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) arg
391   ; let (_, nvec) = splitAppTy (Var.varType arg)
392   ; len2 <- MonadState.lift vsType $ tfp_to_int $ tfvec_len_ty nvec
393           -- TODO: Use something better than varToString
394   ; let { label       = mkVHDLExtId ("concatVector" ++ (varToString res))
395         ; n_id        = mkVHDLBasicId "n"
396         ; n_expr      = idToVHDLExpr n_id
397         ; fromRange   = n_expr AST.:*: (AST.PrimLit $ show len2)
398         ; genScheme   = AST.ForGn n_id range
399           -- Create the content of the generate statement: Applying the mapped_f to
400           -- each of the elements in arg, storing to each element in res
401         ; toRange     = (n_expr AST.:*: (AST.PrimLit $ show len2)) AST.:+: (AST.PrimLit $ show (len2-1))
402         ; range       = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len1-1))
403         ; resname     = vecSlice fromRange toRange
404         ; argexpr     = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg) n_expr
405         ; out_assign  = mkUncondAssign (Right resname) argexpr
406         } ;
407     -- Return the generate statement
408   ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] [out_assign]]
409   }
410   where
411     vecSlice init last =  AST.NSlice (AST.SliceName (varToVHDLName res) 
412                             (AST.ToRange init last))
413
414 genIteraten :: BuiltinBuilder
415 genIteraten dst f args = genIterate dst f (tail args)
416
417 genIterate :: BuiltinBuilder
418 genIterate = genIterateOrGenerate True
419
420 genGeneraten :: BuiltinBuilder
421 genGeneraten dst f args = genGenerate dst f (tail args)
422
423 genGenerate :: BuiltinBuilder
424 genGenerate = genIterateOrGenerate False
425
426 genIterateOrGenerate :: Bool -> BuiltinBuilder
427 genIterateOrGenerate iter = genVarArgs (genIterateOrGenerate' iter)
428
429 genIterateOrGenerate' :: Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
430 genIterateOrGenerate' iter (Left res) f args = do
431   len <- MonadState.lift vsType $ tfp_to_int ((tfvec_len_ty . Var.varType) res)
432   genIterateOrGenerate'' len iter (Left res) f args
433
434 genIterateOrGenerate'' :: Int -> Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
435 -- Special case for an empty input vector, just assign start to res
436 genIterateOrGenerate'' len iter (Left res) _ [app_f, start] | len == 0 = return [mkUncondAssign (Left res) (AST.PrimLit "\"\"")]
437
438 genIterateOrGenerate'' len iter (Left res) f [app_f, start] = do
439   -- The vector length
440   -- len <- MonadState.lift vsType $ tfp_to_int ((tfvec_len_ty . Var.varType) res)
441   -- An expression for len-1
442   let len_min_expr = (AST.PrimLit $ show (len-1))
443   -- -- evec is (TFVec n), so it still needs an element type
444   -- let (nvec, _) = splitAppTy (Var.varType vec)
445   -- -- Put the type of the start value in nvec, this will be the type of our
446   -- -- temporary vector
447   let tmp_ty = Var.varType res
448   let error_msg = "\nGenerate.genFold': Can not construct temp vector for element type: " ++ pprString tmp_ty 
449   tmp_vhdl_ty <- MonadState.lift vsType $ vhdl_ty error_msg tmp_ty
450   -- Setup the generate scheme
451   let gen_label = mkVHDLExtId ("iterateVector" ++ (varToString start))
452   let block_label = mkVHDLExtId ("iterateVector" ++ (varToString res))
453   let gen_range = AST.ToRange (AST.PrimLit "0") len_min_expr
454   let gen_scheme   = AST.ForGn n_id gen_range
455   -- Make the intermediate vector
456   let  tmp_dec     = AST.BDISD $ AST.SigDec tmp_id tmp_vhdl_ty Nothing
457   -- Create the generate statement
458   cells <- sequence [genFirstCell, genOtherCell]
459   let gen_sm = AST.GenerateSm gen_label gen_scheme [] (map AST.CSGSm cells)
460   -- Assign tmp[len-1] or tmp[0] to res
461   let out_assign = mkUncondAssign (Left res) $ vhdlNameToVHDLExpr tmp_name    
462   let block = AST.BlockSm block_label [] (AST.PMapAspect []) [tmp_dec] [AST.CSGSm gen_sm, out_assign]
463   return [AST.CSBSm block]
464   where
465     -- An id for the counter
466     n_id = mkVHDLBasicId "n"
467     n_cur = idToVHDLExpr n_id
468     -- An expression for previous n
469     n_prev = n_cur AST.:-: (AST.PrimLit "1")
470     -- An id for the tmp result vector
471     tmp_id = mkVHDLBasicId "tmp"
472     tmp_name = AST.NSimple tmp_id
473     -- Generate parts of the fold
474     genFirstCell, genOtherCell :: VHDLSession AST.GenerateSm
475     genFirstCell = do
476       let cond_label = mkVHDLExtId "firstcell"
477       -- if n == 0 or n == len-1
478       let cond_scheme = AST.IfGn $ n_cur AST.:=: (AST.PrimLit "0")
479       -- Output to tmp[current n]
480       let resname = mkIndexedName tmp_name n_cur
481       -- Input from start
482       argexpr <- MonadState.lift vsType $ varToVHDLExpr start
483       let startassign = mkUncondAssign (Right resname) argexpr
484       app_concsms <- genApplication (Right resname) app_f  [Right argexpr]
485       -- Return the conditional generate part
486       return $ AST.GenerateSm cond_label cond_scheme [] (if iter then 
487                                                           [startassign]
488                                                          else 
489                                                           app_concsms
490                                                         )
491
492     genOtherCell = do
493       let cond_label = mkVHDLExtId "othercell"
494       -- if n > 0 or n < len-1
495       let cond_scheme = AST.IfGn $ n_cur AST.:/=: (AST.PrimLit "0")
496       -- Output to tmp[current n]
497       let resname = mkIndexedName tmp_name n_cur
498       -- Input from tmp[previous n]
499       let argexpr = vhdlNameToVHDLExpr $ mkIndexedName tmp_name n_prev
500       app_concsms <- genApplication (Right resname) app_f [Right argexpr]
501       -- Return the conditional generate part
502       return $ AST.GenerateSm cond_label cond_scheme [] app_concsms
503
504
505 -----------------------------------------------------------------------------
506 -- Function to generate VHDL for applications
507 -----------------------------------------------------------------------------
508 genApplication ::
509   (Either CoreSyn.CoreBndr AST.VHDLName) -- ^ Where to store the result?
510   -> CoreSyn.CoreBndr -- ^ The function to apply
511   -> [Either CoreSyn.CoreExpr AST.Expr] -- ^ The arguments to apply
512   -> VHDLSession [AST.ConcSm] -- ^ The resulting concurrent statements
513 genApplication dst f args = do
514   case Var.isGlobalId f of
515     False -> do
516       signatures <- getA vsSignatures
517       -- This is a local id, so it should be a function whose definition we
518       -- have and which can be turned into a component instantiation.
519       case (Map.lookup f signatures) of
520         Just signature -> do
521           args' <- eitherCoreOrExprArgs args
522           -- We have a signature, this is a top level binding. Generate a
523           -- component instantiation.
524           let entity_id = ent_id signature
525           -- TODO: Using show here isn't really pretty, but we'll need some
526           -- unique-ish value...
527           let label = "comp_ins_" ++ (either show prettyShow) dst
528           let portmaps = mkAssocElems args' ((either varToVHDLName id) dst) signature
529           return [mkComponentInst label entity_id portmaps]
530         Nothing -> do
531           -- No signature, so this must be a local variable reference. It
532           -- should have a representable type (and thus, no arguments) and a
533           -- signal should be generated for it. Just generate an
534           -- unconditional assignment here.
535           f' <- MonadState.lift vsType $ varToVHDLExpr f
536           return $ [mkUncondAssign dst f']
537     True ->
538       case Var.idDetails f of
539         IdInfo.DataConWorkId dc -> case dst of
540           -- It's a datacon. Create a record from its arguments.
541           Left bndr -> do
542             -- We have the bndr, so we can get at the type
543             labels <- MonadState.lift vsType $ getFieldLabels (Var.varType bndr)
544             args' <- eitherCoreOrExprArgs args
545             return $ zipWith mkassign labels $ args'
546             where
547               mkassign :: AST.VHDLId -> AST.Expr -> AST.ConcSm
548               mkassign label arg =
549                 let sel_name = mkSelectedName ((either varToVHDLName id) dst) label in
550                 mkUncondAssign (Right sel_name) arg
551           Right _ -> error $ "\nGenerate.genApplication: Can't generate dataconstructor application without an original binder"
552         IdInfo.VanillaId -> do
553           -- It's a global value imported from elsewhere. These can be builtin
554           -- functions. Look up the function name in the name table and execute
555           -- the associated builder if there is any and the argument count matches
556           -- (this should always be the case if it typechecks, but just to be
557           -- sure...).
558           case (Map.lookup (varToString f) globalNameTable) of
559             Just (arg_count, builder) ->
560               if length args == arg_count then
561                 builder dst f args
562               else
563                 error $ "\nGenerate.genApplication(VanillaGlobal): Incorrect number of arguments to builtin function: " ++ pprString f ++ " Args: " ++ show args
564             Nothing -> error $ "\nGenerate.genApplication(VanillaGlobal): Using function from another module that is not a known builtin: " ++ pprString f
565         IdInfo.ClassOpId cls -> do
566           -- FIXME: Not looking for what instance this class op is called for
567           -- Is quite stupid of course.
568           case (Map.lookup (varToString f) globalNameTable) of
569             Just (arg_count, builder) ->
570               if length args == arg_count then
571                 builder dst f args
572               else
573                 error $ "\nGenerate.genApplication(ClassOpId): Incorrect number of arguments to builtin function: " ++ pprString f ++ " Args: " ++ show args
574             Nothing -> error $ "\nGenerate.genApplication(ClassOpId): Using function from another module that is not a known builtin: " ++ pprString f
575         details -> error $ "\nGenerate.genApplication: Calling unsupported function " ++ pprString f ++ " with GlobalIdDetails " ++ pprString details
576
577 -----------------------------------------------------------------------------
578 -- Functions to generate functions dealing with vectors.
579 -----------------------------------------------------------------------------
580
581 -- Returns the VHDLId of the vector function with the given name for the given
582 -- element type. Generates -- this function if needed.
583 vectorFunId :: Type.Type -> String -> TypeSession AST.VHDLId
584 vectorFunId el_ty fname = do
585   let error_msg = "\nGenerate.vectorFunId: Can not construct vector function for element: " ++ pprString el_ty
586   elemTM <- vhdl_ty error_msg el_ty
587   -- TODO: This should not be duplicated from mk_vector_ty. Probably but it in
588   -- the VHDLState or something.
589   let vectorTM = mkVHDLExtId $ "vector_" ++ (AST.fromVHDLId elemTM)
590   typefuns <- getA vsTypeFuns
591   case Map.lookup (OrdType el_ty, fname) typefuns of
592     -- Function already generated, just return it
593     Just (id, _) -> return id
594     -- Function not generated yet, generate it
595     Nothing -> do
596       let functions = genUnconsVectorFuns elemTM vectorTM
597       case lookup fname functions of
598         Just body -> do
599           modA vsTypeFuns $ Map.insert (OrdType el_ty, fname) (function_id, (fst body))
600           mapM_ (vectorFunId el_ty) (snd body)
601           return function_id
602         Nothing -> error $ "\nGenerate.vectorFunId: I don't know how to generate vector function " ++ fname
603   where
604     function_id = mkVHDLExtId fname
605
606 genUnconsVectorFuns :: AST.TypeMark -- ^ type of the vector elements
607                     -> AST.TypeMark -- ^ type of the vector
608                     -> [(String, (AST.SubProgBody, [String]))]
609 genUnconsVectorFuns elemTM vectorTM  = 
610   [ (exId, (AST.SubProgBody exSpec      []                  [exExpr],[]))
611   , (replaceId, (AST.SubProgBody replaceSpec [AST.SPVD replaceVar] [replaceExpr,replaceRet],[]))
612   , (lastId, (AST.SubProgBody lastSpec    []                  [lastExpr],[]))
613   , (initId, (AST.SubProgBody initSpec    [AST.SPVD initVar]  [initExpr, initRet],[]))
614   , (takeId, (AST.SubProgBody takeSpec    [AST.SPVD takeVar]  [takeExpr, takeRet],[]))
615   , (dropId, (AST.SubProgBody dropSpec    [AST.SPVD dropVar]  [dropExpr, dropRet],[]))
616   , (plusgtId, (AST.SubProgBody plusgtSpec  [AST.SPVD plusgtVar] [plusgtExpr, plusgtRet],[]))
617   , (emptyId, (AST.SubProgBody emptySpec   [AST.SPCD emptyVar] [emptyExpr],[]))
618   , (singletonId, (AST.SubProgBody singletonSpec [AST.SPVD singletonVar] [singletonRet],[]))
619   , (copynId, (AST.SubProgBody copynSpec    [AST.SPVD copynVar]      [copynExpr],[]))
620   , (selId, (AST.SubProgBody selSpec  [AST.SPVD selVar] [selFor, selRet],[]))
621   , (ltplusId, (AST.SubProgBody ltplusSpec [AST.SPVD ltplusVar] [ltplusExpr, ltplusRet],[]))  
622   , (plusplusId, (AST.SubProgBody plusplusSpec [AST.SPVD plusplusVar] [plusplusExpr, plusplusRet],[]))
623   , (lengthTId, (AST.SubProgBody lengthTSpec [] [lengthTExpr],[]))
624   , (shiftlId, (AST.SubProgBody shiftlSpec [AST.SPVD shiftlVar] [shiftlExpr, shiftlRet], [initId]))
625   , (shiftrId, (AST.SubProgBody shiftrSpec [AST.SPVD shiftrVar] [shiftrExpr, shiftrRet], [tailId]))
626   , (nullId, (AST.SubProgBody nullSpec [] [nullExpr], []))
627   , (rotlId, (AST.SubProgBody rotlSpec [AST.SPVD rotlVar] [rotlExpr, rotlRet], [nullId, lastId, initId]))
628   , (rotrId, (AST.SubProgBody rotrSpec [AST.SPVD rotrVar] [rotrExpr, rotrRet], [nullId, tailId, headId]))
629   , (reverseId, (AST.SubProgBody reverseSpec [AST.SPVD reverseVar] [reverseFor, reverseRet], []))
630   ]
631   where 
632     ixPar   = AST.unsafeVHDLBasicId "ix"
633     vecPar  = AST.unsafeVHDLBasicId "vec"
634     vec1Par = AST.unsafeVHDLBasicId "vec1"
635     vec2Par = AST.unsafeVHDLBasicId "vec2"
636     nPar    = AST.unsafeVHDLBasicId "n"
637     iId     = AST.unsafeVHDLBasicId "i"
638     iPar    = iId
639     aPar    = AST.unsafeVHDLBasicId "a"
640     fPar = AST.unsafeVHDLBasicId "f"
641     sPar = AST.unsafeVHDLBasicId "s"
642     resId   = AST.unsafeVHDLBasicId "res"
643     exSpec = AST.Function (mkVHDLExtId exId) [AST.IfaceVarDec vecPar vectorTM,
644                                AST.IfaceVarDec ixPar  naturalTM] elemTM
645     exExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NIndexed 
646               (AST.IndexedName (AST.NSimple vecPar) [AST.PrimName $ 
647                 AST.NSimple ixPar]))
648     replaceSpec = AST.Function (mkVHDLExtId replaceId)  [ AST.IfaceVarDec vecPar vectorTM
649                                           , AST.IfaceVarDec iPar   naturalTM
650                                           , AST.IfaceVarDec aPar   elemTM
651                                           ] vectorTM 
652        -- variable res : fsvec_x (0 to vec'length-1);
653     replaceVar =
654          AST.VarDec resId 
655                 (AST.SubtypeIn vectorTM
656                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
657                    [AST.ToRange (AST.PrimLit "0")
658                             (AST.PrimName (AST.NAttribute $ 
659                               AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
660                                 (AST.PrimLit "1"))   ]))
661                 Nothing
662        --  res AST.:= vec(0 to i-1) & a & vec(i+1 to length'vec-1)
663     replaceExpr = AST.NSimple resId AST.:=
664            (vecSlice (AST.PrimLit "0") (AST.PrimName (AST.NSimple iPar) AST.:-: AST.PrimLit "1") AST.:&:
665             AST.PrimName (AST.NSimple aPar) AST.:&: 
666              vecSlice (AST.PrimName (AST.NSimple iPar) AST.:+: AST.PrimLit "1")
667                       ((AST.PrimName (AST.NAttribute $ 
668                                 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing)) 
669                                                               AST.:-: AST.PrimLit "1"))
670     replaceRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
671     vecSlice init last =  AST.PrimName (AST.NSlice 
672                                         (AST.SliceName 
673                                               (AST.NSimple vecPar) 
674                                               (AST.ToRange init last)))
675     lastSpec = AST.Function (mkVHDLExtId lastId) [AST.IfaceVarDec vecPar vectorTM] elemTM
676        -- return vec(vec'length-1);
677     lastExpr = AST.ReturnSm (Just $ (AST.PrimName $ AST.NIndexed (AST.IndexedName 
678                     (AST.NSimple vecPar) 
679                     [AST.PrimName (AST.NAttribute $ 
680                                 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) 
681                                                              AST.:-: AST.PrimLit "1"])))
682     initSpec = AST.Function (mkVHDLExtId initId) [AST.IfaceVarDec vecPar vectorTM] vectorTM 
683        -- variable res : fsvec_x (0 to vec'length-2);
684     initVar = 
685          AST.VarDec resId 
686                 (AST.SubtypeIn vectorTM
687                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
688                    [AST.ToRange (AST.PrimLit "0")
689                             (AST.PrimName (AST.NAttribute $ 
690                               AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
691                                 (AST.PrimLit "2"))   ]))
692                 Nothing
693        -- resAST.:= vec(0 to vec'length-2)
694     initExpr = AST.NSimple resId AST.:= (vecSlice 
695                                (AST.PrimLit "0") 
696                                (AST.PrimName (AST.NAttribute $ 
697                                   AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) 
698                                                              AST.:-: AST.PrimLit "2"))
699     initRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
700     takeSpec = AST.Function (mkVHDLExtId takeId) [AST.IfaceVarDec nPar   naturalTM,
701                                    AST.IfaceVarDec vecPar vectorTM ] vectorTM
702        -- variable res : fsvec_x (0 to n-1);
703     takeVar = 
704          AST.VarDec resId 
705                 (AST.SubtypeIn vectorTM
706                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
707                    [AST.ToRange (AST.PrimLit "0")
708                                ((AST.PrimName (AST.NSimple nPar)) AST.:-:
709                                 (AST.PrimLit "1"))   ]))
710                 Nothing
711        -- res AST.:= vec(0 to n-1)
712     takeExpr = AST.NSimple resId AST.:= 
713                     (vecSlice (AST.PrimLit "1") 
714                               (AST.PrimName (AST.NSimple $ nPar) AST.:-: AST.PrimLit "1"))
715     takeRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
716     dropSpec = AST.Function (mkVHDLExtId dropId) [AST.IfaceVarDec nPar   naturalTM,
717                                    AST.IfaceVarDec vecPar vectorTM ] vectorTM 
718        -- variable res : fsvec_x (0 to vec'length-n-1);
719     dropVar = 
720          AST.VarDec resId 
721                 (AST.SubtypeIn vectorTM
722                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
723                    [AST.ToRange (AST.PrimLit "0")
724                             (AST.PrimName (AST.NAttribute $ 
725                               AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
726                                (AST.PrimName $ AST.NSimple nPar)AST.:-: (AST.PrimLit "1")) ]))
727                Nothing
728        -- res AST.:= vec(n to vec'length-1)
729     dropExpr = AST.NSimple resId AST.:= (vecSlice 
730                                (AST.PrimName $ AST.NSimple nPar) 
731                                (AST.PrimName (AST.NAttribute $ 
732                                   AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) 
733                                                              AST.:-: AST.PrimLit "1"))
734     dropRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
735     plusgtSpec = AST.Function (mkVHDLExtId plusgtId) [AST.IfaceVarDec aPar   elemTM,
736                                        AST.IfaceVarDec vecPar vectorTM] vectorTM 
737     -- variable res : fsvec_x (0 to vec'length);
738     plusgtVar = 
739       AST.VarDec resId 
740              (AST.SubtypeIn vectorTM
741                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
742                 [AST.ToRange (AST.PrimLit "0")
743                         (AST.PrimName (AST.NAttribute $ 
744                           AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing))]))
745              Nothing
746     plusgtExpr = AST.NSimple resId AST.:= 
747                    ((AST.PrimName $ AST.NSimple aPar) AST.:&: 
748                     (AST.PrimName $ AST.NSimple vecPar))
749     plusgtRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
750     emptySpec = AST.Function (mkVHDLExtId emptyId) [] vectorTM
751     emptyVar = 
752           AST.ConstDec resId 
753               (AST.SubtypeIn vectorTM Nothing)
754               (Just $ AST.PrimLit "\"\"")
755     emptyExpr = AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
756     singletonSpec = AST.Function (mkVHDLExtId singletonId) [AST.IfaceVarDec aPar elemTM ] 
757                                          vectorTM
758     -- variable res : fsvec_x (0 to 0) := (others => a);
759     singletonVar = 
760       AST.VarDec resId 
761              (AST.SubtypeIn vectorTM
762                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
763                 [AST.ToRange (AST.PrimLit "0") (AST.PrimLit "0")]))
764              (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
765                                           (AST.PrimName $ AST.NSimple aPar)])
766     singletonRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
767     copynSpec = AST.Function (mkVHDLExtId copynId) [AST.IfaceVarDec nPar   naturalTM,
768                                    AST.IfaceVarDec aPar   elemTM   ] vectorTM 
769     -- variable res : fsvec_x (0 to n-1) := (others => a);
770     copynVar = 
771       AST.VarDec resId 
772              (AST.SubtypeIn vectorTM
773                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
774                 [AST.ToRange (AST.PrimLit "0")
775                             ((AST.PrimName (AST.NSimple nPar)) AST.:-:
776                              (AST.PrimLit "1"))   ]))
777              (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
778                                           (AST.PrimName $ AST.NSimple aPar)])
779     -- return res
780     copynExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
781     selSpec = AST.Function (mkVHDLExtId selId) [AST.IfaceVarDec fPar   naturalTM,
782                                AST.IfaceVarDec sPar   naturalTM,
783                                AST.IfaceVarDec nPar   naturalTM,
784                                AST.IfaceVarDec vecPar vectorTM ] vectorTM
785     -- variable res : fsvec_x (0 to n-1);
786     selVar = 
787       AST.VarDec resId 
788                 (AST.SubtypeIn vectorTM
789                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
790                     [AST.ToRange (AST.PrimLit "0")
791                       ((AST.PrimName (AST.NSimple nPar)) AST.:-:
792                       (AST.PrimLit "1"))   ])
793                 )
794                 Nothing
795     -- for i res'range loop
796     --   res(i) := vec(f+i*s);
797     -- end loop;
798     selFor = AST.ForSM iId (AST.AttribRange $ AST.AttribName (AST.NSimple resId) (AST.NSimple $ rangeId) Nothing) [selAssign]
799     -- res(i) := vec(f+i*s);
800     selAssign = let origExp = AST.PrimName (AST.NSimple fPar) AST.:+: 
801                                 (AST.PrimName (AST.NSimple iId) AST.:*: 
802                                   AST.PrimName (AST.NSimple sPar)) in
803                                   AST.NIndexed (AST.IndexedName (AST.NSimple resId) [AST.PrimName (AST.NSimple iId)]) AST.:=
804                                     (AST.PrimName $ AST.NIndexed (AST.IndexedName (AST.NSimple vecPar) [origExp]))
805     -- return res;
806     selRet =  AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
807     ltplusSpec = AST.Function (mkVHDLExtId ltplusId) [AST.IfaceVarDec vecPar vectorTM,
808                                         AST.IfaceVarDec aPar   elemTM] vectorTM 
809      -- variable res : fsvec_x (0 to vec'length);
810     ltplusVar = 
811       AST.VarDec resId 
812         (AST.SubtypeIn vectorTM
813           (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
814             [AST.ToRange (AST.PrimLit "0")
815               (AST.PrimName (AST.NAttribute $ 
816                 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing))]))
817         Nothing
818     ltplusExpr = AST.NSimple resId AST.:= 
819                      ((AST.PrimName $ AST.NSimple vecPar) AST.:&: 
820                       (AST.PrimName $ AST.NSimple aPar))
821     ltplusRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
822     plusplusSpec = AST.Function (mkVHDLExtId plusplusId) [AST.IfaceVarDec vec1Par vectorTM,
823                                              AST.IfaceVarDec vec2Par vectorTM] 
824                                              vectorTM 
825     -- variable res : fsvec_x (0 to vec1'length + vec2'length -1);
826     plusplusVar = 
827       AST.VarDec resId 
828         (AST.SubtypeIn vectorTM
829           (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
830             [AST.ToRange (AST.PrimLit "0")
831               (AST.PrimName (AST.NAttribute $ 
832                 AST.AttribName (AST.NSimple vec1Par) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:+:
833                   AST.PrimName (AST.NAttribute $ 
834                 AST.AttribName (AST.NSimple vec2Par) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
835                   AST.PrimLit "1")]))
836        Nothing
837     plusplusExpr = AST.NSimple resId AST.:= 
838                      ((AST.PrimName $ AST.NSimple vec1Par) AST.:&: 
839                       (AST.PrimName $ AST.NSimple vec2Par))
840     plusplusRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
841     lengthTSpec = AST.Function (mkVHDLExtId lengthTId) [AST.IfaceVarDec vecPar vectorTM] naturalTM
842     lengthTExpr = AST.ReturnSm (Just $ AST.PrimName (AST.NAttribute $ 
843                                 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing))
844     shiftlSpec = AST.Function (mkVHDLExtId shiftlId) [AST.IfaceVarDec vecPar vectorTM,
845                                    AST.IfaceVarDec aPar   elemTM  ] vectorTM 
846     -- variable res : fsvec_x (0 to vec'length-1);
847     shiftlVar = 
848      AST.VarDec resId 
849             (AST.SubtypeIn vectorTM
850               (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
851                [AST.ToRange (AST.PrimLit "0")
852                         (AST.PrimName (AST.NAttribute $ 
853                           AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
854                            (AST.PrimLit "1")) ]))
855             Nothing
856     -- res := a & init(vec)
857     shiftlExpr = AST.NSimple resId AST.:=
858                     (AST.PrimName (AST.NSimple aPar) AST.:&:
859                      (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId initId))  
860                        [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]))
861     shiftlRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)       
862     shiftrSpec = AST.Function (mkVHDLExtId shiftrId) [AST.IfaceVarDec vecPar vectorTM,
863                                        AST.IfaceVarDec aPar   elemTM  ] vectorTM 
864     -- variable res : fsvec_x (0 to vec'length-1);
865     shiftrVar = 
866      AST.VarDec resId 
867             (AST.SubtypeIn vectorTM
868               (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
869                [AST.ToRange (AST.PrimLit "0")
870                         (AST.PrimName (AST.NAttribute $ 
871                           AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
872                            (AST.PrimLit "1")) ]))
873             Nothing
874     -- res := tail(vec) & a
875     shiftrExpr = AST.NSimple resId AST.:=
876                   ((AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId tailId))  
877                     [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]) AST.:&:
878                   (AST.PrimName (AST.NSimple aPar)))
879                 
880     shiftrRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)      
881     nullSpec = AST.Function (mkVHDLExtId nullId) [AST.IfaceVarDec vecPar vectorTM] booleanTM
882     -- return vec'length = 0
883     nullExpr = AST.ReturnSm (Just $ 
884                 AST.PrimName (AST.NAttribute $ 
885                   AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:=:
886                     AST.PrimLit "0")
887     rotlSpec = AST.Function (mkVHDLExtId rotlId) [AST.IfaceVarDec vecPar vectorTM] vectorTM 
888     -- variable res : fsvec_x (0 to vec'length-1);
889     rotlVar = 
890      AST.VarDec resId 
891             (AST.SubtypeIn vectorTM
892               (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
893                [AST.ToRange (AST.PrimLit "0")
894                         (AST.PrimName (AST.NAttribute $ 
895                           AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
896                            (AST.PrimLit "1")) ]))
897             Nothing
898     -- if null(vec) then res := vec else res := last(vec) & init(vec)
899     rotlExpr = AST.IfSm (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId nullId))  
900                           [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)])
901                         [AST.NSimple resId AST.:= (AST.PrimName $ AST.NSimple vecPar)]
902                         []
903                         (Just $ AST.Else [rotlExprRet])
904       where rotlExprRet = 
905                 AST.NSimple resId AST.:= 
906                       ((AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId lastId))  
907                         [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]) AST.:&:
908                       (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId initId))  
909                         [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]))
910     rotlRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)       
911     rotrSpec = AST.Function (mkVHDLExtId rotrId) [AST.IfaceVarDec vecPar vectorTM] vectorTM 
912     -- variable res : fsvec_x (0 to vec'length-1);
913     rotrVar = 
914      AST.VarDec resId 
915             (AST.SubtypeIn vectorTM
916               (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
917                [AST.ToRange (AST.PrimLit "0")
918                         (AST.PrimName (AST.NAttribute $ 
919                           AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
920                            (AST.PrimLit "1")) ]))
921             Nothing
922     -- if null(vec) then res := vec else res := tail(vec) & head(vec)
923     rotrExpr = AST.IfSm (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId nullId))  
924                           [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)])
925                         [AST.NSimple resId AST.:= (AST.PrimName $ AST.NSimple vecPar)]
926                         []
927                         (Just $ AST.Else [rotrExprRet])
928       where rotrExprRet = 
929                 AST.NSimple resId AST.:= 
930                       ((AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId tailId))  
931                         [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]) AST.:&:
932                       (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId headId))  
933                         [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]))
934     rotrRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
935     reverseSpec = AST.Function (mkVHDLExtId reverseId) [AST.IfaceVarDec vecPar vectorTM] vectorTM
936     reverseVar = 
937       AST.VarDec resId 
938              (AST.SubtypeIn vectorTM
939                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
940                 [AST.ToRange (AST.PrimLit "0")
941                          (AST.PrimName (AST.NAttribute $ 
942                            AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
943                             (AST.PrimLit "1")) ]))
944              Nothing
945     -- for i in 0 to res'range loop
946     --   res(vec'length-i-1) := vec(i);
947     -- end loop;
948     reverseFor = 
949        AST.ForSM iId (AST.AttribRange $ AST.AttribName (AST.NSimple resId) (AST.NSimple $ rangeId) Nothing) [reverseAssign]
950     -- res(vec'length-i-1) := vec(i);
951     reverseAssign = AST.NIndexed (AST.IndexedName (AST.NSimple resId) [destExp]) AST.:=
952       (AST.PrimName $ AST.NIndexed (AST.IndexedName (AST.NSimple vecPar) 
953                            [AST.PrimName $ AST.NSimple iId]))
954         where destExp = AST.PrimName (AST.NAttribute $ AST.AttribName (AST.NSimple vecPar) 
955                                    (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-: 
956                         AST.PrimName (AST.NSimple iId) AST.:-: 
957                         (AST.PrimLit "1") 
958     -- return res;
959     reverseRet = AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
960
961     
962 -----------------------------------------------------------------------------
963 -- A table of builtin functions
964 -----------------------------------------------------------------------------
965
966 -- | The builtin functions we support. Maps a name to an argument count and a
967 -- builder function.
968 globalNameTable :: NameTable
969 globalNameTable = Map.fromList
970   [ (exId             , (2, genFCall False          ) )
971   , (replaceId        , (3, genFCall False          ) )
972   , (headId           , (1, genFCall True           ) )
973   , (lastId           , (1, genFCall True           ) )
974   , (tailId           , (1, genFCall False          ) )
975   , (initId           , (1, genFCall False          ) )
976   , (takeId           , (2, genFCall False          ) )
977   , (dropId           , (2, genFCall False          ) )
978   , (selId            , (4, genFCall False          ) )
979   , (plusgtId         , (2, genFCall False          ) )
980   , (ltplusId         , (2, genFCall False          ) )
981   , (plusplusId       , (2, genFCall False          ) )
982   , (mapId            , (2, genMap                  ) )
983   , (zipWithId        , (3, genZipWith              ) )
984   , (foldlId          , (3, genFoldl                ) )
985   , (foldrId          , (3, genFoldr                ) )
986   , (zipId            , (2, genZip                  ) )
987   , (unzipId          , (1, genUnzip                ) )
988   , (shiftlId         , (2, genFCall False          ) )
989   , (shiftrId         , (2, genFCall False          ) )
990   , (rotlId           , (1, genFCall False          ) )
991   , (rotrId           , (1, genFCall False          ) )
992   , (concatId         , (1, genConcat               ) )
993   , (reverseId        , (1, genFCall False          ) )
994   , (iteratenId       , (3, genIteraten             ) )
995   , (iterateId        , (2, genIterate              ) )
996   , (generatenId      , (3, genGeneraten            ) )
997   , (generateId       , (2, genGenerate             ) )
998   , (emptyId          , (0, genFCall False          ) )
999   , (singletonId      , (1, genFCall False          ) )
1000   , (copynId          , (2, genFCall False          ) )
1001   , (copyId           , (1, genCopy                 ) )
1002   , (lengthTId        , (1, genFCall False          ) )
1003   , (nullId           , (1, genFCall False          ) )
1004   , (hwxorId          , (2, genOperator2 AST.Xor    ) )
1005   , (hwandId          , (2, genOperator2 AST.And    ) )
1006   , (hworId           , (2, genOperator2 AST.Or     ) )
1007   , (hwnotId          , (1, genOperator1 AST.Not    ) )
1008   , (plusId           , (2, genOperator2 (AST.:+:)  ) )
1009   , (timesId          , (2, genOperator2 (AST.:*:)  ) )
1010   , (negateId         , (1, genNegation             ) )
1011   , (minusId          , (2, genOperator2 (AST.:-:)  ) )
1012   , (fromSizedWordId  , (1, genFromSizedWord        ) )
1013   , (fromIntegerId    , (1, genFromInteger          ) )
1014   , (resizeId         , (1, genResize               ) )
1015   ]