f55aa3d9e5e029312cb19a1de239d3e226497b98
[matthijs/master-project/cλash.git] / Generate.hs
1 module Generate where
2
3 -- Standard modules
4 import qualified Control.Monad as Monad
5 import qualified Data.Map as Map
6 import qualified Maybe
7 import qualified Data.Either as Either
8 import Data.Accessor
9 import Debug.Trace
10
11 -- ForSyDe
12 import qualified ForSyDe.Backend.VHDL.AST as AST
13
14 -- GHC API
15 import CoreSyn
16 import Type
17 import qualified Var
18 import qualified IdInfo
19
20 -- Local imports
21 import Constants
22 import VHDLTypes
23 import VHDLTools
24 import CoreTools
25 import Pretty
26
27 -----------------------------------------------------------------------------
28 -- Functions to generate VHDL for builtin functions
29 -----------------------------------------------------------------------------
30
31 -- | A function to wrap a builder-like function that expects its arguments to
32 -- be expressions.
33 genExprArgs ::
34   (dst -> func -> [AST.Expr] -> res)
35   -> (dst -> func -> [Either CoreSyn.CoreExpr AST.Expr] -> res)
36 genExprArgs wrap dst func args = wrap dst func args'
37   where args' = map (either (varToVHDLExpr.exprToVar) id) args
38   
39 -- | A function to wrap a builder-like function that expects its arguments to
40 -- be variables.
41 genVarArgs ::
42   (dst -> func -> [Var.Var] -> res)
43   -> (dst -> func -> [Either CoreSyn.CoreExpr AST.Expr] -> res)
44 genVarArgs wrap dst func args = wrap dst func args'
45   where
46     args' = map exprToVar exprargs
47     -- Check (rather crudely) that all arguments are CoreExprs
48     (exprargs, []) = Either.partitionEithers args
49
50 -- | A function to wrap a builder-like function that produces an expression
51 -- and expects it to be assigned to the destination.
52 genExprRes ::
53   ((Either CoreSyn.CoreBndr AST.VHDLName) -> func -> [arg] -> VHDLSession AST.Expr)
54   -> ((Either CoreSyn.CoreBndr AST.VHDLName) -> func -> [arg] -> VHDLSession [AST.ConcSm])
55 genExprRes wrap dst func args = do
56   expr <- wrap dst func args
57   return $ [mkUncondAssign dst expr]
58
59 -- | Generate a binary operator application. The first argument should be a
60 -- constructor from the AST.Expr type, e.g. AST.And.
61 genOperator2 :: (AST.Expr -> AST.Expr -> AST.Expr) -> BuiltinBuilder 
62 genOperator2 op = genExprArgs $ genExprRes (genOperator2' op)
63 genOperator2' :: (AST.Expr -> AST.Expr -> AST.Expr) -> dst -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
64 genOperator2' op _ f [arg1, arg2] = return $ op arg1 arg2
65
66 -- | Generate a unary operator application
67 genOperator1 :: (AST.Expr -> AST.Expr) -> BuiltinBuilder 
68 genOperator1 op = genExprArgs $ genExprRes (genOperator1' op)
69 genOperator1' :: (AST.Expr -> AST.Expr) -> dst -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
70 genOperator1' op _ f [arg] = return $ op arg
71
72 -- | Generate a function call from the destination binder, function name and a
73 -- list of expressions (its arguments)
74 genFCall :: BuiltinBuilder 
75 genFCall = genExprArgs $ genExprRes genFCall'
76 genFCall' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
77 genFCall' (Left res) f args = do
78   let fname = varToString f
79   let el_ty = (tfvec_elem . Var.varType) res
80   id <- vectorFunId el_ty fname
81   return $ AST.PrimFCall $ AST.FCall (AST.NSimple id)  $
82              map (\exp -> Nothing AST.:=>: AST.ADExpr exp) args
83 genFCall' (Right name) _ _ = error $ "Cannot generate builtin function call assigned to a VHDLName: " ++ show name
84
85 -- | Generate a generate statement for the builtin function "map"
86 genMap :: BuiltinBuilder
87 genMap = genVarArgs genMap'
88 genMap' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
89 genMap' (Left res) f [mapped_f, arg] =
90   let
91     -- Setup the generate scheme
92     len         = (tfvec_len . Var.varType) res
93     -- TODO: Use something better than varToString
94     label       = mkVHDLExtId ("mapVector" ++ (varToString res))
95     n_id        = mkVHDLBasicId "n"
96     n_expr      = idToVHDLExpr n_id
97     range       = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
98     genScheme   = AST.ForGn n_id range
99
100     -- Create the content of the generate statement: Applying the mapped_f to
101     -- each of the elements in arg, storing to each element in res
102     resname     = mkIndexedName (varToVHDLName res) n_expr
103     argexpr     = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg) n_expr
104   in do
105     app_concsms <- genApplication (Right resname) mapped_f [Right argexpr]
106     -- Return the generate statement
107     return [AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms]
108
109 genMap' (Right name) _ _ = error $ "Cannot generate map function call assigned to a VHDLName: " ++ show name
110     
111 genZipWith :: BuiltinBuilder
112 genZipWith = genVarArgs genZipWith'
113 genZipWith' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
114 genZipWith' (Left res) f args@[zipped_f, arg1, arg2] =
115   let
116     -- Setup the generate scheme
117     len         = (tfvec_len . Var.varType) res
118     -- TODO: Use something better than varToString
119     label       = mkVHDLExtId ("zipWithVector" ++ (varToString res))
120     n_id        = mkVHDLBasicId "n"
121     n_expr      = idToVHDLExpr n_id
122     range       = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
123     genScheme   = AST.ForGn n_id range
124
125     -- Create the content of the generate statement: Applying the zipped_f to
126     -- each of the elements in arg1 and arg2, storing to each element in res
127     resname     = mkIndexedName (varToVHDLName res) n_expr
128     argexpr1    = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg1) n_expr
129     argexpr2    = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg2) n_expr
130   in do
131     app_concsms <- genApplication (Right resname) zipped_f [Right argexpr1, Right argexpr2]
132     -- Return the generate functions
133     return [AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms]
134
135 genFoldl :: BuiltinBuilder
136 genFoldl = genFold True
137
138 genFoldr :: BuiltinBuilder
139 genFoldr = genFold False
140
141 genFold :: Bool -> BuiltinBuilder
142 genFold left = genVarArgs (genFold' left)
143 genFold' :: Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
144 -- Special case for an empty input vector, just assign start to res
145 genFold' left (Left res) _ [_, start, vec] | len == 0 = return [mkUncondAssign (Left res) (varToVHDLExpr start)]
146     where len = (tfvec_len . Var.varType) vec
147 genFold' left (Left res) f [folded_f, start, vec] = do
148   -- evec is (TFVec n), so it still needs an element type
149   let (nvec, _) = splitAppTy (Var.varType vec)
150   -- Put the type of the start value in nvec, this will be the type of our
151   -- temporary vector
152   let tmp_ty = Type.mkAppTy nvec (Var.varType start)
153   tmp_vhdl_ty <- vhdl_ty tmp_ty
154   -- Setup the generate scheme
155   let gen_label = mkVHDLExtId ("foldlVector" ++ (varToString vec))
156   let block_label = mkVHDLExtId ("foldlVector" ++ (varToString start))
157   let gen_range = if left then AST.ToRange (AST.PrimLit "0") len_min_expr
158                   else AST.DownRange len_min_expr (AST.PrimLit "0")
159   let gen_scheme   = AST.ForGn n_id gen_range
160   -- Make the intermediate vector
161   let  tmp_dec     = AST.BDISD $ AST.SigDec tmp_id tmp_vhdl_ty Nothing
162   -- Create the generate statement
163   cells <- sequence [genFirstCell, genOtherCell]
164   let gen_sm = AST.GenerateSm gen_label gen_scheme [] (map AST.CSGSm cells)
165   -- Assign tmp[len-1] or tmp[0] to res
166   let out_assign = mkUncondAssign (Left res) $ vhdlNameToVHDLExpr (if left then
167                     (mkIndexedName tmp_name (AST.PrimLit $ show (len-1))) else
168                     (mkIndexedName tmp_name (AST.PrimLit "0")))      
169   let block = AST.BlockSm block_label [] (AST.PMapAspect []) [tmp_dec] [AST.CSGSm gen_sm, out_assign]
170   return [AST.CSBSm block]
171   where
172     -- The vector length
173     len         = (tfvec_len . Var.varType) vec
174     -- An id for the counter
175     n_id = mkVHDLBasicId "n"
176     n_cur = idToVHDLExpr n_id
177     -- An expression for previous n
178     n_prev = if left then (n_cur AST.:-: (AST.PrimLit "1"))
179                      else (n_cur AST.:+: (AST.PrimLit "1"))
180     -- An expression for len-1
181     len_min_expr = (AST.PrimLit $ show (len-1))
182     -- An id for the tmp result vector
183     tmp_id = mkVHDLBasicId "tmp"
184     tmp_name = AST.NSimple tmp_id
185     -- Generate parts of the fold
186     genFirstCell, genOtherCell :: VHDLSession AST.GenerateSm
187     genFirstCell = do
188       let cond_label = mkVHDLExtId "firstcell"
189       -- if n == 0 or n == len-1
190       let cond_scheme = AST.IfGn $ n_cur AST.:=: (if left then (AST.PrimLit "0")
191                                                   else (AST.PrimLit $ show (len-1)))
192       -- Output to tmp[current n]
193       let resname = mkIndexedName tmp_name n_cur
194       -- Input from start
195       let argexpr1 = varToVHDLExpr start
196       -- Input from vec[current n]
197       let argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName vec) n_cur
198       app_concsms <- genApplication (Right resname) folded_f  ( if left then
199                                                                   [Right argexpr1, Right argexpr2]
200                                                                 else
201                                                                   [Right argexpr2, Right argexpr1]
202                                                               )
203       -- Return the conditional generate part
204       return $ AST.GenerateSm cond_label cond_scheme [] app_concsms
205
206     genOtherCell = do
207       let cond_label = mkVHDLExtId "othercell"
208       -- if n > 0 or n < len-1
209       let cond_scheme = AST.IfGn $ n_cur AST.:/=: (if left then (AST.PrimLit "0")
210                                                    else (AST.PrimLit $ show (len-1)))
211       -- Output to tmp[current n]
212       let resname = mkIndexedName tmp_name n_cur
213       -- Input from tmp[previous n]
214       let argexpr1 = vhdlNameToVHDLExpr $ mkIndexedName tmp_name n_prev
215       -- Input from vec[current n]
216       let argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName vec) n_cur
217       app_concsms <- genApplication (Right resname) folded_f  ( if left then
218                                                                   [Right argexpr1, Right argexpr2]
219                                                                 else
220                                                                   [Right argexpr2, Right argexpr1]
221                                                               )
222       -- Return the conditional generate part
223       return $ AST.GenerateSm cond_label cond_scheme [] app_concsms
224
225 -----------------------------------------------------------------------------
226 -- Function to generate VHDL for applications
227 -----------------------------------------------------------------------------
228 genApplication ::
229   (Either CoreSyn.CoreBndr AST.VHDLName) -- ^ Where to store the result?
230   -> CoreSyn.CoreBndr -- ^ The function to apply
231   -> [Either CoreSyn.CoreExpr AST.Expr] -- ^ The arguments to apply
232   -> VHDLSession [AST.ConcSm] -- ^ The resulting concurrent statements
233 genApplication dst f args =
234   case Var.globalIdVarDetails f of
235     IdInfo.DataConWorkId dc -> case dst of
236       -- It's a datacon. Create a record from its arguments.
237       Left bndr -> do
238         -- We have the bndr, so we can get at the type
239         labels <- getFieldLabels (Var.varType bndr)
240         return $ zipWith mkassign labels $ map (either exprToVHDLExpr id) args
241         where
242           mkassign :: AST.VHDLId -> AST.Expr -> AST.ConcSm
243           mkassign label arg =
244             let sel_name = mkSelectedName ((either varToVHDLName id) dst) label in
245             mkUncondAssign (Right sel_name) arg
246       Right _ -> error $ "Generate.genApplication Can't generate dataconstructor application without an original binder"
247     IdInfo.VanillaGlobal -> do
248       -- It's a global value imported from elsewhere. These can be builtin
249       -- functions. Look up the function name in the name table and execute
250       -- the associated builder if there is any and the argument count matches
251       -- (this should always be the case if it typechecks, but just to be
252       -- sure...).
253       case (Map.lookup (varToString f) globalNameTable) of
254         Just (arg_count, builder) ->
255           if length args == arg_count then
256             builder dst f args
257           else
258             error $ "Generate.genApplication Incorrect number of arguments to builtin function: " ++ pprString f ++ " Args: " ++ show args
259         Nothing -> error $ "Using function from another module that is not a known builtin: " ++ pprString f
260     IdInfo.NotGlobalId -> do
261       signatures <- getA vsSignatures
262       -- This is a local id, so it should be a function whose definition we
263       -- have and which can be turned into a component instantiation.
264       let  
265         signature = Maybe.fromMaybe 
266           (error $ "Using function '" ++ (varToString f) ++ "' without signature? This should not happen!") 
267           (Map.lookup f signatures)
268         entity_id = ent_id signature
269         -- TODO: Using show here isn't really pretty, but we'll need some
270         -- unique-ish value...
271         label = "comp_ins_" ++ (either show prettyShow) dst
272         portmaps = mkAssocElems (map (either exprToVHDLExpr id) args) ((either varToVHDLName id) dst) signature
273         in
274           return [mkComponentInst label entity_id portmaps]
275     details -> error $ "Calling unsupported function " ++ pprString f ++ " with GlobalIdDetails " ++ pprString details
276
277 -----------------------------------------------------------------------------
278 -- Functions to generate functions dealing with vectors.
279 -----------------------------------------------------------------------------
280
281 -- Returns the VHDLId of the vector function with the given name for the given
282 -- element type. Generates -- this function if needed.
283 vectorFunId :: Type.Type -> String -> VHDLSession AST.VHDLId
284 vectorFunId el_ty fname = do
285   elemTM <- vhdl_ty el_ty
286   -- TODO: This should not be duplicated from mk_vector_ty. Probably but it in
287   -- the VHDLState or something.
288   let vectorTM = mkVHDLExtId $ "vector_" ++ (AST.fromVHDLId elemTM)
289   typefuns <- getA vsTypeFuns
290   case Map.lookup (OrdType el_ty, fname) typefuns of
291     -- Function already generated, just return it
292     Just (id, _) -> return id
293     -- Function not generated yet, generate it
294     Nothing -> do
295       let functions = genUnconsVectorFuns elemTM vectorTM
296       case lookup fname functions of
297         Just body -> do
298           modA vsTypeFuns $ Map.insert (OrdType el_ty, fname) (function_id, body)
299           return function_id
300         Nothing -> error $ "I don't know how to generate vector function " ++ fname
301   where
302     function_id = mkVHDLExtId fname
303
304 genUnconsVectorFuns :: AST.TypeMark -- ^ type of the vector elements
305                     -> AST.TypeMark -- ^ type of the vector
306                     -> [(String, AST.SubProgBody)]
307 genUnconsVectorFuns elemTM vectorTM  = 
308   [ (exId, AST.SubProgBody exSpec      []                  [exExpr])
309   , (replaceId, AST.SubProgBody replaceSpec [AST.SPVD replaceVar] [replaceExpr,replaceRet])
310   , (headId, AST.SubProgBody headSpec    []                  [headExpr])
311   , (lastId, AST.SubProgBody lastSpec    []                  [lastExpr])
312   , (initId, AST.SubProgBody initSpec    [AST.SPVD initVar]  [initExpr, initRet])
313   , (tailId, AST.SubProgBody tailSpec    [AST.SPVD tailVar]  [tailExpr, tailRet])
314   , (takeId, AST.SubProgBody takeSpec    [AST.SPVD takeVar]  [takeExpr, takeRet])
315   , (dropId, AST.SubProgBody dropSpec    [AST.SPVD dropVar]  [dropExpr, dropRet])
316   , (plusgtId, AST.SubProgBody plusgtSpec  [AST.SPVD plusgtVar] [plusgtExpr, plusgtRet])
317   , (emptyId, AST.SubProgBody emptySpec   [AST.SPCD emptyVar] [emptyExpr])
318   , (singletonId, AST.SubProgBody singletonSpec [AST.SPVD singletonVar] [singletonRet])
319   , (copyId, AST.SubProgBody copySpec    [AST.SPVD copyVar]      [copyExpr])
320   , (selId, AST.SubProgBody selSpec  [AST.SPVD selVar] [selFor, selRet])
321   ]
322   where 
323     ixPar   = AST.unsafeVHDLBasicId "ix"
324     vecPar  = AST.unsafeVHDLBasicId "vec"
325     nPar    = AST.unsafeVHDLBasicId "n"
326     iId     = AST.unsafeVHDLBasicId "i"
327     iPar    = iId
328     aPar    = AST.unsafeVHDLBasicId "a"
329     fPar = AST.unsafeVHDLBasicId "f"
330     sPar = AST.unsafeVHDLBasicId "s"
331     resId   = AST.unsafeVHDLBasicId "res"
332     exSpec = AST.Function (mkVHDLExtId exId) [AST.IfaceVarDec vecPar vectorTM,
333                                AST.IfaceVarDec ixPar  naturalTM] elemTM
334     exExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NIndexed 
335               (AST.IndexedName (AST.NSimple vecPar) [AST.PrimName $ 
336                 AST.NSimple ixPar]))
337     replaceSpec = AST.Function (mkVHDLExtId replaceId)  [ AST.IfaceVarDec vecPar vectorTM
338                                           , AST.IfaceVarDec iPar   naturalTM
339                                           , AST.IfaceVarDec aPar   elemTM
340                                           ] vectorTM 
341        -- variable res : fsvec_x (0 to vec'length-1);
342     replaceVar =
343          AST.VarDec resId 
344                 (AST.SubtypeIn vectorTM
345                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
346                    [AST.ToRange (AST.PrimLit "0")
347                             (AST.PrimName (AST.NAttribute $ 
348                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
349                                 (AST.PrimLit "1"))   ]))
350                 Nothing
351        --  res AST.:= vec(0 to i-1) & a & vec(i+1 to length'vec-1)
352     replaceExpr = AST.NSimple resId AST.:=
353            (vecSlice (AST.PrimLit "0") (AST.PrimName (AST.NSimple iPar) AST.:-: AST.PrimLit "1") AST.:&:
354             AST.PrimName (AST.NSimple aPar) AST.:&: 
355              vecSlice (AST.PrimName (AST.NSimple iPar) AST.:+: AST.PrimLit "1")
356                       ((AST.PrimName (AST.NAttribute $ 
357                                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing)) 
358                                                               AST.:-: AST.PrimLit "1"))
359     replaceRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
360     vecSlice init last =  AST.PrimName (AST.NSlice 
361                                         (AST.SliceName 
362                                               (AST.NSimple vecPar) 
363                                               (AST.ToRange init last)))
364     headSpec = AST.Function (mkVHDLExtId headId) [AST.IfaceVarDec vecPar vectorTM] elemTM
365        -- return vec(0);
366     headExpr = AST.ReturnSm (Just $ (AST.PrimName $ AST.NIndexed (AST.IndexedName 
367                     (AST.NSimple vecPar) [AST.PrimLit "0"])))
368     lastSpec = AST.Function (mkVHDLExtId lastId) [AST.IfaceVarDec vecPar vectorTM] elemTM
369        -- return vec(vec'length-1);
370     lastExpr = AST.ReturnSm (Just $ (AST.PrimName $ AST.NIndexed (AST.IndexedName 
371                     (AST.NSimple vecPar) 
372                     [AST.PrimName (AST.NAttribute $ 
373                                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
374                                                              AST.:-: AST.PrimLit "1"])))
375     initSpec = AST.Function (mkVHDLExtId initId) [AST.IfaceVarDec vecPar vectorTM] vectorTM 
376        -- variable res : fsvec_x (0 to vec'length-2);
377     initVar = 
378          AST.VarDec resId 
379                 (AST.SubtypeIn vectorTM
380                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
381                    [AST.ToRange (AST.PrimLit "0")
382                             (AST.PrimName (AST.NAttribute $ 
383                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
384                                 (AST.PrimLit "2"))   ]))
385                 Nothing
386        -- resAST.:= vec(0 to vec'length-2)
387     initExpr = AST.NSimple resId AST.:= (vecSlice 
388                                (AST.PrimLit "0") 
389                                (AST.PrimName (AST.NAttribute $ 
390                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
391                                                              AST.:-: AST.PrimLit "2"))
392     initRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
393     tailSpec = AST.Function (mkVHDLExtId tailId) [AST.IfaceVarDec vecPar vectorTM] vectorTM
394        -- variable res : fsvec_x (0 to vec'length-2); 
395     tailVar = 
396          AST.VarDec resId 
397                 (AST.SubtypeIn vectorTM
398                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
399                    [AST.ToRange (AST.PrimLit "0")
400                             (AST.PrimName (AST.NAttribute $ 
401                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
402                                 (AST.PrimLit "2"))   ]))
403                 Nothing       
404        -- res AST.:= vec(1 to vec'length-1)
405     tailExpr = AST.NSimple resId AST.:= (vecSlice 
406                                (AST.PrimLit "1") 
407                                (AST.PrimName (AST.NAttribute $ 
408                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
409                                                              AST.:-: AST.PrimLit "1"))
410     tailRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
411     takeSpec = AST.Function (mkVHDLExtId takeId) [AST.IfaceVarDec nPar   naturalTM,
412                                    AST.IfaceVarDec vecPar vectorTM ] vectorTM
413        -- variable res : fsvec_x (0 to n-1);
414     takeVar = 
415          AST.VarDec resId 
416                 (AST.SubtypeIn vectorTM
417                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
418                    [AST.ToRange (AST.PrimLit "0")
419                                ((AST.PrimName (AST.NSimple nPar)) AST.:-:
420                                 (AST.PrimLit "1"))   ]))
421                 Nothing
422        -- res AST.:= vec(0 to n-1)
423     takeExpr = AST.NSimple resId AST.:= 
424                     (vecSlice (AST.PrimLit "1") 
425                               (AST.PrimName (AST.NSimple $ nPar) AST.:-: AST.PrimLit "1"))
426     takeRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
427     dropSpec = AST.Function (mkVHDLExtId dropId) [AST.IfaceVarDec nPar   naturalTM,
428                                    AST.IfaceVarDec vecPar vectorTM ] vectorTM 
429        -- variable res : fsvec_x (0 to vec'length-n-1);
430     dropVar = 
431          AST.VarDec resId 
432                 (AST.SubtypeIn vectorTM
433                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
434                    [AST.ToRange (AST.PrimLit "0")
435                             (AST.PrimName (AST.NAttribute $ 
436                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
437                                (AST.PrimName $ AST.NSimple nPar)AST.:-: (AST.PrimLit "1")) ]))
438                Nothing
439        -- res AST.:= vec(n to vec'length-1)
440     dropExpr = AST.NSimple resId AST.:= (vecSlice 
441                                (AST.PrimName $ AST.NSimple nPar) 
442                                (AST.PrimName (AST.NAttribute $ 
443                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
444                                                              AST.:-: AST.PrimLit "1"))
445     dropRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
446     plusgtSpec = AST.Function (mkVHDLExtId plusgtId) [AST.IfaceVarDec aPar   elemTM,
447                                        AST.IfaceVarDec vecPar vectorTM] vectorTM 
448     -- variable res : fsvec_x (0 to vec'length);
449     plusgtVar = 
450       AST.VarDec resId 
451              (AST.SubtypeIn vectorTM
452                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
453                 [AST.ToRange (AST.PrimLit "0")
454                         (AST.PrimName (AST.NAttribute $ 
455                           AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing))]))
456              Nothing
457     plusgtExpr = AST.NSimple resId AST.:= 
458                    ((AST.PrimName $ AST.NSimple aPar) AST.:&: 
459                     (AST.PrimName $ AST.NSimple vecPar))
460     plusgtRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
461     emptySpec = AST.Function (mkVHDLExtId emptyId) [] vectorTM
462     emptyVar = 
463           AST.ConstDec resId 
464               (AST.SubtypeIn vectorTM Nothing)
465               (Just $ AST.PrimLit "\"\"")
466     emptyExpr = AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
467     singletonSpec = AST.Function (mkVHDLExtId singletonId) [AST.IfaceVarDec aPar elemTM ] 
468                                          vectorTM
469     -- variable res : fsvec_x (0 to 0) := (others => a);
470     singletonVar = 
471       AST.VarDec resId 
472              (AST.SubtypeIn vectorTM
473                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
474                 [AST.ToRange (AST.PrimLit "0") (AST.PrimLit "0")]))
475              (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
476                                           (AST.PrimName $ AST.NSimple aPar)])
477     singletonRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
478     copySpec = AST.Function (mkVHDLExtId copyId) [AST.IfaceVarDec nPar   naturalTM,
479                                    AST.IfaceVarDec aPar   elemTM   ] vectorTM 
480     -- variable res : fsvec_x (0 to n-1) := (others => a);
481     copyVar = 
482       AST.VarDec resId 
483              (AST.SubtypeIn vectorTM
484                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
485                 [AST.ToRange (AST.PrimLit "0")
486                             ((AST.PrimName (AST.NSimple nPar)) AST.:-:
487                              (AST.PrimLit "1"))   ]))
488              (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
489                                           (AST.PrimName $ AST.NSimple aPar)])
490     -- return res
491     copyExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
492     selSpec = AST.Function (mkVHDLExtId selId) [AST.IfaceVarDec fPar   naturalTM,
493                                AST.IfaceVarDec nPar   naturalTM,
494                                AST.IfaceVarDec sPar   naturalTM,
495                                AST.IfaceVarDec vecPar vectorTM ] vectorTM
496     -- variable res : fsvec_x (0 to n-1);
497     selVar = 
498       AST.VarDec resId 
499                 (AST.SubtypeIn vectorTM
500                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
501                     [AST.ToRange (AST.PrimLit "0")
502                       ((AST.PrimName (AST.NSimple nPar)) AST.:-:
503                       (AST.PrimLit "1"))   ])
504                 )
505                 Nothing
506     -- for i res'range loop
507     --   res(i) := vec(f+i*s);
508     -- end loop;
509     selFor = AST.ForSM iId (AST.AttribRange $ AST.AttribName (AST.NSimple resId) rangeId Nothing) [selAssign]
510     -- res(i) := vec(f+i*s);
511     selAssign = let origExp = AST.PrimName (AST.NSimple fPar) AST.:+: 
512                                 (AST.PrimName (AST.NSimple iId) AST.:*: 
513                                   AST.PrimName (AST.NSimple sPar)) in
514                                   AST.NIndexed (AST.IndexedName (AST.NSimple resId) [AST.PrimName (AST.NSimple iId)]) AST.:=
515                                     (AST.PrimName $ AST.NIndexed (AST.IndexedName (AST.NSimple vecPar) [origExp]))
516     -- return res;
517     selRet =  AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
518
519 -----------------------------------------------------------------------------
520 -- A table of builtin functions
521 -----------------------------------------------------------------------------
522
523 -- | The builtin functions we support. Maps a name to an argument count and a
524 -- builder function.
525 globalNameTable :: NameTable
526 globalNameTable = Map.fromList
527   [ (exId             , (2, genFCall                ) )
528   , (replaceId        , (3, genFCall                ) )
529   , (headId           , (1, genFCall                ) )
530   , (lastId           , (1, genFCall                ) )
531   , (tailId           , (1, genFCall                ) )
532   , (initId           , (1, genFCall                ) )
533   , (takeId           , (2, genFCall                ) )
534   , (dropId           , (2, genFCall                ) )
535   , (selId            , (4, genFCall                ) )
536   , (plusgtId         , (2, genFCall                ) )
537   , (mapId            , (2, genMap                  ) )
538   , (zipWithId        , (3, genZipWith              ) )
539   , (foldlId          , (3, genFoldl                ) )
540   , (foldrId          , (3, genFoldr                ) )
541   , (emptyId          , (0, genFCall                ) )
542   , (singletonId      , (1, genFCall                ) )
543   , (copyId           , (2, genFCall                ) )
544   , (hwxorId          , (2, genOperator2 AST.Xor    ) )
545   , (hwandId          , (2, genOperator2 AST.And    ) )
546   , (hworId           , (2, genOperator2 AST.Or     ) )
547   , (hwnotId          , (1, genOperator1 AST.Not    ) )
548   ]