1 module Main(main) where
4 import qualified CoreUtils
8 import qualified DataCon
10 import qualified Module
11 import qualified Control.Monad.State as State
14 import NameEnv ( lookupNameEnv )
15 import HscTypes ( cm_binds, cm_types )
16 import MonadUtils ( liftIO )
17 import Outputable ( showSDoc, ppr )
18 import GHC.Paths ( libdir )
19 import DynFlags ( defaultDynFlags )
22 import qualified Monad
24 -- The following modules come from the ForSyDe project. They are really
25 -- internal modules, so ForSyDe.cabal has to be modified prior to installing
26 -- ForSyDe to get access to these modules.
27 import qualified ForSyDe.Backend.VHDL.AST as AST
28 import qualified ForSyDe.Backend.VHDL.Ppr
29 import qualified ForSyDe.Backend.VHDL.FileIO
30 import qualified ForSyDe.Backend.Ppr
31 -- This is needed for rendering the pretty printed VHDL
32 import Text.PrettyPrint.HughesPJ (render)
36 defaultErrorHandler defaultDynFlags $ do
37 runGhc (Just libdir) $ do
38 dflags <- getSessionDynFlags
39 setSessionDynFlags dflags
40 --target <- guessTarget "adder.hs" Nothing
41 --liftIO (print (showSDoc (ppr (target))))
42 --liftIO $ printTarget target
45 --core <- GHC.compileToCoreSimplified "Adders.hs"
46 core <- GHC.compileToCoreSimplified "Adders.hs"
47 --liftIO $ printBinds (cm_binds core)
48 let binds = Maybe.mapMaybe (findBind (cm_binds core)) ["full_adder", "half_adder"]
49 liftIO $ printBinds binds
50 -- Turn bind into VHDL
51 let vhdl = State.evalState (mkVHDL binds) (VHDLSession 0 [])
52 liftIO $ putStr $ render $ ForSyDe.Backend.Ppr.ppr vhdl
53 liftIO $ ForSyDe.Backend.VHDL.FileIO.writeDesignFile vhdl "../vhdl/vhdl/output.vhdl"
56 -- Turns the given bind into VHDL
58 -- Add the builtin functions
59 mapM (uncurry addFunc) builtin_funcs
60 -- Create entities and architectures for them
61 units <- mapM expandBind binds
62 return $ AST.DesignFile
66 printTarget (Target (TargetFile file (Just x)) obj Nothing) =
69 printBinds [] = putStr "done\n\n"
70 printBinds (b:bs) = do
75 printBind (NonRec b expr) = do
79 printBind (Rec binds) = do
81 foldl1 (>>) (map printBind' binds)
83 printBind' (b, expr) = do
84 putStr $ getOccString b
85 putStr $ showSDoc $ ppr expr
88 findBind :: [CoreBind] -> String -> Maybe CoreBind
89 findBind binds lookfor =
90 -- This ignores Recs and compares the name of the bind with lookfor,
91 -- disregarding any namespaces in OccName and extra attributes in Name and
95 NonRec var _ -> lookfor == (occNameString $ nameOccName $ getName var)
99 SignalNameMap -- The port name to bind to
101 -- The signal or port to bind to it
102 -> AST.AssocElem -- The resulting port map entry
104 -- Accepts a port name and an argument to map to it.
105 -- Returns the appropriate line for in the port map
106 getPortMapEntry (Single (portname, _)) (Single (signame, _)) =
107 (Just portname) AST.:=>: (AST.ADName (AST.NSimple signame))
109 [(CoreBndr, SignalNameMap)]
110 -- A list of bindings in effect
111 -> CoreExpr -- The expression to expand
113 [AST.SigDec], -- Needed signal declarations
114 [AST.ConcSm], -- Needed component instantations and
115 -- signal assignments.
116 [SignalNameMap], -- The signal names corresponding to
117 -- the expression's arguments
118 SignalNameMap) -- The signal names corresponding to
119 -- the expression's result.
120 expandExpr binds lam@(Lam b expr) = do
121 -- Generate a new signal to which we will expect this argument to be bound.
122 signal_name <- uniqueName ("arg_" ++ getOccString b)
123 -- Find the type of the binder
124 let (arg_ty, _) = Type.splitFunTy (CoreUtils.exprType lam)
125 -- Create signal names for the binder
126 let arg_signal = getPortNameMapForTy ("xxx") arg_ty
127 -- Create the corresponding signal declarations
128 let signal_decls = mkSignalsFromMap arg_signal
129 -- Add the binder to the list of binds
130 let binds' = (b, arg_signal) : binds
131 -- Expand the rest of the expression
132 (signal_decls', statements', arg_signals', res_signal') <- expandExpr binds' expr
133 -- Properly merge the results
134 return (signal_decls ++ signal_decls',
136 arg_signal : arg_signals',
139 expandExpr binds (Var id) =
140 return ([], [], [], Single (signal_id, ty))
142 -- Lookup the id in our binds map
143 Single (signal_id, ty) = Maybe.fromMaybe
144 (error $ "Argument " ++ getOccString id ++ "is unknown")
147 expandExpr binds l@(Let (NonRec b bexpr) expr) = do
148 (signal_decls, statements, arg_signals, res_signals) <- expandExpr binds bexpr
149 let binds' = (b, res_signals) : binds
150 (signal_decls', statements', arg_signals', res_signals') <- expandExpr binds' expr
152 signal_decls ++ signal_decls',
153 statements ++ statements',
157 expandExpr binds app@(App _ _) = do
158 -- Is this a data constructor application?
159 case CoreUtils.exprIsConApp_maybe app of
160 -- Is this a tuple construction?
161 Just (dc, args) -> if DataCon.isTupleCon dc
163 expandBuildTupleExpr binds (dataConAppArgs dc args)
165 error "Data constructors other than tuples not supported"
167 -- Normal function application, should map to a component instantiation
168 let ((Var f), args) = collectArgs app in
169 expandApplicationExpr binds (CoreUtils.exprType app) f args
171 expandExpr binds expr@(Case (Var v) b _ alts) =
173 [alt] -> expandSingleAltCaseExpr binds v b alt
174 otherwise -> error $ "Multiple alternative case expression not supported: " ++ (showSDoc $ ppr expr)
176 expandExpr binds expr@(Case _ b _ _) =
177 error $ "Case expression with non-variable scrutinee not supported: " ++ (showSDoc $ ppr expr)
179 expandExpr binds expr =
180 error $ "Unsupported expression: " ++ (showSDoc $ ppr $ expr)
182 -- Expands the construction of a tuple into VHDL
183 expandBuildTupleExpr ::
184 [(CoreBndr, SignalNameMap)]
185 -- A list of bindings in effect
186 -> [CoreExpr] -- A list of expressions to put in the tuple
187 -> VHDLState ( [AST.SigDec], [AST.ConcSm], [SignalNameMap], SignalNameMap)
189 expandBuildTupleExpr binds args = do
190 -- Split the tuple constructor arguments into types and actual values.
191 -- Expand each of the values in the tuple
192 (signals_declss, statementss, arg_signalss, res_signals) <-
193 (Monad.liftM List.unzip4) $ mapM (expandExpr binds) args
194 if any (not . null) arg_signalss
195 then error "Putting high order functions in tuples not supported"
198 concat signals_declss,
203 -- Expands the most simple case expression that scrutinizes a plain variable
204 -- and has a single alternative. This simple form currently allows only for
205 -- unpacking tuple variables.
206 expandSingleAltCaseExpr ::
207 [(CoreBndr, SignalNameMap)]
208 -- A list of bindings in effect
209 -> Var.Var -- The scrutinee
210 -> CoreBndr -- The binder to bind the scrutinee to
211 -> CoreAlt -- The single alternative
212 -> VHDLState ( [AST.SigDec], [AST.ConcSm], [SignalNameMap], SignalNameMap)
215 expandSingleAltCaseExpr binds v b alt@(DataAlt datacon, bind_vars, expr) =
216 if not (DataCon.isTupleCon datacon)
218 error $ "Dataconstructors other than tuple constructors not supported in case pattern of alternative: " ++ (showSDoc $ ppr alt)
221 -- Lookup the scrutinee (which must be a variable bound to a tuple) in
222 -- the existing bindings list and get the portname map for each of
224 Tuple tuple_ports = Maybe.fromMaybe
225 (error $ "Case expression uses unknown scrutinee " ++ getOccString v)
227 -- TODO include b in the binds list
228 -- Merge our existing binds with the new binds.
229 binds' = (zip bind_vars tuple_ports) ++ binds
231 -- Expand the expression with the new binds list
232 expandExpr binds' expr
234 expandSingleAltCaseExpr _ _ _ alt =
235 error $ "Case patterns other than data constructors not supported in case alternative: " ++ (showSDoc $ ppr alt)
238 -- Expands the application of argument to a function into VHDL
239 expandApplicationExpr ::
240 [(CoreBndr, SignalNameMap)]
241 -- A list of bindings in effect
242 -> Type -- The result type of the function call
243 -> Var.Var -- The function to call
244 -> [CoreExpr] -- A list of argumetns to apply to the function
245 -> VHDLState ( [AST.SigDec], [AST.ConcSm], [SignalNameMap], SignalNameMap)
247 expandApplicationExpr binds ty f args = do
248 let name = getOccString f
249 -- Generate a unique name for the application
250 appname <- uniqueName ("app_" ++ name)
251 -- Lookup the hwfunction to instantiate
252 HWFunction vhdl_id inports outport <- getHWFunc (appToHsFunction f args ty)
253 -- Expand each of the args, so each of them is reduced to output signals
254 (arg_signal_decls, arg_statements, arg_res_signals) <- expandArgs binds args
255 -- Bind each of the input ports to the expanded arguments
256 let inmaps = concat $ zipWith createAssocElems inports arg_res_signals
257 -- Create signal names for our result
258 let res_signal = getPortNameMapForTy (appname ++ "_out") ty
259 -- Create the corresponding signal declarations
260 let signal_decls = mkSignalsFromMap res_signal
261 -- Bind each of the output ports to our output signals
262 let outmaps = mapOutputPorts outport res_signal
263 -- Instantiate the component
264 let component = AST.CSISm $ AST.CompInsSm
265 (AST.unsafeVHDLBasicId appname)
266 (AST.IUEntity (AST.NSimple vhdl_id))
267 (AST.PMapAspect (inmaps ++ outmaps))
268 -- Merge the generated declarations
270 signal_decls ++ arg_signal_decls,
271 component : arg_statements,
272 [], -- We don't take any extra arguments; we don't support higher order functions yet
275 -- Creates a list of AssocElems (port map lines) that maps the given signals
276 -- to the given ports.
278 SignalNameMap -- The port names to bind to
279 -> SignalNameMap -- The signals to bind to it
280 -> [AST.AssocElem] -- The resulting port map lines
282 createAssocElems (Single (port_id, _)) (Single (signal_id, _)) =
283 [(Just port_id) AST.:=>: (AST.ADName (AST.NSimple signal_id))]
285 createAssocElems (Tuple ports) (Tuple signals) =
286 concat $ zipWith createAssocElems ports signals
288 -- Generate a signal declaration for a signal with the given name and the
289 -- given type and no value. Also returns the id of the signal.
290 mkSignal :: String -> AST.TypeMark -> (AST.VHDLId, AST.SigDec)
292 (id, mkSignalFromId id ty)
294 id = AST.unsafeVHDLBasicId name
296 mkSignalFromId :: AST.VHDLId -> AST.TypeMark -> AST.SigDec
297 mkSignalFromId id ty =
298 AST.SigDec id ty Nothing
300 -- Generates signal declarations for all the signals in the given map
305 mkSignalsFromMap (Single (id, ty)) =
306 [mkSignalFromId id ty]
308 mkSignalsFromMap (Tuple signals) =
309 concat $ map mkSignalsFromMap signals
312 [(CoreBndr, SignalNameMap)] -- A list of bindings in effect
313 -> [CoreExpr] -- The arguments to expand
314 -> VHDLState ([AST.SigDec], [AST.ConcSm], [SignalNameMap])
315 -- The resulting signal declarations,
316 -- component instantiations and a
317 -- VHDLName for each of the
318 -- expressions passed in.
319 expandArgs binds (e:exprs) = do
320 -- Expand the first expression
321 (signal_decls, statements, arg_signals, res_signal) <- expandExpr binds e
322 if not (null arg_signals)
323 then error $ "Passing functions as arguments not supported: " ++ (showSDoc $ ppr e)
325 (signal_decls', statements', res_signals') <- expandArgs binds exprs
327 signal_decls ++ signal_decls',
328 statements ++ statements',
329 res_signal : res_signals')
331 expandArgs _ [] = return ([], [], [])
333 -- Extract the arguments from a data constructor application (that is, the
334 -- normal args, leaving out the type args).
335 dataConAppArgs :: DataCon -> [CoreExpr] -> [CoreExpr]
336 dataConAppArgs dc args =
339 tycount = length $ DataCon.dataConAllTyVars dc
342 SignalNameMap -- The output portnames of the component
343 -> SignalNameMap -- The output portnames and/or signals to map these to
344 -> [AST.AssocElem] -- The resulting output ports
346 -- Map the output port of a component to the output port of the containing
348 mapOutputPorts (Single (portname, _)) (Single (signalname, _)) =
349 [(Just portname) AST.:=>: (AST.ADName (AST.NSimple signalname))]
351 -- Map matching output ports in the tuple
352 mapOutputPorts (Tuple ports) (Tuple signals) =
353 concat (zipWith mapOutputPorts ports signals)
356 CoreBind -- The binder to expand into VHDL
357 -> VHDLState [AST.LibraryUnit] -- The resulting VHDL
359 expandBind (Rec _) = error "Recursive binders not supported"
361 expandBind bind@(NonRec var expr) = do
362 -- Create the function signature
363 (hsfunc, hwfunc) <- mkHWFunction bind
364 -- Add it to the session
365 addFunc hsfunc hwfunc
366 arch <- getArchitecture hwfunc expr
367 let entity = getEntity hwfunc
373 HWFunction -- The function to generate an architecture for
374 -> CoreExpr -- The expression that is bound to the function
375 -> VHDLState AST.ArchBody -- The resulting architecture
377 getArchitecture hwfunc expr = do
379 let HWFunction vhdl_id inports outport = hwfunc
380 -- Expand the expression into an architecture body
381 (signal_decls, statements, arg_signals, res_signal) <- expandExpr [] expr
382 let inport_assigns = concat $ zipWith createSignalAssignments arg_signals inports
383 let outport_assigns = createSignalAssignments outport res_signal
384 return $ AST.ArchBody
385 (AST.unsafeVHDLBasicId "structural")
386 (AST.NSimple vhdl_id)
387 (map AST.BDISD signal_decls)
388 (inport_assigns ++ outport_assigns ++ statements)
390 -- Generate a VHDL entity declaration for the given function
391 getEntity :: HWFunction -> AST.EntityDec
392 getEntity (HWFunction vhdl_id inports outport) =
393 AST.EntityDec vhdl_id ports
396 (concat $ map (mkIfaceSigDecs AST.In) inports)
397 ++ mkIfaceSigDecs AST.Out outport
400 AST.Mode -- The port's mode (In or Out)
401 -> SignalNameMap -- The ports to generate a map for
402 -> [AST.IfaceSigDec] -- The resulting ports
404 mkIfaceSigDecs mode (Single (port_id, ty)) =
405 [AST.IfaceSigDec port_id mode ty]
407 mkIfaceSigDecs mode (Tuple ports) =
408 concat $ map (mkIfaceSigDecs mode) ports
410 -- Create concurrent assignments of one map of signals to another. The maps
411 -- should have a similar form.
412 createSignalAssignments ::
413 SignalNameMap -- The signals to assign to
414 -> SignalNameMap -- The signals to assign
415 -> [AST.ConcSm] -- The resulting assignments
417 -- A simple assignment of one signal to another (greatly complicated because
418 -- signal assignments can be conditional with multiple conditions in VHDL).
419 createSignalAssignments (Single (dst, _)) (Single (src, _)) =
422 src_name = AST.NSimple src
423 src_expr = AST.PrimName src_name
424 src_wform = AST.Wform [AST.WformElem src_expr Nothing]
425 dst_name = (AST.NSimple dst)
426 assign = dst_name AST.:<==: (AST.ConWforms [] src_wform Nothing)
428 createSignalAssignments (Tuple dsts) (Tuple srcs) =
429 concat $ zipWith createSignalAssignments dsts srcs
431 createSignalAssignments dst src =
432 error $ "Non matching source and destination: " ++ show dst ++ "\nand\n" ++ show src
434 type SignalNameMap = HsValueMap (AST.VHDLId, AST.TypeMark)
436 -- | A datatype that maps each of the single values in a haskell structure to
437 -- a mapto. The map has the same structure as the haskell type mapped, ie
438 -- nested tuples etc.
439 data HsValueMap mapto =
440 Tuple [HsValueMap mapto]
444 -- | Creates a HsValueMap with the same structure as the given type, using the
445 -- given function for mapping the single types.
447 (Type -> HsValueMap mapto) -- ^ A function to map single value Types
448 -- (basically anything but tuples) to a
449 -- HsValueMap (not limited to the Single
451 -> Type -- ^ The type to map to a HsValueMap
452 -> HsValueMap mapto -- ^ The resulting map
455 case Type.splitTyConApp_maybe ty of
456 Just (tycon, args) ->
457 if (TyCon.isTupleTyCon tycon)
459 -- Handle tuple construction especially
460 Tuple (map (mkHsValueMap f) args)
462 -- And let f handle the rest
464 -- And let f handle the rest
467 -- Generate a port name map (or multiple for tuple types) in the given direction for
469 getPortNameMapForTys :: String -> Int -> [Type] -> [SignalNameMap]
470 getPortNameMapForTys prefix num [] = []
471 getPortNameMapForTys prefix num (t:ts) =
472 (getPortNameMapForTy (prefix ++ show num) t) : getPortNameMapForTys prefix (num + 1) ts
474 getPortNameMapForTy :: String -> Type -> SignalNameMap
475 getPortNameMapForTy name ty =
476 if (TyCon.isTupleTyCon tycon) then
477 -- Expand tuples we find
478 Tuple (getPortNameMapForTys name 0 args)
479 else -- Assume it's a type constructor application, ie simple data type
480 Single ((AST.unsafeVHDLBasicId name), (vhdl_ty ty))
482 (tycon, args) = Type.splitTyConApp ty
484 data HWFunction = HWFunction { -- A function that is available in hardware
485 vhdlId :: AST.VHDLId,
486 inPorts :: [SignalNameMap],
487 outPort :: SignalNameMap
488 --entity :: AST.EntityDec
491 -- Turns a CoreExpr describing a function into a description of its input and
494 CoreBind -- The core binder to generate the interface for
495 -> VHDLState (HsFunction, HWFunction) -- The name of the function and its interface
497 mkHWFunction (NonRec var expr) =
498 return (hsfunc, HWFunction (mkVHDLId name) inports outport)
500 name = getOccString var
501 ty = CoreUtils.exprType expr
502 (fargs, res) = Type.splitFunTys ty
503 args = if length fargs == 1 then fargs else (init fargs)
504 --state = if length fargs == 1 then () else (last fargs)
505 inports = case args of
506 -- Handle a single port specially, to prevent an extra 0 in the name
507 [port] -> [getPortNameMapForTy "portin" port]
508 ps -> getPortNameMapForTys "portin" 0 ps
509 outport = getPortNameMapForTy "portout" res
510 hsfunc = HsFunction name [] (Tuple [])
512 mkHWFunction (Rec _) =
513 error "Recursive binders not supported"
515 -- | How is a given (single) value in a function's type (ie, argument or
516 -- return value) used?
518 Port -- ^ Use it as a port (input or output)
521 -- | This type describes a particular use of a Haskell function and is used to
522 -- look up an appropriate hardware description.
523 data HsFunction = HsFunction {
524 hsName :: String, -- ^ What was the name of the original Haskell function?
525 hsArgs :: [HsValueMap HsValueUse], -- ^ How are the arguments used?
526 hsRes :: HsValueMap HsValueUse -- ^ How is the result value used?
527 } deriving (Show, Eq)
529 -- | Translate a function application to a HsFunction. i.e., which function
530 -- do you need to translate this function application.
532 Var.Var -- ^ The function to call
533 -> [CoreExpr] -- ^ The function arguments
534 -> Type -- ^ The return type
535 -> HsFunction -- ^ The needed HsFunction
537 appToHsFunction f args ty =
538 HsFunction hsname hsargs hsres
540 mkPort = \x -> Single Port
541 hsargs = map (mkHsValueMap mkPort . CoreUtils.exprType) args
542 hsres = mkHsValueMap mkPort ty
543 hsname = getOccString f
545 data VHDLSession = VHDLSession {
546 nameCount :: Int, -- A counter that can be used to generate unique names
547 funcs :: [(HsFunction, HWFunction)] -- All functions available
550 type VHDLState = State.State VHDLSession
552 -- Add the function to the session
553 addFunc :: HsFunction -> HWFunction -> VHDLState ()
554 addFunc hsfunc hwfunc = do
555 fs <- State.gets funcs -- Get the funcs element from the session
556 State.modify (\x -> x {funcs = (hsfunc, hwfunc) : fs }) -- Prepend name and f
558 -- Lookup the function with the given name in the current session. Errors if
560 getHWFunc :: HsFunction -> VHDLState HWFunction
561 getHWFunc hsfunc = do
562 fs <- State.gets funcs -- Get the funcs element from the session
563 return $ Maybe.fromMaybe
564 (error $ "Function " ++ (hsName hsfunc) ++ "is unknown? This should not happen!")
567 -- Makes the given name unique by appending a unique number.
568 -- This does not do any checking against existing names, so it only guarantees
569 -- uniqueness with other names generated by uniqueName.
570 uniqueName :: String -> VHDLState String
572 count <- State.gets nameCount -- Get the funcs element from the session
573 State.modify (\s -> s {nameCount = count + 1})
574 return $ name ++ "_" ++ (show count)
577 mkVHDLId :: String -> AST.VHDLId
578 mkVHDLId = AST.unsafeVHDLBasicId
582 (HsFunction "hwxor" [(Single Port), (Single Port)] (Single Port), HWFunction (mkVHDLId "hwxor") [Single (mkVHDLId "a", vhdl_bit_ty), Single (mkVHDLId "b", vhdl_bit_ty)] (Single (mkVHDLId "o", vhdl_bit_ty))),
583 (HsFunction "hwand" [(Single Port), (Single Port)] (Single Port), HWFunction (mkVHDLId "hwand") [Single (mkVHDLId "a", vhdl_bit_ty), Single (mkVHDLId "b", vhdl_bit_ty)] (Single (mkVHDLId "o", vhdl_bit_ty))),
584 (HsFunction "hwor" [(Single Port), (Single Port)] (Single Port), HWFunction (mkVHDLId "hwor") [Single (mkVHDLId "a", vhdl_bit_ty), Single (mkVHDLId "b", vhdl_bit_ty)] (Single (mkVHDLId "o", vhdl_bit_ty))),
585 (HsFunction "hwnot" [(Single Port)] (Single Port), HWFunction (mkVHDLId "hwnot") [Single (mkVHDLId "i", vhdl_bit_ty)] (Single (mkVHDLId "o", vhdl_bit_ty)))
588 vhdl_bit_ty :: AST.TypeMark
589 vhdl_bit_ty = AST.unsafeVHDLBasicId "Bit"
591 -- Translate a Haskell type to a VHDL type
592 vhdl_ty :: Type -> AST.TypeMark
593 vhdl_ty ty = Maybe.fromMaybe
594 (error $ "Unsupported Haskell type: " ++ (showSDoc $ ppr ty))
597 -- Translate a Haskell type to a VHDL type
598 vhdl_ty_maybe :: Type -> Maybe AST.TypeMark
600 case Type.splitTyConApp_maybe ty of
601 Just (tycon, args) ->
602 let name = TyCon.tyConName tycon in
603 -- TODO: Do something more robust than string matching
604 case getOccString name of
605 "Bit" -> Just vhdl_bit_ty
609 -- vim: set ts=8 sw=2 sts=2 expandtab: