Builtin builder arguments now get an extra Type.Type
[matthijs/master-project/cλash.git] / clash / CLasH / VHDL / Generate.hs
1 module CLasH.VHDL.Generate where
2
3 -- Standard modules
4 import qualified Data.List as List
5 import qualified Data.Map as Map
6 import qualified Control.Monad as Monad
7 import qualified Maybe
8 import qualified Data.Either as Either
9 import qualified Data.Accessor.Monad.Trans.State as MonadState
10
11 -- VHDL Imports
12 import qualified Language.VHDL.AST as AST
13
14 -- GHC API
15 import qualified CoreSyn
16 import qualified Type
17 import qualified Var
18 import qualified Id
19 import qualified IdInfo
20 import qualified Literal
21 import qualified Name
22 import qualified TyCon
23 import qualified CoreUtils
24
25 -- Local imports
26 import CLasH.Translator.TranslatorTypes
27 import CLasH.VHDL.Constants
28 import CLasH.VHDL.VHDLTypes
29 import CLasH.VHDL.VHDLTools
30 import CLasH.Utils
31 import CLasH.Utils.Core.CoreTools
32 import CLasH.Utils.Pretty
33 import qualified CLasH.Normalize as Normalize
34
35 -----------------------------------------------------------------------------
36 -- Functions to generate VHDL for user-defined functions.
37 -----------------------------------------------------------------------------
38
39 -- | Create an entity for a given function
40 getEntity ::
41   CoreSyn.CoreBndr
42   -> TranslatorSession Entity -- ^ The resulting entity
43
44 getEntity fname = makeCached fname tsEntities $ do
45       expr <- Normalize.getNormalized False fname
46       -- Split the normalized expression
47       let (args, binds, res) = Normalize.splitNormalized expr
48       -- Generate ports for all non-empty types
49       args' <- catMaybesM $ mapM mkMap args
50       -- TODO: Handle Nothing
51       res' <- mkMap res
52       count <- MonadState.get tsEntityCounter 
53       let vhdl_id = mkVHDLBasicId $ varToString fname ++ "Component_" ++ show count
54       MonadState.set tsEntityCounter (count + 1)
55       let ent_decl = createEntityAST vhdl_id args' res'
56       let signature = Entity vhdl_id args' res' ent_decl
57       return signature
58   where
59     mkMap ::
60       --[(SignalId, SignalInfo)] 
61       CoreSyn.CoreBndr 
62       -> TranslatorSession (Maybe Port)
63     mkMap = (\bndr ->
64       let
65         --info = Maybe.fromMaybe
66         --  (error $ "Signal not found in the name map? This should not happen!")
67         --  (lookup id sigmap)
68         --  Assume the bndr has a valid VHDL id already
69         id = varToVHDLId bndr
70         ty = Var.varType bndr
71         error_msg = "\nVHDL.createEntity.mkMap: Can not create entity: " ++ pprString fname ++ "\nbecause no type can be created for port: " ++ pprString bndr 
72       in do
73         type_mark_maybe <- MonadState.lift tsType $ vhdlTy error_msg ty
74         case type_mark_maybe of 
75           Just type_mark -> return $ Just (id, type_mark)
76           Nothing -> return Nothing
77      )
78
79 -- | Create the VHDL AST for an entity
80 createEntityAST ::
81   AST.VHDLId                   -- ^ The name of the function
82   -> [Port]                    -- ^ The entity's arguments
83   -> Maybe Port                -- ^ The entity's result
84   -> AST.EntityDec             -- ^ The entity with the ent_decl filled in as well
85
86 createEntityAST vhdl_id args res =
87   AST.EntityDec vhdl_id ports
88   where
89     -- Create a basic Id, since VHDL doesn't grok filenames with extended Ids.
90     ports = map (mkIfaceSigDec AST.In) args
91               ++ (Maybe.maybeToList res_port)
92               ++ [clk_port,resetn_port]
93     -- Add a clk port if we have state
94     clk_port = AST.IfaceSigDec clockId AST.In std_logicTM
95     resetn_port = AST.IfaceSigDec resetId AST.In std_logicTM
96     res_port = fmap (mkIfaceSigDec AST.Out) res
97
98 -- | Create a port declaration
99 mkIfaceSigDec ::
100   AST.Mode                         -- ^ The mode for the port (In / Out)
101   -> Port                          -- ^ The id and type for the port
102   -> AST.IfaceSigDec               -- ^ The resulting port declaration
103
104 mkIfaceSigDec mode (id, ty) = AST.IfaceSigDec id mode ty
105
106 -- | Create an architecture for a given function
107 getArchitecture ::
108   CoreSyn.CoreBndr -- ^ The function to get an architecture for
109   -> TranslatorSession (Architecture, [CoreSyn.CoreBndr])
110   -- ^ The architecture for this function
111
112 getArchitecture fname = makeCached fname tsArchitectures $ do
113   expr <- Normalize.getNormalized False fname
114   -- Split the normalized expression
115   let (args, binds, res) = Normalize.splitNormalized expr
116   
117   -- Get the entity for this function
118   signature <- getEntity fname
119   let entity_id = ent_id signature
120
121   -- Create signal declarations for all binders in the let expression, except
122   -- for the output port (that will already have an output port declared in
123   -- the entity).
124   sig_dec_maybes <- mapM (mkSigDec . fst) (filter ((/=res).fst) binds)
125   let sig_decs = Maybe.catMaybes sig_dec_maybes
126   -- Process each bind, resulting in info about state variables and concurrent
127   -- statements.
128   (state_vars, sms) <- Monad.mapAndUnzipM dobind binds
129   let (in_state_maybes, out_state_maybes) = unzip state_vars
130   let (statementss, used_entitiess) = unzip sms
131   -- Get initial state, if it's there
132   initSmap <- MonadState.get tsInitStates
133   let init_state = Map.lookup fname initSmap
134   -- Create a state proc, if needed
135   (state_proc, resbndr) <- case (Maybe.catMaybes in_state_maybes, Maybe.catMaybes out_state_maybes, init_state) of
136         ([in_state], [out_state], Nothing) -> do 
137           nonEmpty <- hasNonEmptyType in_state
138           if nonEmpty 
139             then error ("No initial state defined for: " ++ show fname) 
140             else return ([],[])
141         ([in_state], [out_state], Just resetval) -> do
142           nonEmpty <- hasNonEmptyType in_state
143           if nonEmpty 
144             then mkStateProcSm (in_state, out_state, resetval)
145             else error ("Initial state defined for function with only substate: " ++ show fname)
146         ([], [], Just _) -> error $ "Initial state defined for state-less function: " ++ show fname
147         ([], [], Nothing) -> return ([],[])
148         (ins, outs, res) -> error $ "Weird use of state in " ++ show fname ++ ". In: " ++ show ins ++ " Out: " ++ show outs
149   -- Join the create statements and the (optional) state_proc
150   let statements = concat statementss ++ state_proc
151   -- Create the architecture
152   let arch = AST.ArchBody (mkVHDLBasicId "structural") (AST.NSimple entity_id) (map AST.BDISD sig_decs) statements
153   let used_entities = (concat used_entitiess) ++ resbndr
154   return (arch, used_entities)
155   where
156     dobind :: (CoreSyn.CoreBndr, CoreSyn.CoreExpr) -- ^ The bind to process
157               -> TranslatorSession ((Maybe CoreSyn.CoreBndr, Maybe CoreSyn.CoreBndr), ([AST.ConcSm], [CoreSyn.CoreBndr]))
158               -- ^ ((Input state variable, output state variable), (statements, used entities))
159     -- newtype unpacking is just a cast
160     dobind (bndr, unpacked@(CoreSyn.Cast packed coercion)) 
161       | hasStateType packed && not (hasStateType unpacked)
162       = return ((Just bndr, Nothing), ([], []))
163     -- With simplCore, newtype packing is just a cast
164     dobind (bndr, packed@(CoreSyn.Cast unpacked@(CoreSyn.Var state) coercion)) 
165       | hasStateType packed && not (hasStateType unpacked)
166       = return ((Nothing, Just state), ([], []))
167     -- Without simplCore, newtype packing uses a data constructor
168     dobind (bndr, (CoreSyn.App (CoreSyn.App (CoreSyn.Var con) (CoreSyn.Type _)) (CoreSyn.Var state))) 
169       | isStateCon con
170       = return ((Nothing, Just state), ([], []))
171     -- Anything else is handled by mkConcSm
172     dobind bind = do
173       sms <- mkConcSm bind
174       return ((Nothing, Nothing), sms)
175
176 mkStateProcSm :: 
177   (CoreSyn.CoreBndr, CoreSyn.CoreBndr, CoreSyn.CoreBndr) -- ^ The current state, new state and reset variables
178   -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr]) -- ^ The resulting statements
179 mkStateProcSm (old, new, res) = do
180   let error_msg = "\nVHDL.mkSigDec: Can not make signal declaration for type: \n" ++ pprString res 
181   type_mark_old_maybe <- MonadState.lift tsType $ vhdlTy error_msg (Var.varType old)
182   let type_mark_old = Maybe.fromMaybe 
183                         (error $ "\nGenerate.mkStateProcSm: empty type for state? Type: " ++ pprString (Var.varType old))
184                         type_mark_old_maybe
185   type_mark_res_maybe <- MonadState.lift tsType $ vhdlTy error_msg (Var.varType res)
186   let type_mark_res' = Maybe.fromMaybe 
187                         (error $ "\nGenerate.mkStateProcSm: empty type for initial state? Type: " ++ pprString (Var.varType res))
188                         type_mark_res_maybe
189   let type_mark_res = if type_mark_old == type_mark_res' then
190                         type_mark_res'
191                       else 
192                         error $ "Initial state has different type than state type, state type: " ++ show type_mark_old ++ ", init type: "  ++ show type_mark_res'    
193   let resvalid  = mkVHDLExtId $ varToString res ++ "val"
194   let resvaldec = AST.BDISD $ AST.SigDec resvalid type_mark_res Nothing
195   let reswform  = AST.Wform [AST.WformElem (AST.PrimName $ AST.NSimple resvalid) Nothing]
196   let res_assign = AST.SigAssign (varToVHDLName old) reswform
197   let blocklabel       = mkVHDLBasicId "state"
198   let statelabel  = mkVHDLBasicId "stateupdate"
199   let rising_edge = AST.NSimple $ mkVHDLBasicId "rising_edge"
200   let wform       = AST.Wform [AST.WformElem (AST.PrimName $ varToVHDLName new) Nothing]
201   let clk_assign      = AST.SigAssign (varToVHDLName old) wform
202   let rising_edge_clk = AST.PrimFCall $ AST.FCall rising_edge [Nothing AST.:=>: (AST.ADName $ AST.NSimple clockId)]
203   let resetn_is_low  = (AST.PrimName $ AST.NSimple resetId) AST.:=: (AST.PrimLit "'0'")
204   signature <- getEntity res
205   let entity_id = ent_id signature
206   let reslabel = "resetval_" ++ ((prettyShow . varToVHDLName) res)
207   let portmaps = mkAssocElems [] (AST.NSimple resvalid) signature
208   let reset_statement = mkComponentInst reslabel entity_id portmaps
209   let clk_statement = [AST.ElseIf rising_edge_clk [clk_assign]]
210   let statement   = AST.IfSm resetn_is_low [res_assign] clk_statement Nothing
211   let stateupdate = AST.CSPSm $ AST.ProcSm statelabel [clockId,resetId,resvalid] [statement]
212   let block = AST.CSBSm $ AST.BlockSm blocklabel [] (AST.PMapAspect []) [resvaldec] [reset_statement,stateupdate]
213   return ([block],[res])
214
215 -- | Transforms a core binding into a VHDL concurrent statement
216 mkConcSm ::
217   (CoreSyn.CoreBndr, CoreSyn.CoreExpr) -- ^ The binding to process
218   -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr]) 
219   -- ^ The corresponding VHDL concurrent statements and entities
220   --   instantiated.
221
222
223 -- Ignore Cast expressions, they should not longer have any meaning as long as
224 -- the type works out. Throw away state repacking
225 mkConcSm (bndr, to@(CoreSyn.Cast from ty))
226   | hasStateType to && hasStateType from
227   = return ([],[])
228 mkConcSm (bndr, CoreSyn.Cast expr ty) = mkConcSm (bndr, expr)
229
230 -- Simple a = b assignments are just like applications, but without arguments.
231 -- We can't just generate an unconditional assignment here, since b might be a
232 -- top level binding (e.g., a function with no arguments).
233 mkConcSm (bndr, CoreSyn.Var v) = do
234   genApplication (Left bndr, Var.varType bndr) v []
235
236 mkConcSm (bndr, app@(CoreSyn.App _ _))= do
237   let (CoreSyn.Var f, args) = CoreSyn.collectArgs app
238   let valargs = get_val_args (Var.varType f) args
239   genApplication (Left bndr, Var.varType bndr) f (zip (map Left valargs) (map CoreUtils.exprType valargs))
240
241 -- A single alt case must be a selector. This means the scrutinee is a simple
242 -- variable, the alternative is a dataalt with a single non-wild binder that
243 -- is also returned.
244 mkConcSm (bndr, expr@(CoreSyn.Case (CoreSyn.Var scrut) b ty [alt])) 
245                 -- Don't generate VHDL for substate extraction
246                 | hasStateType bndr = return ([], [])
247                 | otherwise =
248   case alt of
249     (CoreSyn.DataAlt dc, bndrs, (CoreSyn.Var sel_bndr)) -> do
250       nonemptysel <- hasNonEmptyType sel_bndr 
251       if nonemptysel 
252         then do
253           bndrs' <- Monad.filterM hasNonEmptyType bndrs
254           case List.elemIndex sel_bndr bndrs' of
255             Just sel_i -> do
256               htypeScrt <- MonadState.lift tsType $ mkHTypeEither (Var.varType scrut)
257               htypeBndr <- MonadState.lift tsType $ mkHTypeEither (Var.varType bndr)
258               case htypeScrt == htypeBndr of
259                 True -> do
260                   let sel_name = varToVHDLName scrut
261                   let sel_expr = AST.PrimName sel_name
262                   return ([mkUncondAssign (Left bndr) sel_expr], [])
263                 otherwise ->
264                   case htypeScrt of
265                     Right htype@(AggrType _ _ _) -> do
266                       let dc_i = datacon_index (Id.idType scrut) dc
267                       let labels = getFieldLabels htype dc_i
268                       let label = labels!!sel_i
269                       let sel_name = mkSelectedName (varToVHDLName scrut) label
270                       let sel_expr = AST.PrimName sel_name
271                       return ([mkUncondAssign (Left bndr) sel_expr], [])
272                     _ -> do -- error $ "DIE!"
273                       let sel_name = varToVHDLName scrut
274                       let sel_expr = AST.PrimName sel_name
275                       return ([mkUncondAssign (Left bndr) sel_expr], [])
276             Nothing -> error $ "\nVHDL.mkConcSM: Not in normal form: Not a selector case: result is not one of the binders\n" ++ (pprString expr)
277           else
278             -- A selector case that selects a state value, ignore it.
279             return ([], [])
280       
281     _ -> error $ "\nVHDL.mkConcSM: Not in normal form: Not a selector case:\n" ++ (pprString expr)
282
283 -- Multiple case alt become conditional assignments and have only wild
284 -- binders in the alts and only variables in the case values and a variable
285 -- for a scrutinee. We check the constructor of the second alt, since the
286 -- first is the default case, if there is any.
287 mkConcSm (bndr, expr@(CoreSyn.Case (CoreSyn.Var scrut) _ _ alts)) = do
288   htype <- MonadState.lift tsType $ mkHType ("\nVHDL.mkConcSm: Unrepresentable scrutinee type? Expression: " ++ pprString expr) scrut
289   -- Turn the scrutinee into a VHDLExpr
290   scrut_expr <- MonadState.lift tsType $ varToVHDLExpr scrut
291   (enums, cmp) <- case htype of
292     EnumType _ enums -> do
293       -- Enumeration type, compare with the scrutinee directly
294       return (map stringToVHDLExpr enums, scrut_expr)
295     AggrType _ (Just (name, EnumType _ enums)) _ -> do
296       -- Extract the enumeration field from the aggregation
297       let sel_name = mkSelectedName (varToVHDLName scrut) (mkVHDLBasicId name)
298       let sel_expr = AST.PrimName sel_name
299       return (map stringToVHDLExpr enums, sel_expr)
300     (BuiltinType "Bit") -> do
301       let enums = [AST.PrimLit "'1'", AST.PrimLit "'0'"]
302       return (enums, scrut_expr)
303     (BuiltinType "Bool") -> do
304       let enums = [AST.PrimLit "true", AST.PrimLit "false"]
305       return (enums, scrut_expr)
306     _ -> error $ "\nSelector case on weird scrutinee: " ++ pprString scrut ++ " scrutinee type: " ++ pprString (Id.idType scrut)
307   -- Omit first condition, which is the default. Look up each altcon in
308   -- the enums list from the HType to find the actual enum value names.
309   let altcons = map (\(CoreSyn.DataAlt dc, _, _) -> enums!!(datacon_index scrut dc)) (tail alts)
310   -- Compare the (constructor field of the) scrutinee with each of the
311   -- alternatives.
312   let cond_exprs = map (\x -> cmp AST.:=: x) altcons
313   -- Rotate expressions to the left, so that the expression related to the default case is the last
314   exprs <- MonadState.lift tsType $ mapM (varToVHDLExpr . (\(_,_,CoreSyn.Var expr) -> expr)) ((tail alts) ++ [head alts])
315   return ([mkAltsAssign (Left bndr) cond_exprs exprs], [])
316
317 mkConcSm (_, CoreSyn.Case _ _ _ _) = error "\nVHDL.mkConcSm: Not in normal form: Case statement does not have a simple variable as scrutinee"
318 mkConcSm (bndr, expr) = error $ "\nVHDL.mkConcSM: Unsupported binding in let expression: " ++ pprString bndr ++ " = " ++ pprString expr
319
320 -----------------------------------------------------------------------------
321 -- Functions to generate VHDL for builtin functions
322 -----------------------------------------------------------------------------
323
324 -- | A function to wrap a builder-like function that expects its arguments to
325 -- be expressions.
326 genExprArgs wrap dst func args = do
327   args' <- argsToVHDLExprs (map fst args)
328   wrap dst func (zip args' (map snd args))
329
330 -- | Turn the all lefts into VHDL Expressions.
331 argsToVHDLExprs :: [Either CoreSyn.CoreExpr AST.Expr] -> TranslatorSession [AST.Expr]
332 argsToVHDLExprs = catMaybesM . (mapM argToVHDLExpr)
333
334 argToVHDLExpr :: Either CoreSyn.CoreExpr AST.Expr -> TranslatorSession (Maybe AST.Expr)
335 argToVHDLExpr (Left expr) = MonadState.lift tsType $ do
336   let errmsg = "Generate.argToVHDLExpr: Using non-representable type? Should not happen!"
337   ty_maybe <- vhdlTy errmsg expr
338   case ty_maybe of
339     Just _ -> do
340       vhdl_expr <- varToVHDLExpr $ exprToVar expr
341       return $ Just vhdl_expr
342     Nothing -> return Nothing
343
344 argToVHDLExpr (Right expr) = return $ Just expr
345
346 -- A function to wrap a builder-like function that generates no component
347 -- instantiations
348 genNoInsts ::
349   (dst -> func -> args -> TranslatorSession [AST.ConcSm])
350   -> (dst -> func -> args -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr]))
351 genNoInsts wrap dst func args = do
352   concsms <- wrap dst func args
353   return (concsms, [])
354
355 -- | A function to wrap a builder-like function that expects its arguments to
356 -- be variables.
357 -- genVarArgs ::
358 --   (dst -> func -> [Var.Var] -> res)
359 --   -> (dst -> func -> [Either CoreSyn.CoreExpr AST.Expr] -> res)
360 -- genVarArgs wrap = genCoreArgs $ \dst func args -> let
361 --     args' = map exprToVar args
362 --   in
363 --     wrap dst func args'
364
365 -- | A function to wrap a builder-like function that expects its arguments to
366 -- be core expressions.
367 genCoreArgs ::
368   (dst -> func -> [CoreSyn.CoreExpr] -> res)
369   -> (dst -> func -> [(Either CoreSyn.CoreExpr AST.Expr, Type.Type)] -> res)
370 genCoreArgs wrap dst func args = wrap dst func args'
371   where
372     -- Check (rather crudely) that all arguments are CoreExprs
373     args' = case Either.partitionEithers (map fst args) of 
374       (exprargs, []) -> exprargs
375       (exprsargs, rest) -> error $ "\nGenerate.genCoreArgs: expect core expression arguments but found ast exprs:" ++ (show rest)
376
377 -- | A function to wrap a builder-like function that produces an expression
378 -- and expects it to be assigned to the destination.
379 genExprRes ::
380   ((Either CoreSyn.CoreBndr AST.VHDLName) -> func -> [arg] -> TranslatorSession AST.Expr)
381   -> ((Either CoreSyn.CoreBndr AST.VHDLName) -> func -> [arg] -> TranslatorSession [AST.ConcSm])
382 genExprRes wrap dst func args = do
383   expr <- wrap dst func args
384   return [mkUncondAssign dst expr]
385
386 -- | Generate a binary operator application. The first argument should be a
387 -- constructor from the AST.Expr type, e.g. AST.And.
388 genOperator2 :: (AST.Expr -> AST.Expr -> AST.Expr) -> BuiltinBuilder 
389 genOperator2 op = genNoInsts $ genExprArgs $ genExprRes (genOperator2' op)
390 genOperator2' :: (AST.Expr -> AST.Expr -> AST.Expr) -> dst -> CoreSyn.CoreBndr -> [(AST.Expr, Type.Type)] -> TranslatorSession AST.Expr
391 genOperator2' op _ f [(arg1,_), (arg2,_)] = return $ op arg1 arg2
392
393 -- | Generate a unary operator application
394 genOperator1 :: (AST.Expr -> AST.Expr) -> BuiltinBuilder 
395 genOperator1 op = genNoInsts $ genExprArgs $ genExprRes (genOperator1' op)
396 genOperator1' :: (AST.Expr -> AST.Expr) -> dst -> CoreSyn.CoreBndr -> [(AST.Expr, Type.Type)] -> TranslatorSession AST.Expr
397 genOperator1' op _ f [(arg,_)] = return $ op arg
398
399 -- | Generate a unary operator application
400 genNegation :: BuiltinBuilder 
401 genNegation = genNoInsts $ genExprRes genNegation'
402 genNegation' :: dst -> CoreSyn.CoreBndr -> [(Either CoreSyn.CoreExpr AST.Expr, Type.Type)] -> TranslatorSession AST.Expr
403 genNegation' _ f [(arg,argType)] = do
404   [arg1] <-  argsToVHDLExprs [arg]
405   let (tycon, args) = Type.splitTyConApp argType
406   let name = Name.getOccString (TyCon.tyConName tycon)
407   case name of
408     "Signed" -> return $ AST.Neg arg1
409     otherwise -> error $ "\nGenerate.genNegation': Negation not allowed for type: " ++ show name 
410
411 -- | Generate a function call from the destination binder, function name and a
412 -- list of expressions (its arguments)
413 genFCall :: Bool -> BuiltinBuilder 
414 genFCall switch = genNoInsts $ genExprArgs $ genExprRes (genFCall' switch)
415 genFCall' :: Bool -> Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [(AST.Expr, Type.Type)] -> TranslatorSession AST.Expr
416 genFCall' switch (Left res) f args = do
417   let fname = varToString f
418   let el_ty = if switch then (Var.varType res) else ((tfvec_elem . Var.varType) res)
419   id <- MonadState.lift tsType $ vectorFunId el_ty fname
420   return $ AST.PrimFCall $ AST.FCall (AST.NSimple id)  $
421              map (\exp -> Nothing AST.:=>: AST.ADExpr exp) (map fst args)
422 genFCall' _ (Right name) _ _ = error $ "\nGenerate.genFCall': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
423
424 genFromSizedWord :: BuiltinBuilder
425 genFromSizedWord = genNoInsts $ genExprArgs genFromSizedWord'
426 genFromSizedWord' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [(AST.Expr, Type.Type)] -> TranslatorSession [AST.ConcSm]
427 genFromSizedWord' (Left res) f args@[(arg,_)] =
428   return [mkUncondAssign (Left res) arg]
429   -- let fname = varToString f
430   -- return $ AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLBasicId toIntegerId))  $
431   --            map (\exp -> Nothing AST.:=>: AST.ADExpr exp) args
432 genFromSizedWord' (Right name) _ _ = error $ "\nGenerate.genFromSizedWord': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
433
434 genFromRangedWord :: BuiltinBuilder
435 genFromRangedWord = genNoInsts $ genExprArgs $ genExprRes genFromRangedWord'
436 genFromRangedWord' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [(AST.Expr, Type.Type)] -> TranslatorSession AST.Expr
437 genFromRangedWord' (Left res) f [(arg,_)] = do {
438   ; let { ty = Var.varType res
439         ; (tycon, args) = Type.splitTyConApp ty
440         ; name = Name.getOccString (TyCon.tyConName tycon)
441         } ;
442   ; len <- MonadState.lift tsType $ tfp_to_int (sized_word_len_ty ty)
443   ; return $ AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLBasicId resizeId))
444              [Nothing AST.:=>: AST.ADExpr arg, Nothing AST.:=>: AST.ADExpr( AST.PrimLit (show len))]
445   }
446 genFromRangedWord' (Right name) _ _ = error $ "\nGenerate.genFromRangedWord': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
447
448 genResize :: BuiltinBuilder
449 genResize = genNoInsts $ genExprArgs $ genExprRes genResize'
450 genResize' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [(AST.Expr, Type.Type)] -> TranslatorSession AST.Expr
451 genResize' (Left res) f [(arg,_)] = do {
452   ; let { ty = Var.varType res
453         ; (tycon, args) = Type.splitTyConApp ty
454         ; name = Name.getOccString (TyCon.tyConName tycon)
455         } ;
456   ; len <- case name of
457       "Signed" -> MonadState.lift tsType $ tfp_to_int (sized_int_len_ty ty)
458       "Unsigned" -> MonadState.lift tsType $ tfp_to_int (sized_word_len_ty ty)
459   ; return $ AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLBasicId resizeId))
460              [Nothing AST.:=>: AST.ADExpr arg, Nothing AST.:=>: AST.ADExpr( AST.PrimLit (show len))]
461   }
462 genResize' (Right name) _ _ = error $ "\nGenerate.genFromSizedWord': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
463
464 genTimes :: BuiltinBuilder
465 genTimes = genNoInsts $ genExprArgs $ genExprRes genTimes'
466 genTimes' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [(AST.Expr, Type.Type)] -> TranslatorSession AST.Expr
467 genTimes' (Left res) f [(arg1,_),(arg2,_)] = do {
468   ; let { ty = Var.varType res
469         ; (tycon, args) = Type.splitTyConApp ty
470         ; name = Name.getOccString (TyCon.tyConName tycon)
471         } ;
472   ; len <- case name of
473       "Signed" -> MonadState.lift tsType $ tfp_to_int (sized_int_len_ty ty)
474       "Unsigned" -> MonadState.lift tsType $ tfp_to_int (sized_word_len_ty ty)
475       "Index" -> do {  ubound <- MonadState.lift tsType $ tfp_to_int (ranged_word_bound_ty ty)
476                          ;  let bitsize = floor (logBase 2 (fromInteger (toInteger ubound)))
477                          ;  return bitsize
478                          }
479   ; return $ AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLBasicId resizeId))
480              [Nothing AST.:=>: AST.ADExpr (arg1 AST.:*: arg2), Nothing AST.:=>: AST.ADExpr( AST.PrimLit (show len))]
481   }
482 genTimes' (Right name) _ _ = error $ "\nGenerate.genTimes': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
483
484 -- fromInteger turns an Integer into a Num instance. Since Integer is
485 -- not representable and is only allowed for literals, the actual
486 -- Integer should be inlined entirely into the fromInteger argument.
487 genFromInteger :: BuiltinBuilder
488 genFromInteger = genNoInsts $ genCoreArgs $ genExprRes genFromInteger'
489 genFromInteger' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [CoreSyn.CoreExpr] -> TranslatorSession AST.Expr
490 genFromInteger' (Left res) f args = do
491   let ty = Var.varType res
492   let (tycon, tyargs) = Type.splitTyConApp ty
493   let name = Name.getOccString (TyCon.tyConName tycon)
494   len <- case name of
495     "Signed" -> MonadState.lift tsType $ tfp_to_int (sized_int_len_ty ty)
496     "Unsigned" -> MonadState.lift tsType $ tfp_to_int (sized_word_len_ty ty)
497     "Index" -> do
498       bound <- MonadState.lift tsType $ tfp_to_int (ranged_word_bound_ty ty)
499       return $ floor (logBase 2 (fromInteger (toInteger (bound)))) + 1
500   let fname = case name of "Signed" -> toSignedId ; "Unsigned" -> toUnsignedId ; "Index" -> toUnsignedId
501   case args of
502     [integer] -> do -- The type and dictionary arguments are removed by genApplication
503       literal <- getIntegerLiteral integer
504       return $ AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLBasicId fname))
505               [Nothing AST.:=>: AST.ADExpr (AST.PrimLit (show literal)), Nothing AST.:=>: AST.ADExpr( AST.PrimLit (show len))]
506     _ -> error $ "\nGenerate.genFromInteger': Wrong number of arguments to genInteger. Applying " ++ pprString f ++ " to " ++ pprString args
507
508 genFromInteger' (Right name) _ _ = error $ "\nGenerate.genFromInteger': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
509
510 genSizedInt :: BuiltinBuilder
511 genSizedInt = genFromInteger
512
513 {-
514 -- This function is useful for use with vectorTH, since that generates
515 -- explicit references to the TFVec constructor (which is normally
516 -- hidden). Below implementation is probably not current anymore, but
517 -- kept here in case we start using vectorTH again.
518 -- | Generate a Builder for the builtin datacon TFVec
519 genTFVec :: BuiltinBuilder
520 genTFVec (Left res) f [Left (CoreSyn.Let (CoreSyn.Rec letBinders) letRes)] = do {
521   -- Generate Assignments for all the binders
522   ; letAssigns <- mapM genBinderAssign letBinders
523   -- Generate assignments for the result (which might be another let binding)
524   ; (resBinders,resAssignments) <- genResAssign letRes
525   -- Get all the Assigned binders
526   ; let assignedBinders = Maybe.catMaybes (map fst letAssigns)
527   -- Make signal names for all the assigned binders
528   ; sigs <- mapM (\x -> MonadState.lift tsType $ varToVHDLExpr x) (assignedBinders ++ resBinders)
529   -- Assign all the signals to the resulting vector
530   ; let { vecsigns = mkAggregateSignal sigs
531         ; vecassign = mkUncondAssign (Left res) vecsigns
532         } ;
533   -- Generate all the signal declaration for the assigned binders
534   ; sig_dec_maybes <- mapM mkSigDec (assignedBinders ++ resBinders)
535   ; let { sig_decs = map (AST.BDISD) (Maybe.catMaybes $ sig_dec_maybes)
536   -- Setup the VHDL Block
537         ; block_label = mkVHDLExtId ("TFVec_" ++ show (varToString res))
538         ; block = AST.BlockSm block_label [] (AST.PMapAspect []) sig_decs ((concat (map snd letAssigns)) ++ resAssignments ++ [vecassign])
539         } ;
540   -- Return the block statement coressponding to the TFVec literal
541   ; return $ [AST.CSBSm block]
542   }
543   where
544     genBinderAssign :: (CoreSyn.CoreBndr, CoreSyn.CoreExpr) -> TranslatorSession (Maybe CoreSyn.CoreBndr, [AST.ConcSm])
545     -- For now we only translate applications
546     genBinderAssign (bndr, app@(CoreSyn.App _ _)) = do
547       let (CoreSyn.Var f, args) = CoreSyn.collectArgs app
548       let valargs = get_val_args (Var.varType f) args
549       apps <- genApplication (Left bndr) f (map Left valargs)
550       return (Just bndr, apps)
551     genBinderAssign _ = return (Nothing,[])
552     genResAssign :: CoreSyn.CoreExpr -> TranslatorSession ([CoreSyn.CoreBndr], [AST.ConcSm])
553     genResAssign app@(CoreSyn.App _ letexpr) = do
554       case letexpr of
555         (CoreSyn.Let (CoreSyn.Rec letbndrs) letres) -> do
556           letapps <- mapM genBinderAssign letbndrs
557           let bndrs = Maybe.catMaybes (map fst letapps)
558           let app = (map snd letapps)
559           (vars, apps) <- genResAssign letres
560           return ((bndrs ++ vars),((concat app) ++ apps))
561         otherwise -> return ([],[])
562     genResAssign _ = return ([],[])
563
564 genTFVec (Left res) f [Left app@(CoreSyn.App _ _)] = do {
565   ; let { elems = reduceCoreListToHsList app
566   -- Make signal names for all the binders
567         ; binders = map (\expr -> case expr of 
568                           (CoreSyn.Var b) -> b
569                           otherwise -> error $ "\nGenerate.genTFVec: Cannot generate TFVec: " 
570                             ++ show res ++ ", with elems:\n" ++ show elems ++ "\n" ++ pprString elems) elems
571         } ;
572   ; sigs <- mapM (\x -> MonadState.lift tsType $ varToVHDLExpr x) binders
573   -- Assign all the signals to the resulting vector
574   ; let { vecsigns = mkAggregateSignal sigs
575         ; vecassign = mkUncondAssign (Left res) vecsigns
576   -- Setup the VHDL Block
577         ; block_label = mkVHDLExtId ("TFVec_" ++ show (varToString res))
578         ; block = AST.BlockSm block_label [] (AST.PMapAspect []) [] [vecassign]
579         } ;
580   -- Return the block statement coressponding to the TFVec literal
581   ; return $ [AST.CSBSm block]
582   }
583   
584 genTFVec (Left name) _ [Left xs] = error $ "\nGenerate.genTFVec: Cannot generate TFVec: " ++ show name ++ ", with elems:\n" ++ show xs ++ "\n" ++ pprString xs
585
586 genTFVec (Right name) _ _ = error $ "\nGenerate.genTFVec: Cannot generate TFVec assigned to VHDLName: " ++ show name
587 -}
588 -- | Generate a generate statement for the builtin function "map"
589 genMap :: BuiltinBuilder
590 genMap (Left res) f [(Left mapped_f, _), (Left (CoreSyn.Var arg), _)] = do {
591   -- mapped_f must be a CoreExpr (since we can't represent functions as VHDL
592   -- expressions). arg must be a CoreExpr (and should be a CoreSyn.Var), since
593   -- we must index it (which we couldn't if it was a VHDL Expr, since only
594   -- VHDLNames can be indexed).
595   -- Setup the generate scheme
596   ; len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) res
597   ; let res_type = (tfvec_elem . Var.varType) res
598           -- TODO: Use something better than varToString
599   ; let { label       = mkVHDLExtId ("mapVector" ++ (varToString res))
600         ; n_id        = mkVHDLBasicId "n"
601         ; n_expr      = idToVHDLExpr n_id
602         ; range       = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
603         ; genScheme   = AST.ForGn n_id range
604           -- Create the content of the generate statement: Applying the mapped_f to
605           -- each of the elements in arg, storing to each element in res
606         ; resname     = mkIndexedName (varToVHDLName res) n_expr
607         ; argexpr     = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg) n_expr
608         ; (CoreSyn.Var real_f, already_mapped_args) = CoreSyn.collectArgs mapped_f
609         ; valargs     = get_val_args (Var.varType real_f) already_mapped_args
610         } ;   
611   ; (app_concsms, used) <- genApplication (Right resname,res_type) real_f ((zip (map Left valargs) (map CoreUtils.exprType valargs)) ++ [(Right argexpr, (tfvec_elem . Var.varType) arg)])
612     -- Return the generate statement
613   ; return ([AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms], used)
614   }
615
616 genMap' (Right name) _ _ = error $ "\nGenerate.genMap': Cannot generate map function call assigned to a VHDLName: " ++ show name
617     
618 genZipWith :: BuiltinBuilder
619 genZipWith (Left res) f args@[(Left zipped_f, _), (Left (CoreSyn.Var arg1), _), (Left (CoreSyn.Var arg2), _)] = do {
620   -- Setup the generate scheme
621   ; len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) res
622   ; let res_type = (tfvec_elem . Var.varType) res
623           -- TODO: Use something better than varToString
624   ; let { label       = mkVHDLExtId ("zipWithVector" ++ (varToString res))
625         ; n_id        = mkVHDLBasicId "n"
626         ; n_expr      = idToVHDLExpr n_id
627         ; range       = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
628         ; genScheme   = AST.ForGn n_id range
629           -- Create the content of the generate statement: Applying the zipped_f to
630           -- each of the elements in arg1 and arg2, storing to each element in res
631         ; resname     = mkIndexedName (varToVHDLName res) n_expr
632         ; (CoreSyn.Var real_f, already_mapped_args) = CoreSyn.collectArgs zipped_f
633         ; valargs     = get_val_args (Var.varType real_f) already_mapped_args
634         ; argexpr1    = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg1) n_expr
635         ; argexpr2    = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg2) n_expr
636         } ;
637   ; (app_concsms, used) <- genApplication (Right resname,res_type) real_f ((zip (map Left valargs) (map CoreUtils.exprType valargs)) ++ [(Right argexpr1, (tfvec_elem . Var.varType) arg1), (Right argexpr2, (tfvec_elem . Var.varType) arg2)])
638     -- Return the generate functions
639   ; return ([AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms], used)
640   }
641
642 genFoldl :: BuiltinBuilder
643 genFoldl = genFold True
644
645 genFoldr :: BuiltinBuilder
646 genFoldr = genFold False
647
648 genFold :: Bool -> BuiltinBuilder
649 genFold left res f args@[folded_f, start, (vec, vecType)] = do
650   len <- MonadState.lift tsType $ tfp_to_int (tfvec_len_ty vecType)
651   genFold' len left res f args
652
653 genFold' :: Int -> Bool -> BuiltinBuilder
654 -- Special case for an empty input vector, just assign start to res
655 genFold' len left (Left res) _ [_, (start, _), vec] | len == 0 = do
656   [arg] <- argsToVHDLExprs [start]
657   return ([mkUncondAssign (Left res) arg], [])
658     
659 genFold' len left (Left res) f [(Left folded_f,_), (start,startType), (vec,vecType)] = do
660   [vecExpr] <- argsToVHDLExprs [vec]
661   -- The vector length
662   --len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) vec
663   -- An expression for len-1
664   let len_min_expr = (AST.PrimLit $ show (len-1))
665   -- evec is (TFVec n), so it still needs an element type
666   let (nvec, _) = Type.splitAppTy vecType
667   -- Put the type of the start value in nvec, this will be the type of our
668   -- temporary vector
669   let tmp_ty = Type.mkAppTy nvec startType
670   let error_msg = "\nGenerate.genFold': Can not construct temp vector for element type: " ++ pprString tmp_ty 
671   -- TODO: Handle Nothing
672   Just tmp_vhdl_ty <- MonadState.lift tsType $ vhdlTy error_msg tmp_ty
673   -- Setup the generate scheme
674   let gen_label = mkVHDLExtId ("foldlVector" ++ (show vecExpr))
675   let block_label = mkVHDLExtId ("foldlVector" ++ (varToString res))
676   let gen_range = if left then AST.ToRange (AST.PrimLit "0") len_min_expr
677                   else AST.DownRange len_min_expr (AST.PrimLit "0")
678   let gen_scheme   = AST.ForGn n_id gen_range
679   -- Make the intermediate vector
680   let  tmp_dec     = AST.BDISD $ AST.SigDec tmp_id tmp_vhdl_ty Nothing
681   -- Create the generate statement
682   cells' <- sequence [genFirstCell, genOtherCell]
683   let (cells, useds) = unzip cells'
684   let gen_sm = AST.GenerateSm gen_label gen_scheme [] (map AST.CSGSm cells)
685   -- Assign tmp[len-1] or tmp[0] to res
686   let out_assign = mkUncondAssign (Left res) $ vhdlNameToVHDLExpr (if left then
687                     (mkIndexedName tmp_name (AST.PrimLit $ show (len-1))) else
688                     (mkIndexedName tmp_name (AST.PrimLit "0")))      
689   let block = AST.BlockSm block_label [] (AST.PMapAspect []) [tmp_dec] [AST.CSGSm gen_sm, out_assign]
690   return ([AST.CSBSm block], concat useds)
691   where
692     -- An id for the counter
693     n_id = mkVHDLBasicId "n"
694     n_cur = idToVHDLExpr n_id
695     -- An expression for previous n
696     n_prev = if left then (n_cur AST.:-: (AST.PrimLit "1"))
697                      else (n_cur AST.:+: (AST.PrimLit "1"))
698     -- An id for the tmp result vector
699     tmp_id = mkVHDLBasicId "tmp"
700     tmp_name = AST.NSimple tmp_id
701     -- Generate parts of the fold
702     genFirstCell, genOtherCell :: TranslatorSession (AST.GenerateSm, [CoreSyn.CoreBndr])
703     genFirstCell = do
704       [AST.PrimName vecName, argexpr1] <- argsToVHDLExprs [vec,start]
705       let res_type = (tfvec_elem . Var.varType) res
706       len <- MonadState.lift tsType $ tfp_to_int $ tfvec_len_ty vecType
707       let cond_label = mkVHDLExtId "firstcell"
708       -- if n == 0 or n == len-1
709       let cond_scheme = AST.IfGn $ n_cur AST.:=: (if left then (AST.PrimLit "0")
710                                                   else (AST.PrimLit $ show (len-1)))
711       -- Output to tmp[current n]
712       let resname = mkIndexedName tmp_name n_cur
713       -- Input from start
714       -- argexpr1 <- MonadState.lift tsType $ varToVHDLExpr start
715       -- Input from vec[current n]
716       let argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName vecName n_cur
717       (app_concsms, used) <- genApplication (Right resname,res_type) (exprToVar folded_f)  ( if left then
718                                                                   [(Right argexpr1, startType), (Right argexpr2, tfvec_elem vecType)]
719                                                                 else
720                                                                   [(Right argexpr2, tfvec_elem vecType), (Right argexpr1, startType)]
721                                                               )
722       -- Return the conditional generate part
723       return (AST.GenerateSm cond_label cond_scheme [] app_concsms, used)
724
725     genOtherCell = do
726       [AST.PrimName vecName] <- argsToVHDLExprs [vec]
727       let res_type = (tfvec_elem . Var.varType) res
728       len <- MonadState.lift tsType $ tfp_to_int $ tfvec_len_ty vecType
729       let cond_label = mkVHDLExtId "othercell"
730       -- if n > 0 or n < len-1
731       let cond_scheme = AST.IfGn $ n_cur AST.:/=: (if left then (AST.PrimLit "0")
732                                                    else (AST.PrimLit $ show (len-1)))
733       -- Output to tmp[current n]
734       let resname = mkIndexedName tmp_name n_cur
735       -- Input from tmp[previous n]
736       let argexpr1 = vhdlNameToVHDLExpr $ mkIndexedName tmp_name n_prev
737       -- Input from vec[current n]
738       let argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName vecName n_cur
739       (app_concsms, used) <- genApplication (Right resname,res_type) (exprToVar folded_f)  ( if left then
740                                                                   [(Right argexpr1, startType), (Right argexpr2, tfvec_elem vecType)]
741                                                                 else
742                                                                   [(Right argexpr2, tfvec_elem vecType), (Right argexpr1, startType)]
743                                                               )
744       -- Return the conditional generate part
745       return (AST.GenerateSm cond_label cond_scheme [] app_concsms, used)
746
747 -- | Generate a generate statement for the builtin function "zip"
748 genZip :: BuiltinBuilder
749 genZip = genNoInsts genZip'
750 genZip' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [(Either CoreSyn.CoreExpr AST.Expr, Type.Type)] -> TranslatorSession [AST.ConcSm]
751 genZip' (Left res) f args@[(arg1,_), (arg2,_)] = do {
752     -- Setup the generate scheme
753   ; len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) res
754   ; res_htype <- MonadState.lift tsType $ mkHType "\nGenerate.genZip: Invalid result type" (tfvec_elem (Var.varType res))
755   ; [AST.PrimName argName1, AST.PrimName argName2] <- argsToVHDLExprs [arg1,arg2] 
756           -- TODO: Use something better than varToString
757   ; let { label           = mkVHDLExtId ("zipVector" ++ (varToString res))
758         ; n_id            = mkVHDLBasicId "n"
759         ; n_expr          = idToVHDLExpr n_id
760         ; range           = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
761         ; genScheme       = AST.ForGn n_id range
762         ; resname'        = mkIndexedName (varToVHDLName res) n_expr
763         ; argexpr1        = vhdlNameToVHDLExpr $ mkIndexedName argName1 n_expr
764         ; argexpr2        = vhdlNameToVHDLExpr $ mkIndexedName argName2 n_expr
765         ; labels          = getFieldLabels res_htype 0
766         }
767   ; let { resnameA    = mkSelectedName resname' (labels!!0)
768         ; resnameB    = mkSelectedName resname' (labels!!1)
769         ; resA_assign = mkUncondAssign (Right resnameA) argexpr1
770         ; resB_assign = mkUncondAssign (Right resnameB) argexpr2
771         } ;
772     -- Return the generate functions
773   ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] [resA_assign,resB_assign]]
774   }
775   
776 -- | Generate a generate statement for the builtin function "fst"
777 genFst :: BuiltinBuilder
778 genFst = genNoInsts genFst'
779 genFst' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [(Either CoreSyn.CoreExpr AST.Expr, Type.Type)] -> TranslatorSession [AST.ConcSm]
780 genFst' res f args@[(arg,argType)] = do {
781   ; arg_htype <- MonadState.lift tsType $ mkHType "\nGenerate.genFst: Invalid argument type" argType
782   ; [AST.PrimName argExpr] <- argsToVHDLExprs [arg] 
783   ; let { 
784         ; labels      = getFieldLabels arg_htype 0
785         ; argexprA    = vhdlNameToVHDLExpr $ mkSelectedName argExpr (labels!!0)
786         ; assign      = mkUncondAssign res argexprA
787         } ;
788     -- Return the generate functions
789   ; return [assign]
790   }
791   
792 -- | Generate a generate statement for the builtin function "snd"
793 genSnd :: BuiltinBuilder
794 genSnd = genNoInsts genSnd'
795 genSnd' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [(Either CoreSyn.CoreExpr AST.Expr, Type.Type)] -> TranslatorSession [AST.ConcSm]
796 genSnd' (Left res) f args@[(arg,argType)] = do {
797   ; arg_htype <- MonadState.lift tsType $ mkHType "\nGenerate.genSnd: Invalid argument type" argType
798   ; [AST.PrimName argExpr] <- argsToVHDLExprs [arg] 
799   ; let { 
800         ; labels      = getFieldLabels arg_htype 0
801         ; argexprB    = vhdlNameToVHDLExpr $ mkSelectedName argExpr (labels!!1)
802         ; assign      = mkUncondAssign (Left res) argexprB
803         } ;
804     -- Return the generate functions
805   ; return [assign]
806   }
807     
808 -- | Generate a generate statement for the builtin function "unzip"
809 genUnzip :: BuiltinBuilder
810 genUnzip = genNoInsts genUnzip'
811 genUnzip' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [(Either CoreSyn.CoreExpr AST.Expr, Type.Type)] -> TranslatorSession [AST.ConcSm]
812 genUnzip' (Left res) f args@[(arg,argType)] = do
813   let error_msg = "\nGenerate.genUnzip: Cannot generate unzip call: " ++ pprString res ++ " = " ++ pprString f ++ " " ++ show arg
814   htype <- MonadState.lift tsType $ mkHType error_msg argType
815   -- Prepare a unconditional assignment, for the case when either part
816   -- of the unzip is a state variable, which will disappear in the
817   -- resulting VHDL, making the the unzip no longer required.
818   case htype of
819     -- A normal vector containing two-tuples
820     VecType _ (AggrType _ _ [_, _]) -> do {
821         -- Setup the generate scheme
822       ; len <- MonadState.lift tsType $ tfp_to_int $ tfvec_len_ty argType
823       ; arg_htype <- MonadState.lift tsType $ mkHType "\nGenerate.genUnzip: Invalid argument type" argType
824       ; res_htype <- MonadState.lift tsType $ mkHType "\nGenerate.genUnzip: Invalid result type" (Var.varType res)
825       ; [AST.PrimName arg'] <- argsToVHDLExprs [arg]
826         -- TODO: Use something better than varToString
827       ; let { label           = mkVHDLExtId ("unzipVector" ++ (varToString res))
828             ; n_id            = mkVHDLBasicId "n"
829             ; n_expr          = idToVHDLExpr n_id
830             ; range           = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
831             ; genScheme       = AST.ForGn n_id range
832             ; resname'        = varToVHDLName res
833             ; argexpr'        = mkIndexedName arg' n_expr
834             ; reslabels       = getFieldLabels res_htype 0
835             ; arglabels       = getFieldLabels arg_htype 0
836             } ;
837       ; let { resnameA    = mkIndexedName (mkSelectedName resname' (reslabels!!0)) n_expr
838             ; resnameB    = mkIndexedName (mkSelectedName resname' (reslabels!!1)) n_expr
839             ; argexprA    = vhdlNameToVHDLExpr $ mkSelectedName argexpr' (arglabels!!0)
840             ; argexprB    = vhdlNameToVHDLExpr $ mkSelectedName argexpr' (arglabels!!1)
841             ; resA_assign = mkUncondAssign (Right resnameA) argexprA
842             ; resB_assign = mkUncondAssign (Right resnameB) argexprB
843             } ;
844         -- Return the generate functions
845       ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] [resA_assign,resB_assign]]
846       }
847     -- Both elements of the tuple were state, so they've disappeared. No
848     -- need to do anything
849     VecType _ (AggrType _ _ []) -> return []
850     -- A vector containing aggregates with more than two elements?
851     VecType _ (AggrType _ _ _) -> error $ "Unzipping a value that is not a vector of two-tuples? Value: " ++ show arg ++ "\nType: " ++ pprString argType
852     -- One of the elements of the tuple was state, so there won't be a
853     -- tuple (record) in the VHDL output. We can just do a plain
854     -- assignment, then.
855     VecType _ _ -> do
856       [argexpr] <- argsToVHDLExprs [arg]
857       return [mkUncondAssign (Left res) argexpr]
858     _ -> error $ "Unzipping a value that is not a vector? Value: " ++ show arg ++ "\nType: " ++ pprString argType ++ "\nhtype: " ++ show htype
859
860 genCopy :: BuiltinBuilder 
861 genCopy = genNoInsts genCopy'
862 genCopy' :: (Either CoreSyn.CoreBndr AST.VHDLName ) -> CoreSyn.CoreBndr -> [(Either CoreSyn.CoreExpr AST.Expr, Type.Type)] -> TranslatorSession [AST.ConcSm]
863 genCopy' (Left res) f [(arg,argType)] = do {
864   ; [arg'] <- argsToVHDLExprs [arg]
865   ; let { resExpr = AST.Aggregate [AST.ElemAssoc (Just AST.Others) arg']
866         ; out_assign = mkUncondAssign (Left res) resExpr
867         }
868   ; return [out_assign]
869   }
870     
871 genConcat :: BuiltinBuilder
872 genConcat = genNoInsts genConcat'
873 genConcat' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [(Either CoreSyn.CoreExpr AST.Expr, Type.Type)] -> TranslatorSession [AST.ConcSm]
874 genConcat' (Left res) f args@[(arg,argType)] = do {
875     -- Setup the generate scheme
876   ; len1 <- MonadState.lift tsType $ tfp_to_int $ tfvec_len_ty argType
877   ; let (_, nvec) = Type.splitAppTy argType
878   ; len2 <- MonadState.lift tsType $ tfp_to_int $ tfvec_len_ty nvec
879   ; [AST.PrimName argName] <- argsToVHDLExprs [arg]
880           -- TODO: Use something better than varToString
881   ; let { label       = mkVHDLExtId ("concatVector" ++ (varToString res))
882         ; n_id        = mkVHDLBasicId "n"
883         ; n_expr      = idToVHDLExpr n_id
884         ; fromRange   = n_expr AST.:*: (AST.PrimLit $ show len2)
885         ; genScheme   = AST.ForGn n_id range
886           -- Create the content of the generate statement: Applying the mapped_f to
887           -- each of the elements in arg, storing to each element in res
888         ; toRange     = (n_expr AST.:*: (AST.PrimLit $ show len2)) AST.:+: (AST.PrimLit $ show (len2-1))
889         ; range       = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len1-1))
890         ; resname     = vecSlice fromRange toRange
891         ; argexpr     = vhdlNameToVHDLExpr $ mkIndexedName argName n_expr
892         ; out_assign  = mkUncondAssign (Right resname) argexpr
893         } ;
894     -- Return the generate statement
895   ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] [out_assign]]
896   }
897   where
898     vecSlice init last =  AST.NSlice (AST.SliceName (varToVHDLName res) 
899                             (AST.ToRange init last))
900
901 genIteraten :: BuiltinBuilder
902 genIteraten dst f args = genIterate dst f (tail args)
903
904 genIterate :: BuiltinBuilder
905 genIterate = genIterateOrGenerate True
906
907 genGeneraten :: BuiltinBuilder
908 genGeneraten dst f args = genGenerate dst f (tail args)
909
910 genGenerate :: BuiltinBuilder
911 genGenerate = genIterateOrGenerate False
912
913 genIterateOrGenerate :: Bool -> BuiltinBuilder
914 genIterateOrGenerate iter (Left res) f args = do
915   len <- MonadState.lift tsType $ tfp_to_int ((tfvec_len_ty . Var.varType) res)
916   genIterateOrGenerate' len iter (Left res) f args
917
918 genIterateOrGenerate' :: Int -> Bool -> BuiltinBuilder
919 -- Special case for an empty input vector, just assign start to res
920 genIterateOrGenerate' len iter (Left res) _ [app_f, start] | len == 0 = return ([mkUncondAssign (Left res) (AST.PrimLit "\"\"")], [])
921
922 genIterateOrGenerate' len iter (Left res) f [(Left app_f,_), (start,startType)] = do
923   -- The vector length
924   -- len <- MonadState.lift tsType $ tfp_to_int ((tfvec_len_ty . Var.varType) res)
925   -- An expression for len-1
926   let len_min_expr = (AST.PrimLit $ show (len-1))
927   -- -- evec is (TFVec n), so it still needs an element type
928   -- let (nvec, _) = splitAppTy (Var.varType vec)
929   -- -- Put the type of the start value in nvec, this will be the type of our
930   -- -- temporary vector
931   let tmp_ty = Var.varType res
932   let error_msg = "\nGenerate.genFold': Can not construct temp vector for element type: " ++ pprString tmp_ty 
933   -- TODO: Handle Nothing
934   Just tmp_vhdl_ty <- MonadState.lift tsType $ vhdlTy error_msg tmp_ty
935   -- Setup the generate scheme
936   [startExpr] <- argsToVHDLExprs [start]
937   let gen_label = mkVHDLExtId ("iterateVector" ++ (show startExpr))
938   let block_label = mkVHDLExtId ("iterateVector" ++ (varToString res))
939   let gen_range = AST.ToRange (AST.PrimLit "0") len_min_expr
940   let gen_scheme   = AST.ForGn n_id gen_range
941   -- Make the intermediate vector
942   let  tmp_dec     = AST.BDISD $ AST.SigDec tmp_id tmp_vhdl_ty Nothing
943   -- Create the generate statement
944   cells' <- sequence [genFirstCell, genOtherCell]
945   let (cells, useds) = unzip cells'
946   let gen_sm = AST.GenerateSm gen_label gen_scheme [] (map AST.CSGSm cells)
947   -- Assign tmp[len-1] or tmp[0] to res
948   let out_assign = mkUncondAssign (Left res) $ vhdlNameToVHDLExpr tmp_name    
949   let block = AST.BlockSm block_label [] (AST.PMapAspect []) [tmp_dec] [AST.CSGSm gen_sm, out_assign]
950   return ([AST.CSBSm block], concat useds)
951   where
952     -- An id for the counter
953     n_id = mkVHDLBasicId "n"
954     n_cur = idToVHDLExpr n_id
955     -- An expression for previous n
956     n_prev = n_cur AST.:-: (AST.PrimLit "1")
957     -- An id for the tmp result vector
958     tmp_id = mkVHDLBasicId "tmp"
959     tmp_name = AST.NSimple tmp_id
960     -- Generate parts of the fold
961     genFirstCell, genOtherCell :: TranslatorSession (AST.GenerateSm, [CoreSyn.CoreBndr])
962     genFirstCell = do
963       let res_type = (tfvec_elem . Var.varType) res
964       let cond_label = mkVHDLExtId "firstcell"
965       -- if n == 0 or n == len-1
966       let cond_scheme = AST.IfGn $ n_cur AST.:=: (AST.PrimLit "0")
967       -- Output to tmp[current n]
968       let resname = mkIndexedName tmp_name n_cur
969       -- Input from start
970       [argexpr] <- argsToVHDLExprs [start]
971       let startassign = mkUncondAssign (Right resname) argexpr
972       (app_concsms, used) <- genApplication (Right resname, res_type) (exprToVar app_f)  [(Right argexpr, startType)]
973       -- Return the conditional generate part
974       let gensm = AST.GenerateSm cond_label cond_scheme [] (if iter then 
975                                                           [startassign]
976                                                          else 
977                                                           app_concsms
978                                                         )
979       return (gensm, used)
980
981     genOtherCell = do
982       let res_type = (tfvec_elem . Var.varType) res
983       let cond_label = mkVHDLExtId "othercell"
984       -- if n > 0 or n < len-1
985       let cond_scheme = AST.IfGn $ n_cur AST.:/=: (AST.PrimLit "0")
986       -- Output to tmp[current n]
987       let resname = mkIndexedName tmp_name n_cur
988       -- Input from tmp[previous n]
989       let argexpr = vhdlNameToVHDLExpr $ mkIndexedName tmp_name n_prev
990       (app_concsms, used) <- genApplication (Right resname, res_type) (exprToVar app_f) [(Right argexpr, res_type)]
991       -- Return the conditional generate part
992       return (AST.GenerateSm cond_label cond_scheme [] app_concsms, used)
993
994 genBlockRAM :: BuiltinBuilder
995 genBlockRAM = genNoInsts $ genExprArgs genBlockRAM'
996
997 genBlockRAM' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [(AST.Expr,Type.Type)] -> TranslatorSession [AST.ConcSm]
998 genBlockRAM' (Left res) f args@[data_in,rdaddr,wraddr,wrenable] = do
999   -- Get the ram type
1000   let (tup,data_out) = Type.splitAppTy (Var.varType res)
1001   let (tup',ramvec) = Type.splitAppTy tup
1002   let Just realram = Type.coreView ramvec
1003   let Just (tycon, types) = Type.splitTyConApp_maybe realram
1004   Just ram_vhdl_ty <- MonadState.lift tsType $ vhdlTy "wtf" (head types)
1005   -- Make the intermediate vector
1006   let ram_dec = AST.BDISD $ AST.SigDec ram_id ram_vhdl_ty Nothing
1007   -- Get the data_out name
1008   -- reslabels <- MonadState.lift tsType $ getFieldLabels (Var.varType res)
1009   let resname = varToVHDLName res
1010   -- let resname = mkSelectedName resname' (reslabels!!0)
1011   let rdaddr_int = genExprFCall (mkVHDLBasicId toIntegerId) $ fst rdaddr
1012   let argexpr = vhdlNameToVHDLExpr $ mkIndexedName (AST.NSimple ram_id) rdaddr_int
1013   let assign = mkUncondAssign (Right resname) argexpr
1014   let block_label = mkVHDLExtId ("blockRAM" ++ (varToString res))
1015   let block = AST.BlockSm block_label [] (AST.PMapAspect []) [ram_dec] [assign, mkUpdateProcSm]
1016   return [AST.CSBSm block]
1017   where
1018     ram_id = mkVHDLBasicId "ram"
1019     mkUpdateProcSm :: AST.ConcSm
1020     mkUpdateProcSm = AST.CSPSm $ AST.ProcSm proclabel [clockId] [statement]
1021       where
1022         proclabel   = mkVHDLBasicId "updateRAM"
1023         rising_edge = mkVHDLBasicId "rising_edge"
1024         wraddr_int  = genExprFCall (mkVHDLBasicId toIntegerId) $ fst wraddr
1025         ramloc      = mkIndexedName (AST.NSimple ram_id) wraddr_int
1026         wform       = AST.Wform [AST.WformElem (fst data_in) Nothing]
1027         ramassign      = AST.SigAssign ramloc wform
1028         rising_edge_clk = genExprFCall rising_edge (AST.PrimName $ AST.NSimple clockId)
1029         statement   = AST.IfSm (AST.And rising_edge_clk $ fst wrenable) [ramassign] [] Nothing
1030         
1031 genSplit :: BuiltinBuilder
1032 genSplit = genNoInsts genSplit'
1033
1034 genSplit' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [(Either CoreSyn.CoreExpr AST.Expr, Type.Type)] -> TranslatorSession [AST.ConcSm]
1035 genSplit' (Left res) f args@[(vecIn,vecInType)] = do {
1036   ; len <- MonadState.lift tsType $ tfp_to_int $ tfvec_len_ty vecInType
1037   ; res_htype <- MonadState.lift tsType $ mkHType "\nGenerate.genSplit': Invalid result type" (Var.varType res)
1038   ; [argExpr] <- argsToVHDLExprs [vecIn]
1039   ; let { 
1040         ; labels    = getFieldLabels res_htype 0
1041         ; block_label = mkVHDLExtId ("split" ++ show argExpr)
1042         ; halflen   = round ((fromIntegral len) / 2)
1043         ; rangeL    = vecSlice (AST.PrimLit "0") (AST.PrimLit $ show (halflen - 1))
1044         ; rangeR    = vecSlice (AST.PrimLit $ show halflen) (AST.PrimLit $ show (len - 1))
1045         ; resname   = varToVHDLName res
1046         ; resnameL  = mkSelectedName resname (labels!!0)
1047         ; resnameR  = mkSelectedName resname (labels!!1)
1048         ; argexprL  = vhdlNameToVHDLExpr rangeL
1049         ; argexprR  = vhdlNameToVHDLExpr rangeR
1050         ; out_assignL = mkUncondAssign (Right resnameL) argexprL
1051         ; out_assignR = mkUncondAssign (Right resnameR) argexprR
1052         ; block = AST.BlockSm block_label [] (AST.PMapAspect []) [] [out_assignL, out_assignR]
1053         }
1054   ; return [AST.CSBSm block]
1055   }
1056   where
1057     vecSlice init last =  AST.NSlice (AST.SliceName (varToVHDLName res) 
1058                             (AST.ToRange init last))
1059 -----------------------------------------------------------------------------
1060 -- Function to generate VHDL for applications
1061 -----------------------------------------------------------------------------
1062 genApplication ::
1063   (Either CoreSyn.CoreBndr AST.VHDLName) -- ^ Where to store the result?
1064   -> CoreSyn.CoreBndr -- ^ The function to apply
1065   -> [Either CoreSyn.CoreExpr AST.Expr] -- ^ The arguments to apply
1066   -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr]) 
1067   -- ^ The corresponding VHDL concurrent statements and entities
1068   --   instantiated.
1069 genApplication dst f args = do
1070   nonemptydst <- case dst of
1071     Left bndr -> hasNonEmptyType bndr 
1072     Right _ -> return True
1073   if nonemptydst
1074     then
1075       if Var.isGlobalId f then
1076         case Var.idDetails f of
1077           IdInfo.DataConWorkId dc -> case dst of
1078             -- It's a datacon. Create a record from its arguments.
1079             Left bndr -> do
1080               -- We have the bndr, so we can get at the type
1081               htype_either <- MonadState.lift tsType $ mkHTypeEither (Var.varType bndr)
1082               let argsNoState = filter (\x -> not (either hasStateType (\x -> False) x)) args
1083               let dcs = datacons_for bndr
1084               case (dcs, argsNoState) of
1085                 -- This is a type with a single datacon and a single
1086                 -- argument, so no record is created (the type of the
1087                 -- binder becomes the type of the single argument).
1088                 ([_], [arg]) -> do
1089                   [arg'] <- argsToVHDLExprs [arg]
1090                   return ([mkUncondAssign dst arg'], [])
1091                 -- In all other cases, a record type is created.
1092                 _ -> case htype_either of
1093                   Right htype@(AggrType _ _ _) -> do
1094                     let dc_i = datacon_index (Var.varType bndr) dc
1095                     let labels = getFieldLabels htype dc_i
1096                     arg_exprs <- argsToVHDLExprs argsNoState
1097                     let (final_labels, final_exprs) = case getConstructorFieldLabel htype of
1098                           -- Only a single constructor
1099                           Nothing -> 
1100                             (labels, arg_exprs)
1101                           -- Multiple constructors, so assign the
1102                           -- constructor used to the constructor field as
1103                           -- well.
1104                           Just dc_label ->
1105                             let dc_expr = AST.PrimName $ AST.NSimple $ mkVHDLExtId $ varToString f in
1106                             (dc_label:labels, dc_expr:arg_exprs)
1107                     return (zipWith mkassign final_labels final_exprs, [])
1108                     where
1109                       mkassign :: AST.VHDLId -> AST.Expr -> AST.ConcSm
1110                       mkassign label arg =
1111                         let sel_name = mkSelectedName ((either varToVHDLName id) dst) label in
1112                         mkUncondAssign (Right sel_name) arg
1113                   -- Enumeration types have no arguments and are just
1114                   -- simple assignments
1115                   Right (EnumType _ _) ->
1116                     simple_assign
1117                   -- These builtin types are also enumeration types
1118                   Right (BuiltinType tyname) | tyname `elem` ["Bit", "Bool"] ->
1119                     simple_assign
1120                   Right _ -> error $ "Datacon application does not result in a aggregate type? datacon: " ++ pprString f ++ " Args: " ++ show args
1121                   Left _ -> error $ "Unrepresentable result type in datacon application?  datacon: " ++ pprString f ++ " Args: " ++ show args
1122                   where
1123                     -- Simple uncoditional assignment, for (built-in)
1124                     -- enumeration types
1125                     simple_assign = do
1126                       expr <- MonadState.lift tsType $ dataconToVHDLExpr dc
1127                       return ([mkUncondAssign dst expr], [])
1128
1129             Right _ -> error "\nGenerate.genApplication(DataConWorkId): Can't generate dataconstructor application without an original binder"
1130           IdInfo.DataConWrapId dc -> case dst of
1131             -- It's a datacon. Create a record from its arguments.
1132             Left bndr ->
1133               case (Map.lookup (varToString f) globalNameTable) of
1134                Just (arg_count, builder) ->
1135                 if length args == arg_count then
1136                   builder dst f args
1137                 else
1138                   error $ "\nGenerate.genApplication(DataConWrapId): Incorrect number of arguments to builtin function: " ++ pprString f ++ " Args: " ++ show args
1139                Nothing -> error $ "\nGenerate.genApplication(DataConWrapId): Can't generate dataconwrapper: " ++ (show dc)
1140             Right _ -> error "\nGenerate.genApplication(DataConWrapId): Can't generate dataconwrapper application without an original binder"
1141           IdInfo.VanillaId ->
1142             -- It's a global value imported from elsewhere. These can be builtin
1143             -- functions. Look up the function name in the name table and execute
1144             -- the associated builder if there is any and the argument count matches
1145             -- (this should always be the case if it typechecks, but just to be
1146             -- sure...).
1147             case (Map.lookup (varToString f) globalNameTable) of
1148               Just (arg_count, builder) ->
1149                 if length args == arg_count then
1150                   builder dst f args
1151                 else
1152                   error $ "\nGenerate.genApplication(VanillaId): Incorrect number of arguments to builtin function: " ++ pprString f ++ " Args: " ++ show args
1153               Nothing -> do
1154                 top <- isTopLevelBinder f
1155                 if top then
1156                   do
1157                     -- Local binder that references a top level binding.  Generate a
1158                     -- component instantiation.
1159                     signature <- getEntity f
1160                     args' <- argsToVHDLExprs args
1161                     let entity_id = ent_id signature
1162                     -- TODO: Using show here isn't really pretty, but we'll need some
1163                     -- unique-ish value...
1164                     let label = "comp_ins_" ++ (either show prettyShow) dst
1165                     let portmaps = mkAssocElems args' ((either varToVHDLName id) dst) signature
1166                     return ([mkComponentInst label entity_id portmaps], [f])
1167                   else
1168                     -- Not a top level binder, so this must be a local variable reference.
1169                     -- It should have a representable type (and thus, no arguments) and a
1170                     -- signal should be generated for it. Just generate an unconditional
1171                     -- assignment here.
1172                     -- FIXME : I DONT KNOW IF THE ABOVE COMMENT HOLDS HERE, SO FOR NOW JUST ERROR!
1173                     -- f' <- MonadState.lift tsType $ varToVHDLExpr f
1174                     --                   return $ ([mkUncondAssign dst f'], [])
1175                   do errtype <- case dst of 
1176                         Left bndr -> do 
1177                           htype <- MonadState.lift tsType $ mkHTypeEither (Var.varType bndr)
1178                           return (show htype)
1179                         Right vhd -> return $ show vhd
1180                      error ("\nGenerate.genApplication(VanillaId): Using function from another module that is not a known builtin: " ++ (pprString f) ++ "::" ++ errtype) 
1181           IdInfo.ClassOpId cls ->
1182             -- FIXME: Not looking for what instance this class op is called for
1183             -- Is quite stupid of course.
1184             case (Map.lookup (varToString f) globalNameTable) of
1185               Just (arg_count, builder) ->
1186                 if length args == arg_count then
1187                   builder dst f args
1188                 else
1189                   error $ "\nGenerate.genApplication(ClassOpId): Incorrect number of arguments to builtin function: " ++ pprString f ++ " Args: " ++ show args
1190               Nothing -> error $ "\nGenerate.genApplication(ClassOpId): Using function from another module that is not a known builtin: " ++ pprString f
1191           details -> error $ "\nGenerate.genApplication: Calling unsupported function " ++ pprString f ++ " with GlobalIdDetails " ++ pprString details
1192         else do
1193           top <- isTopLevelBinder f
1194           if top then
1195             do
1196                -- Local binder that references a top level binding.  Generate a
1197                -- component instantiation.
1198                signature <- getEntity f
1199                args' <- argsToVHDLExprs args
1200                let entity_id = ent_id signature
1201                -- TODO: Using show here isn't really pretty, but we'll need some
1202                -- unique-ish value...
1203                let label = "comp_ins_" ++ (either (prettyShow . varToVHDLName) prettyShow) dst
1204                let portmaps = mkAssocElems args' ((either varToVHDLName id) dst) signature
1205                return ([mkComponentInst label entity_id portmaps], [f])
1206             else
1207               -- Not a top level binder, so this must be a local variable reference.
1208               -- It should have a representable type (and thus, no arguments) and a
1209               -- signal should be generated for it. Just generate an unconditional
1210               -- assignment here.
1211             do f' <- MonadState.lift tsType $ varToVHDLExpr f
1212                return ([mkUncondAssign dst f'], [])
1213     else -- Destination has empty type, don't generate anything
1214       return ([], [])
1215 -----------------------------------------------------------------------------
1216 -- Functions to generate functions dealing with vectors.
1217 -----------------------------------------------------------------------------
1218
1219 -- Returns the VHDLId of the vector function with the given name for the given
1220 -- element type. Generates -- this function if needed.
1221 vectorFunId :: Type.Type -> String -> TypeSession AST.VHDLId
1222 vectorFunId el_ty fname = do
1223   let error_msg = "\nGenerate.vectorFunId: Can not construct vector function for element: " ++ pprString el_ty
1224   -- TODO: Handle the Nothing case?
1225   elemTM_maybe <- vhdlTy error_msg el_ty
1226   let elemTM = Maybe.fromMaybe
1227                  (error $ "\nGenerate.vectorFunId: Cannot generate vector function \"" ++ fname ++ "\" for the empty type \"" ++ (pprString el_ty) ++ "\"")
1228                  elemTM_maybe
1229   -- TODO: This should not be duplicated from mk_vector_ty. Probably but it in
1230   -- the VHDLState or something.
1231   let vectorTM = mkVHDLExtId $ "vector_" ++ (AST.fromVHDLId elemTM)
1232   typefuns <- MonadState.get tsTypeFuns
1233   el_htype <- mkHType error_msg el_ty
1234   case Map.lookup (UVecType el_htype, fname) typefuns of
1235     -- Function already generated, just return it
1236     Just (id, _) -> return id
1237     -- Function not generated yet, generate it
1238     Nothing -> do
1239       let functions = genUnconsVectorFuns elemTM vectorTM
1240       case lookup fname functions of
1241         Just body -> do
1242           MonadState.modify tsTypeFuns $ Map.insert (UVecType el_htype, fname) (function_id, (fst body))
1243           mapM_ (vectorFunId el_ty) (snd body)
1244           return function_id
1245         Nothing -> error $ "\nGenerate.vectorFunId: I don't know how to generate vector function " ++ fname
1246   where
1247     function_id = mkVHDLExtId fname
1248
1249 genUnconsVectorFuns :: AST.TypeMark -- ^ type of the vector elements
1250                     -> AST.TypeMark -- ^ type of the vector
1251                     -> [(String, (AST.SubProgBody, [String]))]
1252 genUnconsVectorFuns elemTM vectorTM  = 
1253   [ (exId, (AST.SubProgBody exSpec      []                  [exExpr],[]))
1254   , (replaceId, (AST.SubProgBody replaceSpec [AST.SPVD replaceVar] [replaceExpr1,replaceExpr2,replaceRet],[]))
1255   , (lastId, (AST.SubProgBody lastSpec    []                  [lastExpr],[]))
1256   , (initId, (AST.SubProgBody initSpec    [AST.SPVD initVar]  [initExpr, initRet],[]))
1257   , (minimumId, (AST.SubProgBody minimumSpec [] [minimumExpr],[]))
1258   , (takeId, (AST.SubProgBody takeSpec    [AST.SPVD takeVar]  [takeExpr, takeRet],[minimumId]))
1259   , (dropId, (AST.SubProgBody dropSpec    [AST.SPVD dropVar]  [dropExpr, dropRet],[]))
1260   , (plusgtId, (AST.SubProgBody plusgtSpec  [AST.SPVD plusgtVar] [plusgtExpr, plusgtRet],[]))
1261   , (emptyId, (AST.SubProgBody emptySpec   [AST.SPVD emptyVar] [emptyExpr],[]))
1262   , (singletonId, (AST.SubProgBody singletonSpec [AST.SPVD singletonVar] [singletonRet],[]))
1263   , (copynId, (AST.SubProgBody copynSpec    [AST.SPVD copynVar]      [copynExpr],[]))
1264   , (selId, (AST.SubProgBody selSpec  [AST.SPVD selVar] [selFor, selRet],[]))
1265   , (ltplusId, (AST.SubProgBody ltplusSpec [AST.SPVD ltplusVar] [ltplusExpr, ltplusRet],[]))  
1266   , (plusplusId, (AST.SubProgBody plusplusSpec [AST.SPVD plusplusVar] [plusplusExpr, plusplusRet],[]))
1267   , (lengthTId, (AST.SubProgBody lengthTSpec [] [lengthTExpr],[]))
1268   , (shiftlId, (AST.SubProgBody shiftlSpec [AST.SPVD shiftlVar] [shiftlExpr, shiftlRet], [initId]))
1269   , (shiftrId, (AST.SubProgBody shiftrSpec [AST.SPVD shiftrVar] [shiftrExpr, shiftrRet], [tailId]))
1270   , (nullId, (AST.SubProgBody nullSpec [] [nullExpr], []))
1271   , (rotlId, (AST.SubProgBody rotlSpec [AST.SPVD rotlVar] [rotlExpr, rotlRet], [nullId, lastId, initId]))
1272   , (rotrId, (AST.SubProgBody rotrSpec [AST.SPVD rotrVar] [rotrExpr, rotrRet], [nullId, tailId, headId]))
1273   , (reverseId, (AST.SubProgBody reverseSpec [AST.SPVD reverseVar] [reverseFor, reverseRet], []))
1274   ]
1275   where 
1276     ixPar   = AST.unsafeVHDLBasicId "ix"
1277     vecPar  = AST.unsafeVHDLBasicId "vec"
1278     vec1Par = AST.unsafeVHDLBasicId "vec1"
1279     vec2Par = AST.unsafeVHDLBasicId "vec2"
1280     nPar    = AST.unsafeVHDLBasicId "n"
1281     leftPar = AST.unsafeVHDLBasicId "nLeft"
1282     rightPar = AST.unsafeVHDLBasicId "nRight"
1283     iId     = AST.unsafeVHDLBasicId "i"
1284     iPar    = iId
1285     aPar    = AST.unsafeVHDLBasicId "a"
1286     fPar = AST.unsafeVHDLBasicId "f"
1287     sPar = AST.unsafeVHDLBasicId "s"
1288     resId   = AST.unsafeVHDLBasicId "res"    
1289     exSpec = AST.Function (mkVHDLExtId exId) [AST.IfaceVarDec vecPar vectorTM,
1290                                AST.IfaceVarDec ixPar  unsignedTM] elemTM
1291     exExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NIndexed 
1292               (AST.IndexedName (AST.NSimple vecPar) [genExprFCall (mkVHDLBasicId toIntegerId) (AST.PrimName $ AST.NSimple ixPar)]))
1293     replaceSpec = AST.Function (mkVHDLExtId replaceId)  [ AST.IfaceVarDec vecPar vectorTM
1294                                           , AST.IfaceVarDec iPar   unsignedTM
1295                                           , AST.IfaceVarDec aPar   elemTM
1296                                           ] vectorTM 
1297        -- variable res : fsvec_x (0 to vec'length-1);
1298     replaceVar =
1299          AST.VarDec resId 
1300                 (AST.SubtypeIn vectorTM
1301                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
1302                    [AST.ToRange (AST.PrimLit "0")
1303                             (AST.PrimName (AST.NAttribute $ 
1304                               AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1305                                 (AST.PrimLit "1"))   ]))
1306                 Nothing
1307        --  res AST.:= vec(0 to i-1) & a & vec(i+1 to length'vec-1)
1308     replaceExpr1 = AST.NSimple resId AST.:= AST.PrimName (AST.NSimple vecPar)
1309     replaceExpr2 = AST.NIndexed (AST.IndexedName (AST.NSimple resId) [genExprFCall (mkVHDLBasicId toIntegerId) (AST.PrimName $ AST.NSimple iPar)]) AST.:= AST.PrimName (AST.NSimple aPar)
1310     replaceRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1311     vecSlice init last =  AST.PrimName (AST.NSlice 
1312                                         (AST.SliceName 
1313                                               (AST.NSimple vecPar) 
1314                                               (AST.ToRange init last)))
1315     lastSpec = AST.Function (mkVHDLExtId lastId) [AST.IfaceVarDec vecPar vectorTM] elemTM
1316        -- return vec(vec'length-1);
1317     lastExpr = AST.ReturnSm (Just (AST.PrimName $ AST.NIndexed (AST.IndexedName 
1318                     (AST.NSimple vecPar) 
1319                     [AST.PrimName (AST.NAttribute $ 
1320                                 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) 
1321                                                              AST.:-: AST.PrimLit "1"])))
1322     initSpec = AST.Function (mkVHDLExtId initId) [AST.IfaceVarDec vecPar vectorTM] vectorTM 
1323        -- variable res : fsvec_x (0 to vec'length-2);
1324     initVar = 
1325          AST.VarDec resId 
1326                 (AST.SubtypeIn vectorTM
1327                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
1328                    [AST.ToRange (AST.PrimLit "0")
1329                             (AST.PrimName (AST.NAttribute $ 
1330                               AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1331                                 (AST.PrimLit "2"))   ]))
1332                 Nothing
1333        -- resAST.:= vec(0 to vec'length-2)
1334     initExpr = AST.NSimple resId AST.:= (vecSlice 
1335                                (AST.PrimLit "0") 
1336                                (AST.PrimName (AST.NAttribute $ 
1337                                   AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) 
1338                                                              AST.:-: AST.PrimLit "2"))
1339     initRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1340     minimumSpec = AST.Function (mkVHDLExtId minimumId) [AST.IfaceVarDec leftPar   naturalTM,
1341                                    AST.IfaceVarDec rightPar naturalTM ] naturalTM
1342     minimumExpr = AST.IfSm ((AST.PrimName $ AST.NSimple leftPar) AST.:<: (AST.PrimName $ AST.NSimple rightPar))
1343                         [AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple leftPar)]
1344                         []
1345                         (Just $ AST.Else [minimumExprRet])
1346       where minimumExprRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple rightPar)
1347     takeSpec = AST.Function (mkVHDLExtId takeId) [AST.IfaceVarDec nPar   naturalTM,
1348                                    AST.IfaceVarDec vecPar vectorTM ] vectorTM
1349        -- variable res : fsvec_x (0 to (minimum (n,vec'length))-1);
1350     minLength = AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId minimumId))  
1351                               [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple nPar)
1352                               ,Nothing AST.:=>: AST.ADExpr (AST.PrimName (AST.NAttribute $ 
1353                                 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing))]
1354     takeVar = 
1355          AST.VarDec resId 
1356                 (AST.SubtypeIn vectorTM
1357                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
1358                    [AST.ToRange (AST.PrimLit "0")
1359                                (minLength AST.:-:
1360                                 (AST.PrimLit "1"))   ]))
1361                 Nothing
1362        -- res AST.:= vec(0 to n-1)
1363     takeExpr = AST.NSimple resId AST.:= 
1364                     (vecSlice (AST.PrimLit "0") 
1365                               (minLength AST.:-: AST.PrimLit "1"))
1366     takeRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1367     dropSpec = AST.Function (mkVHDLExtId dropId) [AST.IfaceVarDec nPar   naturalTM,
1368                                    AST.IfaceVarDec vecPar vectorTM ] vectorTM 
1369        -- variable res : fsvec_x (0 to vec'length-n-1);
1370     dropVar = 
1371          AST.VarDec resId 
1372                 (AST.SubtypeIn vectorTM
1373                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
1374                    [AST.ToRange (AST.PrimLit "0")
1375                             (AST.PrimName (AST.NAttribute $ 
1376                               AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1377                                (AST.PrimName $ AST.NSimple nPar)AST.:-: (AST.PrimLit "1")) ]))
1378                Nothing
1379        -- res AST.:= vec(n to vec'length-1)
1380     dropExpr = AST.NSimple resId AST.:= (vecSlice 
1381                                (AST.PrimName $ AST.NSimple nPar) 
1382                                (AST.PrimName (AST.NAttribute $ 
1383                                   AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) 
1384                                                              AST.:-: AST.PrimLit "1"))
1385     dropRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1386     plusgtSpec = AST.Function (mkVHDLExtId plusgtId) [AST.IfaceVarDec aPar   elemTM,
1387                                        AST.IfaceVarDec vecPar vectorTM] vectorTM 
1388     -- variable res : fsvec_x (0 to vec'length);
1389     plusgtVar = 
1390       AST.VarDec resId 
1391              (AST.SubtypeIn vectorTM
1392                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
1393                 [AST.ToRange (AST.PrimLit "0")
1394                         (AST.PrimName (AST.NAttribute $ 
1395                           AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing))]))
1396              Nothing
1397     plusgtExpr = AST.NSimple resId AST.:= 
1398                    ((AST.PrimName $ AST.NSimple aPar) AST.:&: 
1399                     (AST.PrimName $ AST.NSimple vecPar))
1400     plusgtRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1401     emptySpec = AST.Function (mkVHDLExtId emptyId) [] vectorTM
1402     emptyVar = 
1403           AST.VarDec resId
1404             (AST.SubtypeIn vectorTM
1405               (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
1406                 [AST.ToRange (AST.PrimLit "0") (AST.PrimLit "-1")]))
1407              Nothing
1408     emptyExpr = AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
1409     singletonSpec = AST.Function (mkVHDLExtId singletonId) [AST.IfaceVarDec aPar elemTM ] 
1410                                          vectorTM
1411     -- variable res : fsvec_x (0 to 0) := (others => a);
1412     singletonVar = 
1413       AST.VarDec resId 
1414              (AST.SubtypeIn vectorTM
1415                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
1416                 [AST.ToRange (AST.PrimLit "0") (AST.PrimLit "0")]))
1417              (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
1418                                           (AST.PrimName $ AST.NSimple aPar)])
1419     singletonRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1420     copynSpec = AST.Function (mkVHDLExtId copynId) [AST.IfaceVarDec nPar   naturalTM,
1421                                    AST.IfaceVarDec aPar   elemTM   ] vectorTM 
1422     -- variable res : fsvec_x (0 to n-1) := (others => a);
1423     copynVar = 
1424       AST.VarDec resId 
1425              (AST.SubtypeIn vectorTM
1426                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
1427                 [AST.ToRange (AST.PrimLit "0")
1428                             ((AST.PrimName (AST.NSimple nPar)) AST.:-:
1429                              (AST.PrimLit "1"))   ]))
1430              (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
1431                                           (AST.PrimName $ AST.NSimple aPar)])
1432     -- return res
1433     copynExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1434     selSpec = AST.Function (mkVHDLExtId selId) [AST.IfaceVarDec fPar   naturalTM,
1435                                AST.IfaceVarDec sPar   naturalTM,
1436                                AST.IfaceVarDec nPar   naturalTM,
1437                                AST.IfaceVarDec vecPar vectorTM ] vectorTM
1438     -- variable res : fsvec_x (0 to n-1);
1439     selVar = 
1440       AST.VarDec resId 
1441                 (AST.SubtypeIn vectorTM
1442                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
1443                     [AST.ToRange (AST.PrimLit "0")
1444                       ((AST.PrimName (AST.NSimple nPar)) AST.:-:
1445                       (AST.PrimLit "1"))   ])
1446                 )
1447                 Nothing
1448     -- for i res'range loop
1449     --   res(i) := vec(f+i*s);
1450     -- end loop;
1451     selFor = AST.ForSM iId (AST.AttribRange $ AST.AttribName (AST.NSimple resId) (AST.NSimple rangeId) Nothing) [selAssign]
1452     -- res(i) := vec(f+i*s);
1453     selAssign = let origExp = AST.PrimName (AST.NSimple fPar) AST.:+: 
1454                                 (AST.PrimName (AST.NSimple iId) AST.:*: 
1455                                   AST.PrimName (AST.NSimple sPar)) in
1456                                   AST.NIndexed (AST.IndexedName (AST.NSimple resId) [AST.PrimName (AST.NSimple iId)]) AST.:=
1457                                     (AST.PrimName $ AST.NIndexed (AST.IndexedName (AST.NSimple vecPar) [origExp]))
1458     -- return res;
1459     selRet =  AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
1460     ltplusSpec = AST.Function (mkVHDLExtId ltplusId) [AST.IfaceVarDec vecPar vectorTM,
1461                                         AST.IfaceVarDec aPar   elemTM] vectorTM 
1462      -- variable res : fsvec_x (0 to vec'length);
1463     ltplusVar = 
1464       AST.VarDec resId 
1465         (AST.SubtypeIn vectorTM
1466           (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
1467             [AST.ToRange (AST.PrimLit "0")
1468               (AST.PrimName (AST.NAttribute $ 
1469                 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing))]))
1470         Nothing
1471     ltplusExpr = AST.NSimple resId AST.:= 
1472                      ((AST.PrimName $ AST.NSimple vecPar) AST.:&: 
1473                       (AST.PrimName $ AST.NSimple aPar))
1474     ltplusRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1475     plusplusSpec = AST.Function (mkVHDLExtId plusplusId) [AST.IfaceVarDec vec1Par vectorTM,
1476                                              AST.IfaceVarDec vec2Par vectorTM] 
1477                                              vectorTM 
1478     -- variable res : fsvec_x (0 to vec1'length + vec2'length -1);
1479     plusplusVar = 
1480       AST.VarDec resId 
1481         (AST.SubtypeIn vectorTM
1482           (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
1483             [AST.ToRange (AST.PrimLit "0")
1484               (AST.PrimName (AST.NAttribute $ 
1485                 AST.AttribName (AST.NSimple vec1Par) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:+:
1486                   AST.PrimName (AST.NAttribute $ 
1487                 AST.AttribName (AST.NSimple vec2Par) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1488                   AST.PrimLit "1")]))
1489        Nothing
1490     plusplusExpr = AST.NSimple resId AST.:= 
1491                      ((AST.PrimName $ AST.NSimple vec1Par) AST.:&: 
1492                       (AST.PrimName $ AST.NSimple vec2Par))
1493     plusplusRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1494     lengthTSpec = AST.Function (mkVHDLExtId lengthTId) [AST.IfaceVarDec vecPar vectorTM] naturalTM
1495     lengthTExpr = AST.ReturnSm (Just $ AST.PrimName (AST.NAttribute $ 
1496                                 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing))
1497     shiftlSpec = AST.Function (mkVHDLExtId shiftlId) [AST.IfaceVarDec vecPar vectorTM,
1498                                    AST.IfaceVarDec aPar   elemTM  ] vectorTM 
1499     -- variable res : fsvec_x (0 to vec'length-1);
1500     shiftlVar = 
1501      AST.VarDec resId 
1502             (AST.SubtypeIn vectorTM
1503               (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
1504                [AST.ToRange (AST.PrimLit "0")
1505                         (AST.PrimName (AST.NAttribute $ 
1506                           AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1507                            (AST.PrimLit "1")) ]))
1508             Nothing
1509     -- res := a & init(vec)
1510     shiftlExpr = AST.NSimple resId AST.:=
1511                     (AST.PrimName (AST.NSimple aPar) AST.:&:
1512                      (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId initId))  
1513                        [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]))
1514     shiftlRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)       
1515     shiftrSpec = AST.Function (mkVHDLExtId shiftrId) [AST.IfaceVarDec vecPar vectorTM,
1516                                        AST.IfaceVarDec aPar   elemTM  ] vectorTM 
1517     -- variable res : fsvec_x (0 to vec'length-1);
1518     shiftrVar = 
1519      AST.VarDec resId 
1520             (AST.SubtypeIn vectorTM
1521               (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
1522                [AST.ToRange (AST.PrimLit "0")
1523                         (AST.PrimName (AST.NAttribute $ 
1524                           AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1525                            (AST.PrimLit "1")) ]))
1526             Nothing
1527     -- res := tail(vec) & a
1528     shiftrExpr = AST.NSimple resId AST.:=
1529                   ((AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId tailId))  
1530                     [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]) AST.:&:
1531                   (AST.PrimName (AST.NSimple aPar)))
1532                 
1533     shiftrRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)      
1534     nullSpec = AST.Function (mkVHDLExtId nullId) [AST.IfaceVarDec vecPar vectorTM] booleanTM
1535     -- return vec'length = 0
1536     nullExpr = AST.ReturnSm (Just $ 
1537                 AST.PrimName (AST.NAttribute $ 
1538                   AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:=:
1539                     AST.PrimLit "0")
1540     rotlSpec = AST.Function (mkVHDLExtId rotlId) [AST.IfaceVarDec vecPar vectorTM] vectorTM 
1541     -- variable res : fsvec_x (0 to vec'length-1);
1542     rotlVar = 
1543      AST.VarDec resId 
1544             (AST.SubtypeIn vectorTM
1545               (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
1546                [AST.ToRange (AST.PrimLit "0")
1547                         (AST.PrimName (AST.NAttribute $ 
1548                           AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1549                            (AST.PrimLit "1")) ]))
1550             Nothing
1551     -- if null(vec) then res := vec else res := last(vec) & init(vec)
1552     rotlExpr = AST.IfSm (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId nullId))  
1553                           [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)])
1554                         [AST.NSimple resId AST.:= (AST.PrimName $ AST.NSimple vecPar)]
1555                         []
1556                         (Just $ AST.Else [rotlExprRet])
1557       where rotlExprRet = 
1558                 AST.NSimple resId AST.:= 
1559                       ((AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId lastId))  
1560                         [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]) AST.:&:
1561                       (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId initId))  
1562                         [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]))
1563     rotlRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)       
1564     rotrSpec = AST.Function (mkVHDLExtId rotrId) [AST.IfaceVarDec vecPar vectorTM] vectorTM 
1565     -- variable res : fsvec_x (0 to vec'length-1);
1566     rotrVar = 
1567      AST.VarDec resId 
1568             (AST.SubtypeIn vectorTM
1569               (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
1570                [AST.ToRange (AST.PrimLit "0")
1571                         (AST.PrimName (AST.NAttribute $ 
1572                           AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1573                            (AST.PrimLit "1")) ]))
1574             Nothing
1575     -- if null(vec) then res := vec else res := tail(vec) & head(vec)
1576     rotrExpr = AST.IfSm (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId nullId))  
1577                           [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)])
1578                         [AST.NSimple resId AST.:= (AST.PrimName $ AST.NSimple vecPar)]
1579                         []
1580                         (Just $ AST.Else [rotrExprRet])
1581       where rotrExprRet = 
1582                 AST.NSimple resId AST.:= 
1583                       ((AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId tailId))  
1584                         [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]) AST.:&:
1585                       (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId headId))  
1586                         [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]))
1587     rotrRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1588     reverseSpec = AST.Function (mkVHDLExtId reverseId) [AST.IfaceVarDec vecPar vectorTM] vectorTM
1589     reverseVar = 
1590       AST.VarDec resId 
1591              (AST.SubtypeIn vectorTM
1592                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
1593                 [AST.ToRange (AST.PrimLit "0")
1594                          (AST.PrimName (AST.NAttribute $ 
1595                            AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1596                             (AST.PrimLit "1")) ]))
1597              Nothing
1598     -- for i in 0 to res'range loop
1599     --   res(vec'length-i-1) := vec(i);
1600     -- end loop;
1601     reverseFor = 
1602        AST.ForSM iId (AST.AttribRange $ AST.AttribName (AST.NSimple resId) (AST.NSimple rangeId) Nothing) [reverseAssign]
1603     -- res(vec'length-i-1) := vec(i);
1604     reverseAssign = AST.NIndexed (AST.IndexedName (AST.NSimple resId) [destExp]) AST.:=
1605       (AST.PrimName $ AST.NIndexed (AST.IndexedName (AST.NSimple vecPar) 
1606                            [AST.PrimName $ AST.NSimple iId]))
1607         where destExp = AST.PrimName (AST.NAttribute $ AST.AttribName (AST.NSimple vecPar) 
1608                                    (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-: 
1609                         AST.PrimName (AST.NSimple iId) AST.:-: 
1610                         (AST.PrimLit "1") 
1611     -- return res;
1612     reverseRet = AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
1613
1614     
1615 -----------------------------------------------------------------------------
1616 -- A table of builtin functions
1617 -----------------------------------------------------------------------------
1618
1619 -- A function that generates VHDL for a builtin function
1620 type BuiltinBuilder = 
1621   (Either CoreSyn.CoreBndr AST.VHDLName) -- ^ The destination signal and it's original type
1622   -> CoreSyn.CoreBndr -- ^ The function called
1623   -> [(Either CoreSyn.CoreExpr AST.Expr, Type.Type)] -- ^ The value arguments passed (excluding type and
1624                     --   dictionary arguments).
1625   -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr]) 
1626   -- ^ The corresponding VHDL concurrent statements and entities
1627   --   instantiated.
1628
1629 -- A map of a builtin function to VHDL function builder 
1630 type NameTable = Map.Map String (Int, BuiltinBuilder )
1631
1632 -- | The builtin functions we support. Maps a name to an argument count and a
1633 -- builder function. If you add a name to this map, don't forget to add
1634 -- it to VHDL.Constants/builtinIds as well.
1635 globalNameTable :: NameTable
1636 globalNameTable = Map.fromList
1637   [ (exId             , (2, genFCall True          ) )
1638   , (replaceId        , (3, genFCall False          ) )
1639   , (headId           , (1, genFCall True           ) )
1640   , (lastId           , (1, genFCall True           ) )
1641   , (tailId           , (1, genFCall False          ) )
1642   , (initId           , (1, genFCall False          ) )
1643   , (takeId           , (2, genFCall False          ) )
1644   , (dropId           , (2, genFCall False          ) )
1645   , (selId            , (4, genFCall False          ) )
1646   , (plusgtId         , (2, genFCall False          ) )
1647   , (ltplusId         , (2, genFCall False          ) )
1648   , (plusplusId       , (2, genFCall False          ) )
1649   , (mapId            , (2, genMap                  ) )
1650   , (zipWithId        , (3, genZipWith              ) )
1651   , (foldlId          , (3, genFoldl                ) )
1652   , (foldrId          , (3, genFoldr                ) )
1653   , (zipId            , (2, genZip                  ) )
1654   , (unzipId          , (1, genUnzip                ) )
1655   , (shiftlId         , (2, genFCall False          ) )
1656   , (shiftrId         , (2, genFCall False          ) )
1657   , (rotlId           , (1, genFCall False          ) )
1658   , (rotrId           , (1, genFCall False          ) )
1659   , (concatId         , (1, genConcat               ) )
1660   , (reverseId        , (1, genFCall False          ) )
1661   , (iteratenId       , (3, genIteraten             ) )
1662   , (iterateId        , (2, genIterate              ) )
1663   , (generatenId      , (3, genGeneraten            ) )
1664   , (generateId       , (2, genGenerate             ) )
1665   , (emptyId          , (0, genFCall False          ) )
1666   , (singletonId      , (1, genFCall False          ) )
1667   , (copynId          , (2, genFCall False          ) )
1668   , (copyId           , (1, genCopy                 ) )
1669   , (lengthTId        , (1, genFCall False          ) )
1670   , (nullId           , (1, genFCall False          ) )
1671   , (hwxorId          , (2, genOperator2 AST.Xor    ) )
1672   , (hwandId          , (2, genOperator2 AST.And    ) )
1673   , (hworId           , (2, genOperator2 AST.Or     ) )
1674   , (hwnotId          , (1, genOperator1 AST.Not    ) )
1675   , (equalityId       , (2, genOperator2 (AST.:=:)  ) )
1676   , (inEqualityId     , (2, genOperator2 (AST.:/=:) ) )
1677   , (ltId             , (2, genOperator2 (AST.:<:)  ) )
1678   , (lteqId           , (2, genOperator2 (AST.:<=:) ) )
1679   , (gtId             , (2, genOperator2 (AST.:>:)  ) )
1680   , (gteqId           , (2, genOperator2 (AST.:>=:) ) )
1681   , (boolOrId         , (2, genOperator2 AST.Or     ) )
1682   , (boolAndId        , (2, genOperator2 AST.And    ) )
1683   , (boolNot          , (1, genOperator1 AST.Not    ) )
1684   , (plusId           , (2, genOperator2 (AST.:+:)  ) )
1685   , (timesId          , (2, genTimes                ) )
1686   , (negateId         , (1, genNegation             ) )
1687   , (minusId          , (2, genOperator2 (AST.:-:)  ) )
1688   , (fromSizedWordId  , (1, genFromSizedWord        ) )
1689   , (fromRangedWordId , (1, genFromRangedWord       ) )
1690   , (fromIntegerId    , (1, genFromInteger          ) )
1691   , (resizeWordId     , (1, genResize               ) )
1692   , (resizeIntId      , (1, genResize               ) )
1693   , (sizedIntId       , (1, genSizedInt             ) )
1694   , (smallIntegerId   , (1, genFromInteger          ) )
1695   , (fstId            , (1, genFst                  ) )
1696   , (sndId            , (1, genSnd                  ) )
1697   , (blockRAMId       , (5, genBlockRAM             ) )
1698   , (splitId          , (1, genSplit                ) )
1699   --, (tfvecId          , (1, genTFVec                ) )
1700   , (minimumId        , (2, error "\nFunction name: \"minimum\" is used internally, use another name"))
1701   ]