Merge branch 'cλash' of http://git.stderr.nl/matthijs/projects/master-project
[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 (Left res) f [Left mapped_f, Left (Var arg)] =
88   -- mapped_f must be a CoreExpr (since we can't represent functions as VHDL
89   -- expressions). arg must be a CoreExpr (and should be a CoreSyn.Var), since
90   -- we must index it (which we couldn't if it was a VHDL Expr, since only
91   -- VHDLNames can be indexed).
92   let
93     -- Setup the generate scheme
94     len         = (tfvec_len . Var.varType) res
95     -- TODO: Use something better than varToString
96     label       = mkVHDLExtId ("mapVector" ++ (varToString res))
97     n_id        = mkVHDLBasicId "n"
98     n_expr      = idToVHDLExpr n_id
99     range       = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
100     genScheme   = AST.ForGn n_id range
101
102     -- Create the content of the generate statement: Applying the mapped_f to
103     -- each of the elements in arg, storing to each element in res
104     resname     = mkIndexedName (varToVHDLName res) n_expr
105     argexpr     = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg) n_expr
106   in do
107     let (CoreSyn.Var real_f, already_mapped_args) = CoreSyn.collectArgs mapped_f
108     let valargs = get_val_args (Var.varType real_f) already_mapped_args
109     app_concsms <- genApplication (Right resname) real_f (map Left valargs ++ [Right argexpr])
110     -- Return the generate statement
111     return [AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms]
112
113 genMap' (Right name) _ _ = error $ "Cannot generate map function call assigned to a VHDLName: " ++ show name
114     
115 genZipWith :: BuiltinBuilder
116 genZipWith = genVarArgs genZipWith'
117 genZipWith' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
118 genZipWith' (Left res) f args@[zipped_f, arg1, arg2] =
119   let
120     -- Setup the generate scheme
121     len         = (tfvec_len . Var.varType) res
122     -- TODO: Use something better than varToString
123     label       = mkVHDLExtId ("zipWithVector" ++ (varToString res))
124     n_id        = mkVHDLBasicId "n"
125     n_expr      = idToVHDLExpr n_id
126     range       = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
127     genScheme   = AST.ForGn n_id range
128
129     -- Create the content of the generate statement: Applying the zipped_f to
130     -- each of the elements in arg1 and arg2, storing to each element in res
131     resname     = mkIndexedName (varToVHDLName res) n_expr
132     argexpr1    = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg1) n_expr
133     argexpr2    = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg2) n_expr
134   in do
135     app_concsms <- genApplication (Right resname) zipped_f [Right argexpr1, Right argexpr2]
136     -- Return the generate functions
137     return [AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms]
138
139 genFoldl :: BuiltinBuilder
140 genFoldl = genFold True
141
142 genFoldr :: BuiltinBuilder
143 genFoldr = genFold False
144
145 genFold :: Bool -> BuiltinBuilder
146 genFold left = genVarArgs (genFold' left)
147 genFold' :: Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
148 -- Special case for an empty input vector, just assign start to res
149 genFold' left (Left res) _ [_, start, vec] | len == 0 = return [mkUncondAssign (Left res) (varToVHDLExpr start)]
150     where len = (tfvec_len . Var.varType) vec
151 genFold' left (Left res) f [folded_f, start, vec] = do
152   -- evec is (TFVec n), so it still needs an element type
153   let (nvec, _) = splitAppTy (Var.varType vec)
154   -- Put the type of the start value in nvec, this will be the type of our
155   -- temporary vector
156   let tmp_ty = Type.mkAppTy nvec (Var.varType start)
157   tmp_vhdl_ty <- vhdl_ty tmp_ty
158   -- Setup the generate scheme
159   let gen_label = mkVHDLExtId ("foldlVector" ++ (varToString vec))
160   let block_label = mkVHDLExtId ("foldlVector" ++ (varToString start))
161   let gen_range = if left then AST.ToRange (AST.PrimLit "0") len_min_expr
162                   else AST.DownRange len_min_expr (AST.PrimLit "0")
163   let gen_scheme   = AST.ForGn n_id gen_range
164   -- Make the intermediate vector
165   let  tmp_dec     = AST.BDISD $ AST.SigDec tmp_id tmp_vhdl_ty Nothing
166   -- Create the generate statement
167   cells <- sequence [genFirstCell, genOtherCell]
168   let gen_sm = AST.GenerateSm gen_label gen_scheme [] (map AST.CSGSm cells)
169   -- Assign tmp[len-1] or tmp[0] to res
170   let out_assign = mkUncondAssign (Left res) $ vhdlNameToVHDLExpr (if left then
171                     (mkIndexedName tmp_name (AST.PrimLit $ show (len-1))) else
172                     (mkIndexedName tmp_name (AST.PrimLit "0")))      
173   let block = AST.BlockSm block_label [] (AST.PMapAspect []) [tmp_dec] [AST.CSGSm gen_sm, out_assign]
174   return [AST.CSBSm block]
175   where
176     -- The vector length
177     len         = (tfvec_len . Var.varType) vec
178     -- An id for the counter
179     n_id = mkVHDLBasicId "n"
180     n_cur = idToVHDLExpr n_id
181     -- An expression for previous n
182     n_prev = if left then (n_cur AST.:-: (AST.PrimLit "1"))
183                      else (n_cur AST.:+: (AST.PrimLit "1"))
184     -- An expression for len-1
185     len_min_expr = (AST.PrimLit $ show (len-1))
186     -- An id for the tmp result vector
187     tmp_id = mkVHDLBasicId "tmp"
188     tmp_name = AST.NSimple tmp_id
189     -- Generate parts of the fold
190     genFirstCell, genOtherCell :: VHDLSession AST.GenerateSm
191     genFirstCell = do
192       let cond_label = mkVHDLExtId "firstcell"
193       -- if n == 0 or n == len-1
194       let cond_scheme = AST.IfGn $ n_cur AST.:=: (if left then (AST.PrimLit "0")
195                                                   else (AST.PrimLit $ show (len-1)))
196       -- Output to tmp[current n]
197       let resname = mkIndexedName tmp_name n_cur
198       -- Input from start
199       let argexpr1 = varToVHDLExpr start
200       -- Input from vec[current n]
201       let argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName vec) n_cur
202       app_concsms <- genApplication (Right resname) folded_f  ( if left then
203                                                                   [Right argexpr1, Right argexpr2]
204                                                                 else
205                                                                   [Right argexpr2, Right argexpr1]
206                                                               )
207       -- Return the conditional generate part
208       return $ AST.GenerateSm cond_label cond_scheme [] app_concsms
209
210     genOtherCell = do
211       let cond_label = mkVHDLExtId "othercell"
212       -- if n > 0 or n < len-1
213       let cond_scheme = AST.IfGn $ n_cur AST.:/=: (if left then (AST.PrimLit "0")
214                                                    else (AST.PrimLit $ show (len-1)))
215       -- Output to tmp[current n]
216       let resname = mkIndexedName tmp_name n_cur
217       -- Input from tmp[previous n]
218       let argexpr1 = vhdlNameToVHDLExpr $ mkIndexedName tmp_name n_prev
219       -- Input from vec[current n]
220       let argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName vec) n_cur
221       app_concsms <- genApplication (Right resname) folded_f  ( if left then
222                                                                   [Right argexpr1, Right argexpr2]
223                                                                 else
224                                                                   [Right argexpr2, Right argexpr1]
225                                                               )
226       -- Return the conditional generate part
227       return $ AST.GenerateSm cond_label cond_scheme [] app_concsms
228
229 -- | Generate a generate statement for the builtin function "zip"
230 genZip :: BuiltinBuilder
231 genZip = genVarArgs genZip'
232 genZip' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
233 genZip' (Left res) f args@[arg1, arg2] =
234   let
235     -- Setup the generate scheme
236     len             = (tfvec_len . Var.varType) res
237     -- TODO: Use something better than varToString
238     label           = mkVHDLExtId ("zipVector" ++ (varToString res))
239     n_id            = mkVHDLBasicId "n"
240     n_expr          = idToVHDLExpr n_id
241     range           = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
242     genScheme       = AST.ForGn n_id range
243     resname'        = mkIndexedName (varToVHDLName res) n_expr
244     argexpr1        = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg1) n_expr
245     argexpr2        = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg2) n_expr
246   in do
247     labels <- getFieldLabels (tfvec_elem (Var.varType res))
248     let resnameA    = mkSelectedName resname' (labels!!0)
249     let resnameB    = mkSelectedName resname' (labels!!1)
250     let resA_assign = mkUncondAssign (Right resnameA) argexpr1
251     let resB_assign = mkUncondAssign (Right resnameB) argexpr2
252     -- Return the generate functions
253     return [AST.CSGSm $ AST.GenerateSm label genScheme [] [resA_assign,resB_assign]]
254     
255 -- | Generate a generate statement for the builtin function "unzip"
256 genUnzip :: BuiltinBuilder
257 genUnzip = genVarArgs genUnzip'
258 genUnzip' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
259 genUnzip' (Left res) f args@[arg] =
260   let
261     -- Setup the generate scheme
262     len             = (tfvec_len . Var.varType) arg
263     -- TODO: Use something better than varToString
264     label           = mkVHDLExtId ("unzipVector" ++ (varToString res))
265     n_id            = mkVHDLBasicId "n"
266     n_expr          = idToVHDLExpr n_id
267     range           = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
268     genScheme       = AST.ForGn n_id range
269     resname'        = varToVHDLName res
270     argexpr'        = mkIndexedName (varToVHDLName arg) n_expr
271   in do
272     reslabels <- getFieldLabels (Var.varType res)
273     arglabels <- getFieldLabels (tfvec_elem (Var.varType arg))
274     let resnameA    = mkIndexedName (mkSelectedName resname' (reslabels!!0)) n_expr
275     let resnameB    = mkIndexedName (mkSelectedName resname' (reslabels!!1)) n_expr
276     let argexprA    = vhdlNameToVHDLExpr $ mkSelectedName argexpr' (arglabels!!0)
277     let argexprB    = vhdlNameToVHDLExpr $ mkSelectedName argexpr' (arglabels!!1)
278     let resA_assign = mkUncondAssign (Right resnameA) argexprA
279     let resB_assign = mkUncondAssign (Right resnameB) argexprB
280     -- Return the generate functions
281     return [AST.CSGSm $ AST.GenerateSm label genScheme [] [resA_assign,resB_assign]]
282
283 -----------------------------------------------------------------------------
284 -- Function to generate VHDL for applications
285 -----------------------------------------------------------------------------
286 genApplication ::
287   (Either CoreSyn.CoreBndr AST.VHDLName) -- ^ Where to store the result?
288   -> CoreSyn.CoreBndr -- ^ The function to apply
289   -> [Either CoreSyn.CoreExpr AST.Expr] -- ^ The arguments to apply
290   -> VHDLSession [AST.ConcSm] -- ^ The resulting concurrent statements
291 genApplication dst f args =
292   case Var.globalIdVarDetails f of
293     IdInfo.DataConWorkId dc -> case dst of
294       -- It's a datacon. Create a record from its arguments.
295       Left bndr -> do
296         -- We have the bndr, so we can get at the type
297         labels <- getFieldLabels (Var.varType bndr)
298         return $ zipWith mkassign labels $ map (either exprToVHDLExpr id) args
299         where
300           mkassign :: AST.VHDLId -> AST.Expr -> AST.ConcSm
301           mkassign label arg =
302             let sel_name = mkSelectedName ((either varToVHDLName id) dst) label in
303             mkUncondAssign (Right sel_name) arg
304       Right _ -> error $ "Generate.genApplication Can't generate dataconstructor application without an original binder"
305     IdInfo.VanillaGlobal -> do
306       -- It's a global value imported from elsewhere. These can be builtin
307       -- functions. Look up the function name in the name table and execute
308       -- the associated builder if there is any and the argument count matches
309       -- (this should always be the case if it typechecks, but just to be
310       -- sure...).
311       case (Map.lookup (varToString f) globalNameTable) of
312         Just (arg_count, builder) ->
313           if length args == arg_count then
314             builder dst f args
315           else
316             error $ "Generate.genApplication Incorrect number of arguments to builtin function: " ++ pprString f ++ " Args: " ++ show args
317         Nothing -> error $ "Using function from another module that is not a known builtin: " ++ pprString f
318     IdInfo.NotGlobalId -> do
319       signatures <- getA vsSignatures
320       -- This is a local id, so it should be a function whose definition we
321       -- have and which can be turned into a component instantiation.
322       let  
323         signature = Maybe.fromMaybe 
324           (error $ "Using function '" ++ (varToString f) ++ "' without signature? This should not happen!") 
325           (Map.lookup f signatures)
326         entity_id = ent_id signature
327         -- TODO: Using show here isn't really pretty, but we'll need some
328         -- unique-ish value...
329         label = "comp_ins_" ++ (either show prettyShow) dst
330         portmaps = mkAssocElems (map (either exprToVHDLExpr id) args) ((either varToVHDLName id) dst) signature
331         in
332           return [mkComponentInst label entity_id portmaps]
333     details -> error $ "Calling unsupported function " ++ pprString f ++ " with GlobalIdDetails " ++ pprString details
334
335 -----------------------------------------------------------------------------
336 -- Functions to generate functions dealing with vectors.
337 -----------------------------------------------------------------------------
338
339 -- Returns the VHDLId of the vector function with the given name for the given
340 -- element type. Generates -- this function if needed.
341 vectorFunId :: Type.Type -> String -> VHDLSession AST.VHDLId
342 vectorFunId el_ty fname = do
343   elemTM <- vhdl_ty el_ty
344   -- TODO: This should not be duplicated from mk_vector_ty. Probably but it in
345   -- the VHDLState or something.
346   let vectorTM = mkVHDLExtId $ "vector_" ++ (AST.fromVHDLId elemTM)
347   typefuns <- getA vsTypeFuns
348   case Map.lookup (OrdType el_ty, fname) typefuns of
349     -- Function already generated, just return it
350     Just (id, _) -> return id
351     -- Function not generated yet, generate it
352     Nothing -> do
353       let functions = genUnconsVectorFuns elemTM vectorTM
354       case lookup fname functions of
355         Just body -> do
356           modA vsTypeFuns $ Map.insert (OrdType el_ty, fname) (function_id, body)
357           return function_id
358         Nothing -> error $ "I don't know how to generate vector function " ++ fname
359   where
360     function_id = mkVHDLExtId fname
361
362 genUnconsVectorFuns :: AST.TypeMark -- ^ type of the vector elements
363                     -> AST.TypeMark -- ^ type of the vector
364                     -> [(String, AST.SubProgBody)]
365 genUnconsVectorFuns elemTM vectorTM  = 
366   [ (exId, AST.SubProgBody exSpec      []                  [exExpr])
367   , (replaceId, AST.SubProgBody replaceSpec [AST.SPVD replaceVar] [replaceExpr,replaceRet])
368   , (headId, AST.SubProgBody headSpec    []                  [headExpr])
369   , (lastId, AST.SubProgBody lastSpec    []                  [lastExpr])
370   , (initId, AST.SubProgBody initSpec    [AST.SPVD initVar]  [initExpr, initRet])
371   , (tailId, AST.SubProgBody tailSpec    [AST.SPVD tailVar]  [tailExpr, tailRet])
372   , (takeId, AST.SubProgBody takeSpec    [AST.SPVD takeVar]  [takeExpr, takeRet])
373   , (dropId, AST.SubProgBody dropSpec    [AST.SPVD dropVar]  [dropExpr, dropRet])
374   , (plusgtId, AST.SubProgBody plusgtSpec  [AST.SPVD plusgtVar] [plusgtExpr, plusgtRet])
375   , (emptyId, AST.SubProgBody emptySpec   [AST.SPCD emptyVar] [emptyExpr])
376   , (singletonId, AST.SubProgBody singletonSpec [AST.SPVD singletonVar] [singletonRet])
377   , (copyId, AST.SubProgBody copySpec    [AST.SPVD copyVar]      [copyExpr])
378   , (selId, AST.SubProgBody selSpec  [AST.SPVD selVar] [selFor, selRet])
379   , (ltplusId, AST.SubProgBody ltplusSpec [AST.SPVD ltplusVar] [ltplusExpr, ltplusRet]  )  
380   , (plusplusId, AST.SubProgBody plusplusSpec [AST.SPVD plusplusVar] [plusplusExpr, plusplusRet])
381   , (lengthTId, AST.SubProgBody lengthTSpec [] [lengthTExpr])
382   ]
383   where 
384     ixPar   = AST.unsafeVHDLBasicId "ix"
385     vecPar  = AST.unsafeVHDLBasicId "vec"
386     vec1Par = AST.unsafeVHDLBasicId "vec1"
387     vec2Par = AST.unsafeVHDLBasicId "vec2"
388     nPar    = AST.unsafeVHDLBasicId "n"
389     iId     = AST.unsafeVHDLBasicId "i"
390     iPar    = iId
391     aPar    = AST.unsafeVHDLBasicId "a"
392     fPar = AST.unsafeVHDLBasicId "f"
393     sPar = AST.unsafeVHDLBasicId "s"
394     resId   = AST.unsafeVHDLBasicId "res"
395     exSpec = AST.Function (mkVHDLExtId exId) [AST.IfaceVarDec vecPar vectorTM,
396                                AST.IfaceVarDec ixPar  naturalTM] elemTM
397     exExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NIndexed 
398               (AST.IndexedName (AST.NSimple vecPar) [AST.PrimName $ 
399                 AST.NSimple ixPar]))
400     replaceSpec = AST.Function (mkVHDLExtId replaceId)  [ AST.IfaceVarDec vecPar vectorTM
401                                           , AST.IfaceVarDec iPar   naturalTM
402                                           , AST.IfaceVarDec aPar   elemTM
403                                           ] vectorTM 
404        -- variable res : fsvec_x (0 to vec'length-1);
405     replaceVar =
406          AST.VarDec resId 
407                 (AST.SubtypeIn vectorTM
408                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
409                    [AST.ToRange (AST.PrimLit "0")
410                             (AST.PrimName (AST.NAttribute $ 
411                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
412                                 (AST.PrimLit "1"))   ]))
413                 Nothing
414        --  res AST.:= vec(0 to i-1) & a & vec(i+1 to length'vec-1)
415     replaceExpr = AST.NSimple resId AST.:=
416            (vecSlice (AST.PrimLit "0") (AST.PrimName (AST.NSimple iPar) AST.:-: AST.PrimLit "1") AST.:&:
417             AST.PrimName (AST.NSimple aPar) AST.:&: 
418              vecSlice (AST.PrimName (AST.NSimple iPar) AST.:+: AST.PrimLit "1")
419                       ((AST.PrimName (AST.NAttribute $ 
420                                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing)) 
421                                                               AST.:-: AST.PrimLit "1"))
422     replaceRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
423     vecSlice init last =  AST.PrimName (AST.NSlice 
424                                         (AST.SliceName 
425                                               (AST.NSimple vecPar) 
426                                               (AST.ToRange init last)))
427     headSpec = AST.Function (mkVHDLExtId headId) [AST.IfaceVarDec vecPar vectorTM] elemTM
428        -- return vec(0);
429     headExpr = AST.ReturnSm (Just $ (AST.PrimName $ AST.NIndexed (AST.IndexedName 
430                     (AST.NSimple vecPar) [AST.PrimLit "0"])))
431     lastSpec = AST.Function (mkVHDLExtId lastId) [AST.IfaceVarDec vecPar vectorTM] elemTM
432        -- return vec(vec'length-1);
433     lastExpr = AST.ReturnSm (Just $ (AST.PrimName $ AST.NIndexed (AST.IndexedName 
434                     (AST.NSimple vecPar) 
435                     [AST.PrimName (AST.NAttribute $ 
436                                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
437                                                              AST.:-: AST.PrimLit "1"])))
438     initSpec = AST.Function (mkVHDLExtId initId) [AST.IfaceVarDec vecPar vectorTM] vectorTM 
439        -- variable res : fsvec_x (0 to vec'length-2);
440     initVar = 
441          AST.VarDec resId 
442                 (AST.SubtypeIn vectorTM
443                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
444                    [AST.ToRange (AST.PrimLit "0")
445                             (AST.PrimName (AST.NAttribute $ 
446                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
447                                 (AST.PrimLit "2"))   ]))
448                 Nothing
449        -- resAST.:= vec(0 to vec'length-2)
450     initExpr = AST.NSimple resId AST.:= (vecSlice 
451                                (AST.PrimLit "0") 
452                                (AST.PrimName (AST.NAttribute $ 
453                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
454                                                              AST.:-: AST.PrimLit "2"))
455     initRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
456     tailSpec = AST.Function (mkVHDLExtId tailId) [AST.IfaceVarDec vecPar vectorTM] vectorTM
457        -- variable res : fsvec_x (0 to vec'length-2); 
458     tailVar = 
459          AST.VarDec resId 
460                 (AST.SubtypeIn vectorTM
461                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
462                    [AST.ToRange (AST.PrimLit "0")
463                             (AST.PrimName (AST.NAttribute $ 
464                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
465                                 (AST.PrimLit "2"))   ]))
466                 Nothing       
467        -- res AST.:= vec(1 to vec'length-1)
468     tailExpr = AST.NSimple resId AST.:= (vecSlice 
469                                (AST.PrimLit "1") 
470                                (AST.PrimName (AST.NAttribute $ 
471                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
472                                                              AST.:-: AST.PrimLit "1"))
473     tailRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
474     takeSpec = AST.Function (mkVHDLExtId takeId) [AST.IfaceVarDec nPar   naturalTM,
475                                    AST.IfaceVarDec vecPar vectorTM ] vectorTM
476        -- variable res : fsvec_x (0 to n-1);
477     takeVar = 
478          AST.VarDec resId 
479                 (AST.SubtypeIn vectorTM
480                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
481                    [AST.ToRange (AST.PrimLit "0")
482                                ((AST.PrimName (AST.NSimple nPar)) AST.:-:
483                                 (AST.PrimLit "1"))   ]))
484                 Nothing
485        -- res AST.:= vec(0 to n-1)
486     takeExpr = AST.NSimple resId AST.:= 
487                     (vecSlice (AST.PrimLit "1") 
488                               (AST.PrimName (AST.NSimple $ nPar) AST.:-: AST.PrimLit "1"))
489     takeRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
490     dropSpec = AST.Function (mkVHDLExtId dropId) [AST.IfaceVarDec nPar   naturalTM,
491                                    AST.IfaceVarDec vecPar vectorTM ] vectorTM 
492        -- variable res : fsvec_x (0 to vec'length-n-1);
493     dropVar = 
494          AST.VarDec resId 
495                 (AST.SubtypeIn vectorTM
496                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
497                    [AST.ToRange (AST.PrimLit "0")
498                             (AST.PrimName (AST.NAttribute $ 
499                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
500                                (AST.PrimName $ AST.NSimple nPar)AST.:-: (AST.PrimLit "1")) ]))
501                Nothing
502        -- res AST.:= vec(n to vec'length-1)
503     dropExpr = AST.NSimple resId AST.:= (vecSlice 
504                                (AST.PrimName $ AST.NSimple nPar) 
505                                (AST.PrimName (AST.NAttribute $ 
506                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
507                                                              AST.:-: AST.PrimLit "1"))
508     dropRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
509     plusgtSpec = AST.Function (mkVHDLExtId plusgtId) [AST.IfaceVarDec aPar   elemTM,
510                                        AST.IfaceVarDec vecPar vectorTM] vectorTM 
511     -- variable res : fsvec_x (0 to vec'length);
512     plusgtVar = 
513       AST.VarDec resId 
514              (AST.SubtypeIn vectorTM
515                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
516                 [AST.ToRange (AST.PrimLit "0")
517                         (AST.PrimName (AST.NAttribute $ 
518                           AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing))]))
519              Nothing
520     plusgtExpr = AST.NSimple resId AST.:= 
521                    ((AST.PrimName $ AST.NSimple aPar) AST.:&: 
522                     (AST.PrimName $ AST.NSimple vecPar))
523     plusgtRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
524     emptySpec = AST.Function (mkVHDLExtId emptyId) [] vectorTM
525     emptyVar = 
526           AST.ConstDec resId 
527               (AST.SubtypeIn vectorTM Nothing)
528               (Just $ AST.PrimLit "\"\"")
529     emptyExpr = AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
530     singletonSpec = AST.Function (mkVHDLExtId singletonId) [AST.IfaceVarDec aPar elemTM ] 
531                                          vectorTM
532     -- variable res : fsvec_x (0 to 0) := (others => a);
533     singletonVar = 
534       AST.VarDec resId 
535              (AST.SubtypeIn vectorTM
536                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
537                 [AST.ToRange (AST.PrimLit "0") (AST.PrimLit "0")]))
538              (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
539                                           (AST.PrimName $ AST.NSimple aPar)])
540     singletonRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
541     copySpec = AST.Function (mkVHDLExtId copyId) [AST.IfaceVarDec nPar   naturalTM,
542                                    AST.IfaceVarDec aPar   elemTM   ] vectorTM 
543     -- variable res : fsvec_x (0 to n-1) := (others => a);
544     copyVar = 
545       AST.VarDec resId 
546              (AST.SubtypeIn vectorTM
547                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
548                 [AST.ToRange (AST.PrimLit "0")
549                             ((AST.PrimName (AST.NSimple nPar)) AST.:-:
550                              (AST.PrimLit "1"))   ]))
551              (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
552                                           (AST.PrimName $ AST.NSimple aPar)])
553     -- return res
554     copyExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
555     selSpec = AST.Function (mkVHDLExtId selId) [AST.IfaceVarDec fPar   naturalTM,
556                                AST.IfaceVarDec sPar   naturalTM,
557                                AST.IfaceVarDec nPar   naturalTM,
558                                AST.IfaceVarDec vecPar vectorTM ] vectorTM
559     -- variable res : fsvec_x (0 to n-1);
560     selVar = 
561       AST.VarDec resId 
562                 (AST.SubtypeIn vectorTM
563                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
564                     [AST.ToRange (AST.PrimLit "0")
565                       ((AST.PrimName (AST.NSimple nPar)) AST.:-:
566                       (AST.PrimLit "1"))   ])
567                 )
568                 Nothing
569     -- for i res'range loop
570     --   res(i) := vec(f+i*s);
571     -- end loop;
572     selFor = AST.ForSM iId (AST.AttribRange $ AST.AttribName (AST.NSimple resId) rangeId Nothing) [selAssign]
573     -- res(i) := vec(f+i*s);
574     selAssign = let origExp = AST.PrimName (AST.NSimple fPar) AST.:+: 
575                                 (AST.PrimName (AST.NSimple iId) AST.:*: 
576                                   AST.PrimName (AST.NSimple sPar)) in
577                                   AST.NIndexed (AST.IndexedName (AST.NSimple resId) [AST.PrimName (AST.NSimple iId)]) AST.:=
578                                     (AST.PrimName $ AST.NIndexed (AST.IndexedName (AST.NSimple vecPar) [origExp]))
579     -- return res;
580     selRet =  AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
581     ltplusSpec = AST.Function (mkVHDLExtId ltplusId) [AST.IfaceVarDec vecPar vectorTM,
582                                         AST.IfaceVarDec aPar   elemTM] vectorTM 
583      -- variable res : fsvec_x (0 to vec'length);
584     ltplusVar = 
585       AST.VarDec resId 
586         (AST.SubtypeIn vectorTM
587           (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
588             [AST.ToRange (AST.PrimLit "0")
589               (AST.PrimName (AST.NAttribute $ 
590                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing))]))
591         Nothing
592     ltplusExpr = AST.NSimple resId AST.:= 
593                      ((AST.PrimName $ AST.NSimple vecPar) AST.:&: 
594                       (AST.PrimName $ AST.NSimple aPar))
595     ltplusRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
596     plusplusSpec = AST.Function (mkVHDLExtId plusplusId) [AST.IfaceVarDec vec1Par vectorTM,
597                                              AST.IfaceVarDec vec2Par vectorTM] 
598                                              vectorTM 
599     -- variable res : fsvec_x (0 to vec1'length + vec2'length -1);
600     plusplusVar = 
601       AST.VarDec resId 
602         (AST.SubtypeIn vectorTM
603           (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
604             [AST.ToRange (AST.PrimLit "0")
605               (AST.PrimName (AST.NAttribute $ 
606                 AST.AttribName (AST.NSimple vec1Par) (mkVHDLBasicId lengthId) Nothing) AST.:+:
607                   AST.PrimName (AST.NAttribute $ 
608                 AST.AttribName (AST.NSimple vec2Par) (mkVHDLBasicId lengthId) Nothing) AST.:-:
609                   AST.PrimLit "1")]))
610        Nothing
611     plusplusExpr = AST.NSimple resId AST.:= 
612                      ((AST.PrimName $ AST.NSimple vec1Par) AST.:&: 
613                       (AST.PrimName $ AST.NSimple vec2Par))
614     plusplusRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
615     lengthTSpec = AST.Function (mkVHDLExtId lengthTId) [AST.IfaceVarDec vecPar vectorTM] naturalTM
616     lengthTExpr = AST.ReturnSm (Just $ AST.PrimName (AST.NAttribute $ 
617                                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing))
618
619 -----------------------------------------------------------------------------
620 -- A table of builtin functions
621 -----------------------------------------------------------------------------
622
623 -- | The builtin functions we support. Maps a name to an argument count and a
624 -- builder function.
625 globalNameTable :: NameTable
626 globalNameTable = Map.fromList
627   [ (exId             , (2, genFCall                ) )
628   , (replaceId        , (3, genFCall                ) )
629   , (headId           , (1, genFCall                ) )
630   , (lastId           , (1, genFCall                ) )
631   , (tailId           , (1, genFCall                ) )
632   , (initId           , (1, genFCall                ) )
633   , (takeId           , (2, genFCall                ) )
634   , (dropId           , (2, genFCall                ) )
635   , (selId            , (4, genFCall                ) )
636   , (plusgtId         , (2, genFCall                ) )
637   , (ltplusId         , (2, genFCall                ) )
638   , (plusplusId       , (2, genFCall                ) )
639   , (mapId            , (2, genMap                  ) )
640   , (zipWithId        , (3, genZipWith              ) )
641   , (foldlId          , (3, genFoldl                ) )
642   , (foldrId          , (3, genFoldr                ) )
643   , (zipId            , (2, genZip                  ) )
644   , (unzipId          , (1, genUnzip                ) )
645   , (emptyId          , (0, genFCall                ) )
646   , (singletonId      , (1, genFCall                ) )
647   , (copyId           , (2, genFCall                ) )
648   , (lengthTId        , (1, genFCall                ) )
649   , (hwxorId          , (2, genOperator2 AST.Xor    ) )
650   , (hwandId          , (2, genOperator2 AST.And    ) )
651   , (hworId           , (2, genOperator2 AST.Or     ) )
652   , (hwnotId          , (1, genOperator1 AST.Not    ) )
653   ]