691a27d06e39f9a3080954c9117ab7972e50fe4a
[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 -- | Generate a generate statement for the builtin function "zip"
226 genZip :: BuiltinBuilder
227 genZip = genVarArgs genZip'
228 genZip' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
229 genZip' (Left res) f args@[arg1, arg2] =
230   let
231     -- Setup the generate scheme
232     len             = (tfvec_len . Var.varType) res
233     -- TODO: Use something better than varToString
234     label           = mkVHDLExtId ("zipVector" ++ (varToString res))
235     n_id            = mkVHDLBasicId "n"
236     n_expr          = idToVHDLExpr n_id
237     range           = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
238     genScheme       = AST.ForGn n_id range
239     resname'        = mkIndexedName (varToVHDLName res) n_expr
240     argexpr1        = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg1) n_expr
241     argexpr2        = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg2) n_expr
242   in do
243     labels <- getFieldLabels (tfvec_elem (Var.varType res))
244     let resnameA    = mkSelectedName resname' (labels!!0)
245     let resnameB    = mkSelectedName resname' (labels!!1)
246     let resA_assign = mkUncondAssign (Right resnameA) argexpr1
247     let resB_assign = mkUncondAssign (Right resnameB) argexpr2
248     -- Return the generate functions
249     return [AST.CSGSm $ AST.GenerateSm label genScheme [] [resA_assign,resB_assign]]
250
251 -----------------------------------------------------------------------------
252 -- Function to generate VHDL for applications
253 -----------------------------------------------------------------------------
254 genApplication ::
255   (Either CoreSyn.CoreBndr AST.VHDLName) -- ^ Where to store the result?
256   -> CoreSyn.CoreBndr -- ^ The function to apply
257   -> [Either CoreSyn.CoreExpr AST.Expr] -- ^ The arguments to apply
258   -> VHDLSession [AST.ConcSm] -- ^ The resulting concurrent statements
259 genApplication dst f args =
260   case Var.globalIdVarDetails f of
261     IdInfo.DataConWorkId dc -> case dst of
262       -- It's a datacon. Create a record from its arguments.
263       Left bndr -> do
264         -- We have the bndr, so we can get at the type
265         labels <- getFieldLabels (Var.varType bndr)
266         return $ zipWith mkassign labels $ map (either exprToVHDLExpr id) args
267         where
268           mkassign :: AST.VHDLId -> AST.Expr -> AST.ConcSm
269           mkassign label arg =
270             let sel_name = mkSelectedName ((either varToVHDLName id) dst) label in
271             mkUncondAssign (Right sel_name) arg
272       Right _ -> error $ "Generate.genApplication Can't generate dataconstructor application without an original binder"
273     IdInfo.VanillaGlobal -> do
274       -- It's a global value imported from elsewhere. These can be builtin
275       -- functions. Look up the function name in the name table and execute
276       -- the associated builder if there is any and the argument count matches
277       -- (this should always be the case if it typechecks, but just to be
278       -- sure...).
279       case (Map.lookup (varToString f) globalNameTable) of
280         Just (arg_count, builder) ->
281           if length args == arg_count then
282             builder dst f args
283           else
284             error $ "Generate.genApplication Incorrect number of arguments to builtin function: " ++ pprString f ++ " Args: " ++ show args
285         Nothing -> error $ "Using function from another module that is not a known builtin: " ++ pprString f
286     IdInfo.NotGlobalId -> do
287       signatures <- getA vsSignatures
288       -- This is a local id, so it should be a function whose definition we
289       -- have and which can be turned into a component instantiation.
290       let  
291         signature = Maybe.fromMaybe 
292           (error $ "Using function '" ++ (varToString f) ++ "' without signature? This should not happen!") 
293           (Map.lookup f signatures)
294         entity_id = ent_id signature
295         -- TODO: Using show here isn't really pretty, but we'll need some
296         -- unique-ish value...
297         label = "comp_ins_" ++ (either show prettyShow) dst
298         portmaps = mkAssocElems (map (either exprToVHDLExpr id) args) ((either varToVHDLName id) dst) signature
299         in
300           return [mkComponentInst label entity_id portmaps]
301     details -> error $ "Calling unsupported function " ++ pprString f ++ " with GlobalIdDetails " ++ pprString details
302
303 -----------------------------------------------------------------------------
304 -- Functions to generate functions dealing with vectors.
305 -----------------------------------------------------------------------------
306
307 -- Returns the VHDLId of the vector function with the given name for the given
308 -- element type. Generates -- this function if needed.
309 vectorFunId :: Type.Type -> String -> VHDLSession AST.VHDLId
310 vectorFunId el_ty fname = do
311   elemTM <- vhdl_ty el_ty
312   -- TODO: This should not be duplicated from mk_vector_ty. Probably but it in
313   -- the VHDLState or something.
314   let vectorTM = mkVHDLExtId $ "vector_" ++ (AST.fromVHDLId elemTM)
315   typefuns <- getA vsTypeFuns
316   case Map.lookup (OrdType el_ty, fname) typefuns of
317     -- Function already generated, just return it
318     Just (id, _) -> return id
319     -- Function not generated yet, generate it
320     Nothing -> do
321       let functions = genUnconsVectorFuns elemTM vectorTM
322       case lookup fname functions of
323         Just body -> do
324           modA vsTypeFuns $ Map.insert (OrdType el_ty, fname) (function_id, body)
325           return function_id
326         Nothing -> error $ "I don't know how to generate vector function " ++ fname
327   where
328     function_id = mkVHDLExtId fname
329
330 genUnconsVectorFuns :: AST.TypeMark -- ^ type of the vector elements
331                     -> AST.TypeMark -- ^ type of the vector
332                     -> [(String, AST.SubProgBody)]
333 genUnconsVectorFuns elemTM vectorTM  = 
334   [ (exId, AST.SubProgBody exSpec      []                  [exExpr])
335   , (replaceId, AST.SubProgBody replaceSpec [AST.SPVD replaceVar] [replaceExpr,replaceRet])
336   , (headId, AST.SubProgBody headSpec    []                  [headExpr])
337   , (lastId, AST.SubProgBody lastSpec    []                  [lastExpr])
338   , (initId, AST.SubProgBody initSpec    [AST.SPVD initVar]  [initExpr, initRet])
339   , (tailId, AST.SubProgBody tailSpec    [AST.SPVD tailVar]  [tailExpr, tailRet])
340   , (takeId, AST.SubProgBody takeSpec    [AST.SPVD takeVar]  [takeExpr, takeRet])
341   , (dropId, AST.SubProgBody dropSpec    [AST.SPVD dropVar]  [dropExpr, dropRet])
342   , (plusgtId, AST.SubProgBody plusgtSpec  [AST.SPVD plusgtVar] [plusgtExpr, plusgtRet])
343   , (emptyId, AST.SubProgBody emptySpec   [AST.SPCD emptyVar] [emptyExpr])
344   , (singletonId, AST.SubProgBody singletonSpec [AST.SPVD singletonVar] [singletonRet])
345   , (copyId, AST.SubProgBody copySpec    [AST.SPVD copyVar]      [copyExpr])
346   , (selId, AST.SubProgBody selSpec  [AST.SPVD selVar] [selFor, selRet])
347   , (ltplusId, AST.SubProgBody ltplusSpec [AST.SPVD ltplusVar] [ltplusExpr, ltplusRet]  )  
348   , (plusplusId, AST.SubProgBody plusplusSpec [AST.SPVD plusplusVar] [plusplusExpr, plusplusRet])
349   ]
350   where 
351     ixPar   = AST.unsafeVHDLBasicId "ix"
352     vecPar  = AST.unsafeVHDLBasicId "vec"
353     vec1Par = AST.unsafeVHDLBasicId "vec1"
354     vec2Par = AST.unsafeVHDLBasicId "vec2"
355     nPar    = AST.unsafeVHDLBasicId "n"
356     iId     = AST.unsafeVHDLBasicId "i"
357     iPar    = iId
358     aPar    = AST.unsafeVHDLBasicId "a"
359     fPar = AST.unsafeVHDLBasicId "f"
360     sPar = AST.unsafeVHDLBasicId "s"
361     resId   = AST.unsafeVHDLBasicId "res"
362     exSpec = AST.Function (mkVHDLExtId exId) [AST.IfaceVarDec vecPar vectorTM,
363                                AST.IfaceVarDec ixPar  naturalTM] elemTM
364     exExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NIndexed 
365               (AST.IndexedName (AST.NSimple vecPar) [AST.PrimName $ 
366                 AST.NSimple ixPar]))
367     replaceSpec = AST.Function (mkVHDLExtId replaceId)  [ AST.IfaceVarDec vecPar vectorTM
368                                           , AST.IfaceVarDec iPar   naturalTM
369                                           , AST.IfaceVarDec aPar   elemTM
370                                           ] vectorTM 
371        -- variable res : fsvec_x (0 to vec'length-1);
372     replaceVar =
373          AST.VarDec resId 
374                 (AST.SubtypeIn vectorTM
375                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
376                    [AST.ToRange (AST.PrimLit "0")
377                             (AST.PrimName (AST.NAttribute $ 
378                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
379                                 (AST.PrimLit "1"))   ]))
380                 Nothing
381        --  res AST.:= vec(0 to i-1) & a & vec(i+1 to length'vec-1)
382     replaceExpr = AST.NSimple resId AST.:=
383            (vecSlice (AST.PrimLit "0") (AST.PrimName (AST.NSimple iPar) AST.:-: AST.PrimLit "1") AST.:&:
384             AST.PrimName (AST.NSimple aPar) AST.:&: 
385              vecSlice (AST.PrimName (AST.NSimple iPar) AST.:+: AST.PrimLit "1")
386                       ((AST.PrimName (AST.NAttribute $ 
387                                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing)) 
388                                                               AST.:-: AST.PrimLit "1"))
389     replaceRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
390     vecSlice init last =  AST.PrimName (AST.NSlice 
391                                         (AST.SliceName 
392                                               (AST.NSimple vecPar) 
393                                               (AST.ToRange init last)))
394     headSpec = AST.Function (mkVHDLExtId headId) [AST.IfaceVarDec vecPar vectorTM] elemTM
395        -- return vec(0);
396     headExpr = AST.ReturnSm (Just $ (AST.PrimName $ AST.NIndexed (AST.IndexedName 
397                     (AST.NSimple vecPar) [AST.PrimLit "0"])))
398     lastSpec = AST.Function (mkVHDLExtId lastId) [AST.IfaceVarDec vecPar vectorTM] elemTM
399        -- return vec(vec'length-1);
400     lastExpr = AST.ReturnSm (Just $ (AST.PrimName $ AST.NIndexed (AST.IndexedName 
401                     (AST.NSimple vecPar) 
402                     [AST.PrimName (AST.NAttribute $ 
403                                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
404                                                              AST.:-: AST.PrimLit "1"])))
405     initSpec = AST.Function (mkVHDLExtId initId) [AST.IfaceVarDec vecPar vectorTM] vectorTM 
406        -- variable res : fsvec_x (0 to vec'length-2);
407     initVar = 
408          AST.VarDec resId 
409                 (AST.SubtypeIn vectorTM
410                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
411                    [AST.ToRange (AST.PrimLit "0")
412                             (AST.PrimName (AST.NAttribute $ 
413                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
414                                 (AST.PrimLit "2"))   ]))
415                 Nothing
416        -- resAST.:= vec(0 to vec'length-2)
417     initExpr = AST.NSimple resId AST.:= (vecSlice 
418                                (AST.PrimLit "0") 
419                                (AST.PrimName (AST.NAttribute $ 
420                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
421                                                              AST.:-: AST.PrimLit "2"))
422     initRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
423     tailSpec = AST.Function (mkVHDLExtId tailId) [AST.IfaceVarDec vecPar vectorTM] vectorTM
424        -- variable res : fsvec_x (0 to vec'length-2); 
425     tailVar = 
426          AST.VarDec resId 
427                 (AST.SubtypeIn vectorTM
428                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
429                    [AST.ToRange (AST.PrimLit "0")
430                             (AST.PrimName (AST.NAttribute $ 
431                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
432                                 (AST.PrimLit "2"))   ]))
433                 Nothing       
434        -- res AST.:= vec(1 to vec'length-1)
435     tailExpr = AST.NSimple resId AST.:= (vecSlice 
436                                (AST.PrimLit "1") 
437                                (AST.PrimName (AST.NAttribute $ 
438                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
439                                                              AST.:-: AST.PrimLit "1"))
440     tailRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
441     takeSpec = AST.Function (mkVHDLExtId takeId) [AST.IfaceVarDec nPar   naturalTM,
442                                    AST.IfaceVarDec vecPar vectorTM ] vectorTM
443        -- variable res : fsvec_x (0 to n-1);
444     takeVar = 
445          AST.VarDec resId 
446                 (AST.SubtypeIn vectorTM
447                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
448                    [AST.ToRange (AST.PrimLit "0")
449                                ((AST.PrimName (AST.NSimple nPar)) AST.:-:
450                                 (AST.PrimLit "1"))   ]))
451                 Nothing
452        -- res AST.:= vec(0 to n-1)
453     takeExpr = AST.NSimple resId AST.:= 
454                     (vecSlice (AST.PrimLit "1") 
455                               (AST.PrimName (AST.NSimple $ nPar) AST.:-: AST.PrimLit "1"))
456     takeRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
457     dropSpec = AST.Function (mkVHDLExtId dropId) [AST.IfaceVarDec nPar   naturalTM,
458                                    AST.IfaceVarDec vecPar vectorTM ] vectorTM 
459        -- variable res : fsvec_x (0 to vec'length-n-1);
460     dropVar = 
461          AST.VarDec resId 
462                 (AST.SubtypeIn vectorTM
463                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
464                    [AST.ToRange (AST.PrimLit "0")
465                             (AST.PrimName (AST.NAttribute $ 
466                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
467                                (AST.PrimName $ AST.NSimple nPar)AST.:-: (AST.PrimLit "1")) ]))
468                Nothing
469        -- res AST.:= vec(n to vec'length-1)
470     dropExpr = AST.NSimple resId AST.:= (vecSlice 
471                                (AST.PrimName $ AST.NSimple nPar) 
472                                (AST.PrimName (AST.NAttribute $ 
473                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
474                                                              AST.:-: AST.PrimLit "1"))
475     dropRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
476     plusgtSpec = AST.Function (mkVHDLExtId plusgtId) [AST.IfaceVarDec aPar   elemTM,
477                                        AST.IfaceVarDec vecPar vectorTM] vectorTM 
478     -- variable res : fsvec_x (0 to vec'length);
479     plusgtVar = 
480       AST.VarDec resId 
481              (AST.SubtypeIn vectorTM
482                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
483                 [AST.ToRange (AST.PrimLit "0")
484                         (AST.PrimName (AST.NAttribute $ 
485                           AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing))]))
486              Nothing
487     plusgtExpr = AST.NSimple resId AST.:= 
488                    ((AST.PrimName $ AST.NSimple aPar) AST.:&: 
489                     (AST.PrimName $ AST.NSimple vecPar))
490     plusgtRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
491     emptySpec = AST.Function (mkVHDLExtId emptyId) [] vectorTM
492     emptyVar = 
493           AST.ConstDec resId 
494               (AST.SubtypeIn vectorTM Nothing)
495               (Just $ AST.PrimLit "\"\"")
496     emptyExpr = AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
497     singletonSpec = AST.Function (mkVHDLExtId singletonId) [AST.IfaceVarDec aPar elemTM ] 
498                                          vectorTM
499     -- variable res : fsvec_x (0 to 0) := (others => a);
500     singletonVar = 
501       AST.VarDec resId 
502              (AST.SubtypeIn vectorTM
503                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
504                 [AST.ToRange (AST.PrimLit "0") (AST.PrimLit "0")]))
505              (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
506                                           (AST.PrimName $ AST.NSimple aPar)])
507     singletonRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
508     copySpec = AST.Function (mkVHDLExtId copyId) [AST.IfaceVarDec nPar   naturalTM,
509                                    AST.IfaceVarDec aPar   elemTM   ] vectorTM 
510     -- variable res : fsvec_x (0 to n-1) := (others => a);
511     copyVar = 
512       AST.VarDec resId 
513              (AST.SubtypeIn vectorTM
514                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
515                 [AST.ToRange (AST.PrimLit "0")
516                             ((AST.PrimName (AST.NSimple nPar)) AST.:-:
517                              (AST.PrimLit "1"))   ]))
518              (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
519                                           (AST.PrimName $ AST.NSimple aPar)])
520     -- return res
521     copyExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
522     selSpec = AST.Function (mkVHDLExtId selId) [AST.IfaceVarDec fPar   naturalTM,
523                                AST.IfaceVarDec sPar   naturalTM,
524                                AST.IfaceVarDec nPar   naturalTM,
525                                AST.IfaceVarDec vecPar vectorTM ] vectorTM
526     -- variable res : fsvec_x (0 to n-1);
527     selVar = 
528       AST.VarDec resId 
529                 (AST.SubtypeIn vectorTM
530                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
531                     [AST.ToRange (AST.PrimLit "0")
532                       ((AST.PrimName (AST.NSimple nPar)) AST.:-:
533                       (AST.PrimLit "1"))   ])
534                 )
535                 Nothing
536     -- for i res'range loop
537     --   res(i) := vec(f+i*s);
538     -- end loop;
539     selFor = AST.ForSM iId (AST.AttribRange $ AST.AttribName (AST.NSimple resId) rangeId Nothing) [selAssign]
540     -- res(i) := vec(f+i*s);
541     selAssign = let origExp = AST.PrimName (AST.NSimple fPar) AST.:+: 
542                                 (AST.PrimName (AST.NSimple iId) AST.:*: 
543                                   AST.PrimName (AST.NSimple sPar)) in
544                                   AST.NIndexed (AST.IndexedName (AST.NSimple resId) [AST.PrimName (AST.NSimple iId)]) AST.:=
545                                     (AST.PrimName $ AST.NIndexed (AST.IndexedName (AST.NSimple vecPar) [origExp]))
546     -- return res;
547     selRet =  AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
548     ltplusSpec = AST.Function (mkVHDLExtId ltplusId) [AST.IfaceVarDec vecPar vectorTM,
549                                         AST.IfaceVarDec aPar   elemTM] vectorTM 
550      -- variable res : fsvec_x (0 to vec'length);
551     ltplusVar = 
552       AST.VarDec resId 
553         (AST.SubtypeIn vectorTM
554           (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
555             [AST.ToRange (AST.PrimLit "0")
556               (AST.PrimName (AST.NAttribute $ 
557                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing))]))
558         Nothing
559     ltplusExpr = AST.NSimple resId AST.:= 
560                      ((AST.PrimName $ AST.NSimple vecPar) AST.:&: 
561                       (AST.PrimName $ AST.NSimple aPar))
562     ltplusRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
563     plusplusSpec = AST.Function (mkVHDLExtId plusplusId) [AST.IfaceVarDec vec1Par vectorTM,
564                                              AST.IfaceVarDec vec2Par vectorTM] 
565                                              vectorTM 
566     -- variable res : fsvec_x (0 to vec1'length + vec2'length -1);
567     plusplusVar = 
568       AST.VarDec resId 
569         (AST.SubtypeIn vectorTM
570           (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
571             [AST.ToRange (AST.PrimLit "0")
572               (AST.PrimName (AST.NAttribute $ 
573                 AST.AttribName (AST.NSimple vec1Par) (mkVHDLBasicId lengthId) Nothing) AST.:+:
574                   AST.PrimName (AST.NAttribute $ 
575                 AST.AttribName (AST.NSimple vec2Par) (mkVHDLBasicId lengthId) Nothing) AST.:-:
576                   AST.PrimLit "1")]))
577        Nothing
578     plusplusExpr = AST.NSimple resId AST.:= 
579                      ((AST.PrimName $ AST.NSimple vec1Par) AST.:&: 
580                       (AST.PrimName $ AST.NSimple vec2Par))
581     plusplusRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
582
583 -----------------------------------------------------------------------------
584 -- A table of builtin functions
585 -----------------------------------------------------------------------------
586
587 -- | The builtin functions we support. Maps a name to an argument count and a
588 -- builder function.
589 globalNameTable :: NameTable
590 globalNameTable = Map.fromList
591   [ (exId             , (2, genFCall                ) )
592   , (replaceId        , (3, genFCall                ) )
593   , (headId           , (1, genFCall                ) )
594   , (lastId           , (1, genFCall                ) )
595   , (tailId           , (1, genFCall                ) )
596   , (initId           , (1, genFCall                ) )
597   , (takeId           , (2, genFCall                ) )
598   , (dropId           , (2, genFCall                ) )
599   , (selId            , (4, genFCall                ) )
600   , (plusgtId         , (2, genFCall                ) )
601   , (ltplusId         , (2, genFCall                ) )
602   , (plusplusId       , (2, genFCall                ) )
603   , (mapId            , (2, genMap                  ) )
604   , (zipWithId        , (3, genZipWith              ) )
605   , (foldlId          , (3, genFoldl                ) )
606   , (foldrId          , (3, genFoldr                ) )
607   , (zipId            , (2, genZip                  ) )
608   , (emptyId          , (0, genFCall                ) )
609   , (singletonId      , (1, genFCall                ) )
610   , (copyId           , (2, genFCall                ) )
611   , (hwxorId          , (2, genOperator2 AST.Xor    ) )
612   , (hwandId          , (2, genOperator2 AST.And    ) )
613   , (hworId           , (2, genOperator2 AST.Or     ) )
614   , (hwnotId          , (1, genOperator1 AST.Not    ) )
615   ]