Merge git://github.com/darchon/clash into cλash
[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   ]
382   where 
383     ixPar   = AST.unsafeVHDLBasicId "ix"
384     vecPar  = AST.unsafeVHDLBasicId "vec"
385     vec1Par = AST.unsafeVHDLBasicId "vec1"
386     vec2Par = AST.unsafeVHDLBasicId "vec2"
387     nPar    = AST.unsafeVHDLBasicId "n"
388     iId     = AST.unsafeVHDLBasicId "i"
389     iPar    = iId
390     aPar    = AST.unsafeVHDLBasicId "a"
391     fPar = AST.unsafeVHDLBasicId "f"
392     sPar = AST.unsafeVHDLBasicId "s"
393     resId   = AST.unsafeVHDLBasicId "res"
394     exSpec = AST.Function (mkVHDLExtId exId) [AST.IfaceVarDec vecPar vectorTM,
395                                AST.IfaceVarDec ixPar  naturalTM] elemTM
396     exExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NIndexed 
397               (AST.IndexedName (AST.NSimple vecPar) [AST.PrimName $ 
398                 AST.NSimple ixPar]))
399     replaceSpec = AST.Function (mkVHDLExtId replaceId)  [ AST.IfaceVarDec vecPar vectorTM
400                                           , AST.IfaceVarDec iPar   naturalTM
401                                           , AST.IfaceVarDec aPar   elemTM
402                                           ] vectorTM 
403        -- variable res : fsvec_x (0 to vec'length-1);
404     replaceVar =
405          AST.VarDec resId 
406                 (AST.SubtypeIn vectorTM
407                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
408                    [AST.ToRange (AST.PrimLit "0")
409                             (AST.PrimName (AST.NAttribute $ 
410                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
411                                 (AST.PrimLit "1"))   ]))
412                 Nothing
413        --  res AST.:= vec(0 to i-1) & a & vec(i+1 to length'vec-1)
414     replaceExpr = AST.NSimple resId AST.:=
415            (vecSlice (AST.PrimLit "0") (AST.PrimName (AST.NSimple iPar) AST.:-: AST.PrimLit "1") AST.:&:
416             AST.PrimName (AST.NSimple aPar) AST.:&: 
417              vecSlice (AST.PrimName (AST.NSimple iPar) AST.:+: AST.PrimLit "1")
418                       ((AST.PrimName (AST.NAttribute $ 
419                                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing)) 
420                                                               AST.:-: AST.PrimLit "1"))
421     replaceRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
422     vecSlice init last =  AST.PrimName (AST.NSlice 
423                                         (AST.SliceName 
424                                               (AST.NSimple vecPar) 
425                                               (AST.ToRange init last)))
426     headSpec = AST.Function (mkVHDLExtId headId) [AST.IfaceVarDec vecPar vectorTM] elemTM
427        -- return vec(0);
428     headExpr = AST.ReturnSm (Just $ (AST.PrimName $ AST.NIndexed (AST.IndexedName 
429                     (AST.NSimple vecPar) [AST.PrimLit "0"])))
430     lastSpec = AST.Function (mkVHDLExtId lastId) [AST.IfaceVarDec vecPar vectorTM] elemTM
431        -- return vec(vec'length-1);
432     lastExpr = AST.ReturnSm (Just $ (AST.PrimName $ AST.NIndexed (AST.IndexedName 
433                     (AST.NSimple vecPar) 
434                     [AST.PrimName (AST.NAttribute $ 
435                                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
436                                                              AST.:-: AST.PrimLit "1"])))
437     initSpec = AST.Function (mkVHDLExtId initId) [AST.IfaceVarDec vecPar vectorTM] vectorTM 
438        -- variable res : fsvec_x (0 to vec'length-2);
439     initVar = 
440          AST.VarDec resId 
441                 (AST.SubtypeIn vectorTM
442                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
443                    [AST.ToRange (AST.PrimLit "0")
444                             (AST.PrimName (AST.NAttribute $ 
445                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
446                                 (AST.PrimLit "2"))   ]))
447                 Nothing
448        -- resAST.:= vec(0 to vec'length-2)
449     initExpr = AST.NSimple resId AST.:= (vecSlice 
450                                (AST.PrimLit "0") 
451                                (AST.PrimName (AST.NAttribute $ 
452                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
453                                                              AST.:-: AST.PrimLit "2"))
454     initRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
455     tailSpec = AST.Function (mkVHDLExtId tailId) [AST.IfaceVarDec vecPar vectorTM] vectorTM
456        -- variable res : fsvec_x (0 to vec'length-2); 
457     tailVar = 
458          AST.VarDec resId 
459                 (AST.SubtypeIn vectorTM
460                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
461                    [AST.ToRange (AST.PrimLit "0")
462                             (AST.PrimName (AST.NAttribute $ 
463                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
464                                 (AST.PrimLit "2"))   ]))
465                 Nothing       
466        -- res AST.:= vec(1 to vec'length-1)
467     tailExpr = AST.NSimple resId AST.:= (vecSlice 
468                                (AST.PrimLit "1") 
469                                (AST.PrimName (AST.NAttribute $ 
470                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
471                                                              AST.:-: AST.PrimLit "1"))
472     tailRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
473     takeSpec = AST.Function (mkVHDLExtId takeId) [AST.IfaceVarDec nPar   naturalTM,
474                                    AST.IfaceVarDec vecPar vectorTM ] vectorTM
475        -- variable res : fsvec_x (0 to n-1);
476     takeVar = 
477          AST.VarDec resId 
478                 (AST.SubtypeIn vectorTM
479                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
480                    [AST.ToRange (AST.PrimLit "0")
481                                ((AST.PrimName (AST.NSimple nPar)) AST.:-:
482                                 (AST.PrimLit "1"))   ]))
483                 Nothing
484        -- res AST.:= vec(0 to n-1)
485     takeExpr = AST.NSimple resId AST.:= 
486                     (vecSlice (AST.PrimLit "1") 
487                               (AST.PrimName (AST.NSimple $ nPar) AST.:-: AST.PrimLit "1"))
488     takeRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
489     dropSpec = AST.Function (mkVHDLExtId dropId) [AST.IfaceVarDec nPar   naturalTM,
490                                    AST.IfaceVarDec vecPar vectorTM ] vectorTM 
491        -- variable res : fsvec_x (0 to vec'length-n-1);
492     dropVar = 
493          AST.VarDec resId 
494                 (AST.SubtypeIn vectorTM
495                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
496                    [AST.ToRange (AST.PrimLit "0")
497                             (AST.PrimName (AST.NAttribute $ 
498                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
499                                (AST.PrimName $ AST.NSimple nPar)AST.:-: (AST.PrimLit "1")) ]))
500                Nothing
501        -- res AST.:= vec(n to vec'length-1)
502     dropExpr = AST.NSimple resId AST.:= (vecSlice 
503                                (AST.PrimName $ AST.NSimple nPar) 
504                                (AST.PrimName (AST.NAttribute $ 
505                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
506                                                              AST.:-: AST.PrimLit "1"))
507     dropRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
508     plusgtSpec = AST.Function (mkVHDLExtId plusgtId) [AST.IfaceVarDec aPar   elemTM,
509                                        AST.IfaceVarDec vecPar vectorTM] vectorTM 
510     -- variable res : fsvec_x (0 to vec'length);
511     plusgtVar = 
512       AST.VarDec resId 
513              (AST.SubtypeIn vectorTM
514                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
515                 [AST.ToRange (AST.PrimLit "0")
516                         (AST.PrimName (AST.NAttribute $ 
517                           AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing))]))
518              Nothing
519     plusgtExpr = AST.NSimple resId AST.:= 
520                    ((AST.PrimName $ AST.NSimple aPar) AST.:&: 
521                     (AST.PrimName $ AST.NSimple vecPar))
522     plusgtRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
523     emptySpec = AST.Function (mkVHDLExtId emptyId) [] vectorTM
524     emptyVar = 
525           AST.ConstDec resId 
526               (AST.SubtypeIn vectorTM Nothing)
527               (Just $ AST.PrimLit "\"\"")
528     emptyExpr = AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
529     singletonSpec = AST.Function (mkVHDLExtId singletonId) [AST.IfaceVarDec aPar elemTM ] 
530                                          vectorTM
531     -- variable res : fsvec_x (0 to 0) := (others => a);
532     singletonVar = 
533       AST.VarDec resId 
534              (AST.SubtypeIn vectorTM
535                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
536                 [AST.ToRange (AST.PrimLit "0") (AST.PrimLit "0")]))
537              (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
538                                           (AST.PrimName $ AST.NSimple aPar)])
539     singletonRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
540     copySpec = AST.Function (mkVHDLExtId copyId) [AST.IfaceVarDec nPar   naturalTM,
541                                    AST.IfaceVarDec aPar   elemTM   ] vectorTM 
542     -- variable res : fsvec_x (0 to n-1) := (others => a);
543     copyVar = 
544       AST.VarDec resId 
545              (AST.SubtypeIn vectorTM
546                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
547                 [AST.ToRange (AST.PrimLit "0")
548                             ((AST.PrimName (AST.NSimple nPar)) AST.:-:
549                              (AST.PrimLit "1"))   ]))
550              (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
551                                           (AST.PrimName $ AST.NSimple aPar)])
552     -- return res
553     copyExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
554     selSpec = AST.Function (mkVHDLExtId selId) [AST.IfaceVarDec fPar   naturalTM,
555                                AST.IfaceVarDec sPar   naturalTM,
556                                AST.IfaceVarDec nPar   naturalTM,
557                                AST.IfaceVarDec vecPar vectorTM ] vectorTM
558     -- variable res : fsvec_x (0 to n-1);
559     selVar = 
560       AST.VarDec resId 
561                 (AST.SubtypeIn vectorTM
562                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
563                     [AST.ToRange (AST.PrimLit "0")
564                       ((AST.PrimName (AST.NSimple nPar)) AST.:-:
565                       (AST.PrimLit "1"))   ])
566                 )
567                 Nothing
568     -- for i res'range loop
569     --   res(i) := vec(f+i*s);
570     -- end loop;
571     selFor = AST.ForSM iId (AST.AttribRange $ AST.AttribName (AST.NSimple resId) rangeId Nothing) [selAssign]
572     -- res(i) := vec(f+i*s);
573     selAssign = let origExp = AST.PrimName (AST.NSimple fPar) AST.:+: 
574                                 (AST.PrimName (AST.NSimple iId) AST.:*: 
575                                   AST.PrimName (AST.NSimple sPar)) in
576                                   AST.NIndexed (AST.IndexedName (AST.NSimple resId) [AST.PrimName (AST.NSimple iId)]) AST.:=
577                                     (AST.PrimName $ AST.NIndexed (AST.IndexedName (AST.NSimple vecPar) [origExp]))
578     -- return res;
579     selRet =  AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
580     ltplusSpec = AST.Function (mkVHDLExtId ltplusId) [AST.IfaceVarDec vecPar vectorTM,
581                                         AST.IfaceVarDec aPar   elemTM] vectorTM 
582      -- variable res : fsvec_x (0 to vec'length);
583     ltplusVar = 
584       AST.VarDec resId 
585         (AST.SubtypeIn vectorTM
586           (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
587             [AST.ToRange (AST.PrimLit "0")
588               (AST.PrimName (AST.NAttribute $ 
589                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing))]))
590         Nothing
591     ltplusExpr = AST.NSimple resId AST.:= 
592                      ((AST.PrimName $ AST.NSimple vecPar) AST.:&: 
593                       (AST.PrimName $ AST.NSimple aPar))
594     ltplusRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
595     plusplusSpec = AST.Function (mkVHDLExtId plusplusId) [AST.IfaceVarDec vec1Par vectorTM,
596                                              AST.IfaceVarDec vec2Par vectorTM] 
597                                              vectorTM 
598     -- variable res : fsvec_x (0 to vec1'length + vec2'length -1);
599     plusplusVar = 
600       AST.VarDec resId 
601         (AST.SubtypeIn vectorTM
602           (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
603             [AST.ToRange (AST.PrimLit "0")
604               (AST.PrimName (AST.NAttribute $ 
605                 AST.AttribName (AST.NSimple vec1Par) (mkVHDLBasicId lengthId) Nothing) AST.:+:
606                   AST.PrimName (AST.NAttribute $ 
607                 AST.AttribName (AST.NSimple vec2Par) (mkVHDLBasicId lengthId) Nothing) AST.:-:
608                   AST.PrimLit "1")]))
609        Nothing
610     plusplusExpr = AST.NSimple resId AST.:= 
611                      ((AST.PrimName $ AST.NSimple vec1Par) AST.:&: 
612                       (AST.PrimName $ AST.NSimple vec2Par))
613     plusplusRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
614
615 -----------------------------------------------------------------------------
616 -- A table of builtin functions
617 -----------------------------------------------------------------------------
618
619 -- | The builtin functions we support. Maps a name to an argument count and a
620 -- builder function.
621 globalNameTable :: NameTable
622 globalNameTable = Map.fromList
623   [ (exId             , (2, genFCall                ) )
624   , (replaceId        , (3, genFCall                ) )
625   , (headId           , (1, genFCall                ) )
626   , (lastId           , (1, genFCall                ) )
627   , (tailId           , (1, genFCall                ) )
628   , (initId           , (1, genFCall                ) )
629   , (takeId           , (2, genFCall                ) )
630   , (dropId           , (2, genFCall                ) )
631   , (selId            , (4, genFCall                ) )
632   , (plusgtId         , (2, genFCall                ) )
633   , (ltplusId         , (2, genFCall                ) )
634   , (plusplusId       , (2, genFCall                ) )
635   , (mapId            , (2, genMap                  ) )
636   , (zipWithId        , (3, genZipWith              ) )
637   , (foldlId          , (3, genFoldl                ) )
638   , (foldrId          , (3, genFoldr                ) )
639   , (zipId            , (2, genZip                  ) )
640   , (unzipId          , (1, genUnzip                ) )
641   , (emptyId          , (0, genFCall                ) )
642   , (singletonId      , (1, genFCall                ) )
643   , (copyId           , (2, genFCall                ) )
644   , (hwxorId          , (2, genOperator2 AST.Xor    ) )
645   , (hwandId          , (2, genOperator2 AST.And    ) )
646   , (hworId           , (2, genOperator2 AST.Or     ) )
647   , (hwnotId          , (1, genOperator1 AST.Not    ) )
648   ]