packages feed

canontra-0.4.0.0: src/Canontra/Analysis/DFG.hs

{- |
Module      : Canontra.Analysis.DFG
Description : Data-Flow Graph (DFG) builder and reaching definitions analyzer.

This module extracts reaching definitions, Def-Use chains, and SSA-style
value flows across parameters, assignments, and expression evaluations.
-}
module Canontra.Analysis.DFG
  ( NodeId
  , DefUseKind (..)
  , DFGNode (..)
  , DFGEdge (..)
  , DataFlowGraph (..)
  , ScopeStack
  , buildDFGs
  , buildCanonicalDFGs
  , buildFunctionDFG
  , formatDFG
  , processStmts
  , processStmtsWithStack
  , extractExprUses
  , extractExprUsesStack
  , lookupStack
  , updateStack
  , pushScope
  , popScope
  , mergeBranchDefs
  , mergeMultiBranchDefs
  , collectModifiedVars
  , computeLoopPhiVars
  ) where

import Control.DeepSeq (NFData)
import Data.Aeson (FromJSON, ToJSON)
import Data.List (foldl', sortBy)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Ord (comparing)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import GHC.Generics (Generic)

import Canontra.IR.Declaration
import Canontra.IR.Expression
import Canontra.IR.Program
import Canontra.Normalize.Alpha (canonicalizeAlphaProgram)

-- | Difference list for O(1) append without quadratic list concatenation.
type DList a = [a] -> [a]

{-# INLINE dlEmpty #-}
dlEmpty :: DList a
dlEmpty = id

{-# INLINE dlSingleton #-}
dlSingleton :: a -> DList a
dlSingleton x = (x :)

{-# INLINE dlFromList #-}
dlFromList :: [a] -> DList a
dlFromList xs = (xs ++)

{-# INLINE dlAppend #-}
dlAppend :: DList a -> DList a -> DList a
dlAppend = (.)

{-# INLINE dlToList #-}
dlToList :: DList a -> [a]
dlToList dl = dl []

type NodeId = Int

data DefUseKind
  = DefParam Int          -- e.g. Parameter at index i
  | DefAssignment Text    -- e.g. Variable assigned a value
  | DefPhi [NodeId]       -- e.g. SSA phi node
  | UseRead Text          -- e.g. Variable read/evaluated
  | UseArgument Int       -- e.g. Passed into function call
  | UseBranchGuard        -- e.g. Guard in branch condition
  deriving stock (Eq, Ord, Show, Generic)
  deriving anyclass (ToJSON, FromJSON, NFData)

data DFGNode = DFGNode
  { dfgNodeId :: NodeId
  , dfgKind   :: DefUseKind
  , dfgExpr   :: Maybe Expr
  } deriving stock (Eq, Show, Generic)
  deriving anyclass (ToJSON, FromJSON, NFData)

data DFGEdge = DFGEdge
  { dfgSource  :: NodeId
  , dfgTarget  :: NodeId
  , dfgVarName :: Text
  } deriving stock (Eq, Ord, Show, Generic)
  deriving anyclass (ToJSON, FromJSON, NFData)

data DataFlowGraph = DataFlowGraph
  { dfgFunction :: Text
  , dfgNodes    :: [DFGNode]
  , dfgEdges    :: [DFGEdge]
  } deriving stock (Eq, Show, Generic)
  deriving anyclass (ToJSON, FromJSON, NFData)

-- | Build DFGs for all callable entities in a Program.
buildDFGs :: Program -> [DataFlowGraph]
buildDFGs (Program modules _) =
  concatMap extractModuleDFGs modules

-- | Build alpha-canonicalized DFGs where bound local variables are mapped to
-- canonical de Bruijn indices (@v<depth>.<ordinal>).
buildCanonicalDFGs :: Program -> [DataFlowGraph]
buildCanonicalDFGs = buildDFGs . canonicalizeAlphaProgram

extractModuleDFGs :: Module -> [DataFlowGraph]
extractModuleDFGs (Module modName _ decls stmts) =
  let topDFG = if null stmts then [] else [buildFunctionDFG ("<top-level:" <> modName <> ">") [] stmts]
      declDFGs = concatMap extractDeclDFGs decls
  in topDFG ++ declDFGs

extractDeclDFGs :: Declaration -> [DataFlowGraph]
extractDeclDFGs decl = case decl of
  DeclFunction fn ->
    [buildFunctionDFG (fnName fn) (fnParams fn) (fnBody fn)]
  DeclClass cls ->
    [buildFunctionDFG (clsName cls <> "." <> fnName m) (fnParams m) (fnBody m) | m <- clsMethods cls]
  DeclStruct st ->
    [buildFunctionDFG (stName st <> "." <> fnName m) (fnParams m) (fnBody m) | m <- stMethods st]
  DeclTrait tr ->
    [buildFunctionDFG (trName tr <> "." <> fnName m) (fnParams m) (fnBody m) | m <- trMethods tr]
  DeclImpl imp ->
    [buildFunctionDFG (impTarget imp <> "." <> fnName m) (fnParams m) (fnBody m) | m <- impMethods imp]
  DeclReceiver rc fn ->
    [buildFunctionDFG (rcTypeName rc <> "." <> fnName fn) (fnParams fn) (fnBody fn)]
  _ -> []

type ScopeStack = [Map Text NodeId]

lookupStack :: Text -> ScopeStack -> Maybe NodeId
lookupStack _ [] = Nothing
lookupStack v (s:ss) = case Map.lookup v s of
  Just nid -> Just nid
  Nothing  -> lookupStack v ss

updateStack :: Text -> NodeId -> ScopeStack -> ScopeStack
updateStack v nid [] = [Map.singleton v nid]
updateStack v nid (s:ss) = Map.insert v nid s : ss

pushScope :: ScopeStack -> ScopeStack
pushScope s = Map.empty : s

popScope :: ScopeStack -> ScopeStack
popScope (_:ss) = ss
popScope []     = []

-- | Build a DataFlowGraph for a function with parameters and body statements.
buildFunctionDFG :: Text -> [Parameter] -> [Stmt] -> DataFlowGraph
buildFunctionDFG fnName params stmts =
  let (paramNodes, initialDefs, nextId) = setupParams params 0
      (stmtNodes, stmtEdges, _, _) = processStmtsWithStack [initialDefs] stmts nextId
      allNodes = sortBy (comparing dfgNodeId) (paramNodes ++ stmtNodes)
      allEdges = sortBy (comparing (\e -> (dfgSource e, dfgTarget e, dfgVarName e))) stmtEdges
  in DataFlowGraph fnName allNodes allEdges

setupParams :: [Parameter] -> NodeId -> ([DFGNode], Map Text NodeId, NodeId)
setupParams params startId =
  let (nodesDL, defs, nextId) = foldl' step (dlEmpty, Map.empty, startId) (zip [0..] params)
  in (dlToList nodesDL, defs, nextId)
  where
    step (nodes, defs, curId) (idx, p) =
      let pName = paramName p
          node = DFGNode curId (DefParam idx) (Just (ExprId pName))
          newDefs = Map.insert pName curId defs
      in (nodes `dlAppend` dlSingleton node, newDefs, curId + 1)

processStmts :: Map Text NodeId -> [Stmt] -> NodeId -> ([DFGNode], [DFGEdge], NodeId)
processStmts activeDefs stmts startId =
  let (nodes, edges, _, nextId) = processStmtsWithStack [activeDefs] stmts startId
  in (nodes, edges, nextId)

processStmtsWithStack :: ScopeStack -> [Stmt] -> NodeId -> ([DFGNode], [DFGEdge], ScopeStack, NodeId)
processStmtsWithStack initialStack stmts startId =
  let (nodesDL, edgesDL, finalStack, nextId) = foldl' step (dlEmpty, dlEmpty, initialStack, startId) stmts
  in (dlToList nodesDL, dlToList edgesDL, finalStack, nextId)
  where
    mkDefNodes :: Maybe Expr -> NodeId -> [Text] -> ([DFGNode], NodeId)
    mkDefNodes mExpr initId vars =
      let (nsDL, endId) = foldl' (\(ns, cId) v ->
            (ns `dlAppend` dlSingleton (DFGNode cId (DefAssignment v) mExpr), cId + 1)) (dlEmpty, initId) vars
      in (dlToList nsDL, endId)

    step (nodesAcc, edgesAcc, curStack, curId) stmt = case stmt of
      StmtAssign targets val ->
        let (useNodes, useEdges, nextId1) = extractExprUsesStack curStack val curId
            assignedVars = concatMap extractTargetVars targets
            walrusVars = collectWalrusDefs val
            allDefs = assignedVars ++ walrusVars
            (defNodes, nextId2) = mkDefNodes (Just val) nextId1 allDefs
            defEdges = [ DFGEdge (dfgNodeId srcNode) (dfgNodeId targetNode) v
                       | (targetNode, v) <- zip defNodes allDefs
                       , srcNode <- useNodes
                       ]
            newStack = foldl' (\s (dNode, v) -> updateStack v (dfgNodeId dNode) s) curStack (zip defNodes allDefs)
        in ( nodesAcc `dlAppend` dlFromList useNodes `dlAppend` dlFromList defNodes
           , edgesAcc `dlAppend` dlFromList useEdges `dlAppend` dlFromList defEdges
           , newStack
           , nextId2
           )

      StmtAnnAssign target _ mVal ->
        let assignedVars = extractTargetVars target
            (useNodes, useEdges, nextId1) = maybe ([], [], curId) (\val -> extractExprUsesStack curStack val curId) mVal
            walrusVars = maybe [] collectWalrusDefs mVal
            allDefs = assignedVars ++ walrusVars
            (defNodes, nextId2) = mkDefNodes mVal nextId1 allDefs
            defEdges = [ DFGEdge (dfgNodeId srcNode) (dfgNodeId targetNode) v
                       | (targetNode, v) <- zip defNodes allDefs
                       , srcNode <- useNodes
                       ]
            newStack = foldl' (\s (dNode, v) -> updateStack v (dfgNodeId dNode) s) curStack (zip defNodes allDefs)
        in ( nodesAcc `dlAppend` dlFromList useNodes `dlAppend` dlFromList defNodes
           , edgesAcc `dlAppend` dlFromList useEdges `dlAppend` dlFromList defEdges
           , newStack
           , nextId2
           )

      StmtAugAssign target op val ->
        let combinedExpr = ExprBinary op target val
            (useNodes, useEdges, nextId1) = extractExprUsesStack curStack combinedExpr curId
            assignedVars = extractTargetVars target
            walrusVars = collectWalrusDefs val
            allDefs = assignedVars ++ walrusVars
            (defNodes, nextId2) = mkDefNodes (Just combinedExpr) nextId1 allDefs
            defEdges = [ DFGEdge (dfgNodeId srcNode) (dfgNodeId targetNode) v
                       | (targetNode, v) <- zip defNodes allDefs
                       , srcNode <- useNodes
                       ]
            newStack = foldl' (\s (dNode, v) -> updateStack v (dfgNodeId dNode) s) curStack (zip defNodes allDefs)
        in ( nodesAcc `dlAppend` dlFromList useNodes `dlAppend` dlFromList defNodes
           , edgesAcc `dlAppend` dlFromList useEdges `dlAppend` dlFromList defEdges
           , newStack
           , nextId2
           )

      StmtReturn mVal ->
        let (useNodes, useEdges, nextId1) = maybe ([], [], curId) (\val -> extractExprUsesStack curStack val curId) mVal
        in (nodesAcc `dlAppend` dlFromList useNodes, edgesAcc `dlAppend` dlFromList useEdges, curStack, nextId1)

      StmtIf cond thenB elseB ->
        let (cNodes, cEdges, nextId1) = extractExprUsesStack curStack cond curId
            walrusVars = collectWalrusDefs cond
            (wNodes, nextId1_w) = mkDefNodes (Just cond) nextId1 walrusVars
            condStack = foldl' (\s (dNode, v) -> updateStack v (dfgNodeId dNode) s) curStack (zip wNodes walrusVars)
            (tNodes, tEdges, thenStack, nextId2) = processStmtsWithStack condStack thenB nextId1_w
            (eNodes, eEdges, elseStack, nextId3) = processStmtsWithStack condStack elseB nextId2
            (phiNodes, phiEdges, mergedStack, nextId4) = mergeBranchDefs condStack thenStack elseStack nextId3
        in ( nodesAcc `dlAppend` dlFromList cNodes `dlAppend` dlFromList wNodes `dlAppend` dlFromList tNodes `dlAppend` dlFromList eNodes `dlAppend` dlFromList phiNodes
           , edgesAcc `dlAppend` dlFromList cEdges `dlAppend` dlFromList tEdges `dlAppend` dlFromList eEdges `dlAppend` dlFromList phiEdges
           , mergedStack
           , nextId4
           )

      StmtWhile cond body elseB ->
        let loopModVars = collectModifiedVars body
            (phiHeaders, headerStack, nextId1) = allocLoopHeaderPhis curStack loopModVars Set.empty curId
            (cNodes, cEdges, nextId2) = extractExprUsesStack headerStack cond nextId1
            walrusVars = collectWalrusDefs cond
            (wNodes, nextId2_w) = mkDefNodes (Just cond) nextId2 walrusVars
            condStack = foldl' (\s (dNode, v) -> updateStack v (dfgNodeId dNode) s) headerStack (zip wNodes walrusVars)
            (bNodes, bEdges, bodyStack, nextId3) = processStmtsWithStack condStack body nextId2_w
            (finalPhiNodes, finalPhiEdges) = finalizeLoopHeaderPhis phiHeaders bodyStack
            (eNodes, eEdges, elseStack, nextId4) = processStmtsWithStack headerStack elseB nextId3
            (postPhiNodes, postPhiEdges, mergedStack, nextId5) =
              if null elseB
                then ([], [], headerStack, nextId4)
                else mergeBranchDefs headerStack headerStack elseStack nextId4
        in ( nodesAcc `dlAppend` dlFromList finalPhiNodes `dlAppend` dlFromList cNodes `dlAppend` dlFromList wNodes `dlAppend` dlFromList bNodes `dlAppend` dlFromList eNodes `dlAppend` dlFromList postPhiNodes
           , edgesAcc `dlAppend` dlFromList finalPhiEdges `dlAppend` dlFromList cEdges `dlAppend` dlFromList bEdges `dlAppend` dlFromList eEdges `dlAppend` dlFromList postPhiEdges
           , mergedStack
           , nextId5
           )

      StmtFor target iter body elseB ->
        analyzeLoopFor target iter body elseB nodesAcc edgesAcc curStack curId

      StmtAsyncFor target iter body elseB ->
        analyzeLoopFor target iter body elseB nodesAcc edgesAcc curStack curId

      StmtLoop body ->
        let loopModVars = collectModifiedVars body
            (phiHeaders, headerStack, nextId1) = allocLoopHeaderPhis curStack loopModVars Set.empty curId
            (bNodes, bEdges, bodyStack, nextId2) = processStmtsWithStack headerStack body nextId1
            (finalPhiNodes, finalPhiEdges) = finalizeLoopHeaderPhis phiHeaders bodyStack
        in ( nodesAcc `dlAppend` dlFromList finalPhiNodes `dlAppend` dlFromList bNodes
           , edgesAcc `dlAppend` dlFromList finalPhiEdges `dlAppend` dlFromList bEdges
           , headerStack
           , nextId2
           )

      StmtTry tryB handlers elseB finB ->
        let (tNodes, tEdges, tryStack, nextId1) = processStmtsWithStack curStack tryB curId
            (hNodesDL, hEdgesDL, hStacksDL, nextId2) = foldl' stepHandler (dlEmpty, dlEmpty, dlEmpty, nextId1) handlers
            (eNodes, eEdges, elseStack, nextId3) = processStmtsWithStack tryStack elseB nextId2
            branchStacks = (if null elseB then tryStack else elseStack) : dlToList hStacksDL
            (phiNodes, phiEdges, mergedStack, nextId4) = mergeMultiBranchDefs curStack branchStacks nextId3
            (fNodes, fEdges, finStack, nextId5) = processStmtsWithStack mergedStack finB nextId4
        in ( nodesAcc `dlAppend` dlFromList tNodes `dlAppend` hNodesDL `dlAppend` dlFromList eNodes `dlAppend` dlFromList phiNodes `dlAppend` dlFromList fNodes
           , edgesAcc `dlAppend` dlFromList tEdges `dlAppend` hEdgesDL `dlAppend` dlFromList eEdges `dlAppend` dlFromList phiEdges `dlAppend` dlFromList fEdges
           , finStack
           , nextId5
           )
        where
          stepHandler (nsAcc, esAcc, stAcc, cId) (_, mExcName, hStmts) =
            let excStack = case mExcName of
                  Just name -> updateStack name cId curStack
                  Nothing   -> curStack
                excNode = [DFGNode cId (DefAssignment name) Nothing | Just name <- [mExcName]]
                cId1 = if null excNode then cId else cId + 1
                (hN, hE, hS, cId2) = processStmtsWithStack excStack hStmts cId1
            in (nsAcc `dlAppend` dlFromList excNode `dlAppend` dlFromList hN, esAcc `dlAppend` dlFromList hE, stAcc `dlAppend` dlSingleton hS, cId2)

      StmtSwitch expr cases defaultStmts ->
        let (eNodes, eEdges, nextId1) = extractExprUsesStack curStack expr curId
            (cNodesDL, cEdgesDL, caseStacksDL, nextId2) = foldl' stepCase (dlEmpty, dlEmpty, dlEmpty, nextId1) cases
            (defNodes, defEdges, defStack, nextId3) = processStmtsWithStack curStack defaultStmts nextId2
            allBranchStacks = defStack : dlToList caseStacksDL
            (phiNodes, phiEdges, mergedStack, nextId4) = mergeMultiBranchDefs curStack allBranchStacks nextId3
        in ( nodesAcc `dlAppend` dlFromList eNodes `dlAppend` cNodesDL `dlAppend` dlFromList defNodes `dlAppend` dlFromList phiNodes
           , edgesAcc `dlAppend` dlFromList eEdges `dlAppend` cEdgesDL `dlAppend` dlFromList defEdges `dlAppend` dlFromList phiEdges
           , mergedStack
           , nextId4
           )
        where
          stepCase (nsAcc, esAcc, stAcc, cId) (_, cStmts) =
            let (cN, cE, cS, nId) = processStmtsWithStack curStack cStmts cId
            in (nsAcc `dlAppend` dlFromList cN, esAcc `dlAppend` dlFromList cE, stAcc `dlAppend` dlSingleton cS, nId)

      StmtMatch expr cases ->
        let (eNodes, eEdges, nextId1) = extractExprUsesStack curStack expr curId
            (cNodesDL, cEdgesDL, caseStacksDL, nextId2) = foldl' stepCase (dlEmpty, dlEmpty, dlEmpty, nextId1) cases
            (phiNodes, phiEdges, mergedStack, nextId3) = mergeMultiBranchDefs curStack (dlToList caseStacksDL) nextId2
        in ( nodesAcc `dlAppend` dlFromList eNodes `dlAppend` cNodesDL `dlAppend` dlFromList phiNodes
           , edgesAcc `dlAppend` dlFromList eEdges `dlAppend` cEdgesDL `dlAppend` dlFromList phiEdges
           , mergedStack
           , nextId3
           )
        where
          stepCase (nsAcc, esAcc, stAcc, cId) mc =
            let (cN, cE, cS, nId) = processStmtsWithStack curStack (mcBody mc) cId
            in (nsAcc `dlAppend` dlFromList cN, esAcc `dlAppend` dlFromList cE, stAcc `dlAppend` dlSingleton cS, nId)

      StmtExpr e ->
        let (useNodes, useEdges, nextId1) = extractExprUsesStack curStack e curId
            walrusVars = collectWalrusDefs e
            (defNodes, nextId2) = mkDefNodes (Just e) nextId1 walrusVars
            walrusEdges = [ DFGEdge (dfgNodeId srcNode) (dfgNodeId targetNode) v
                          | (targetNode, v) <- zip defNodes walrusVars
                          , srcNode <- useNodes
                          ]
            newStack = foldl' (\s (dNode, v) -> updateStack v (dfgNodeId dNode) s) curStack (zip defNodes walrusVars)
        in ( nodesAcc `dlAppend` dlFromList useNodes `dlAppend` dlFromList defNodes
           , edgesAcc `dlAppend` dlFromList useEdges `dlAppend` dlFromList walrusEdges
           , newStack
           , nextId2
           )

      _ -> (nodesAcc, edgesAcc, curStack, curId)

    analyzeLoopFor target iter body elseB nodesAcc edgesAcc curStack curId =
      let (iNodes, iEdges, nextId1) = extractExprUsesStack curStack iter curId
          vars = extractTargetVars target
          loopModVars = collectModifiedVars body
          (phiHeaders, headerStack, nextId2) = allocLoopHeaderPhis curStack loopModVars (Set.fromList vars) nextId1
          (defNodes, nextId3) = mkDefNodes (Just iter) nextId2 vars
          targetStack = foldl' (\s (dNode, v) -> updateStack v (dfgNodeId dNode) s) headerStack (zip defNodes vars)
          (bNodes, bEdges, bodyStack, nextId4) = processStmtsWithStack targetStack body nextId3
          (finalPhiNodes, finalPhiEdges) = finalizeLoopHeaderPhis phiHeaders bodyStack
          (eNodes, eEdges, elseStack, nextId5) = processStmtsWithStack headerStack elseB nextId4
          (postPhiNodes, postPhiEdges, mergedStack, nextId6) =
            if null elseB
              then ([], [], targetStack, nextId5)
              else mergeBranchDefs targetStack targetStack elseStack nextId5
      in ( nodesAcc `dlAppend` dlFromList iNodes `dlAppend` dlFromList finalPhiNodes `dlAppend` dlFromList defNodes `dlAppend` dlFromList bNodes `dlAppend` dlFromList eNodes `dlAppend` dlFromList postPhiNodes
         , edgesAcc `dlAppend` dlFromList iEdges `dlAppend` dlFromList finalPhiEdges `dlAppend` dlFromList bEdges `dlAppend` dlFromList eEdges `dlAppend` dlFromList postPhiEdges
         , mergedStack
         , nextId6
         )

extractTargetVars :: Expr -> [Text]
extractTargetVars = \case
  ExprId v        -> [v]
  ExprTuple es    -> concatMap extractTargetVars es
  ExprList es     -> concatMap extractTargetVars es
  ExprStarred e   -> extractTargetVars e
  ExprWalrus v _  -> [v]
  _               -> []

mergeBranchDefs :: ScopeStack -> ScopeStack -> ScopeStack -> NodeId -> ([DFGNode], [DFGEdge], ScopeStack, NodeId)
mergeBranchDefs inStack thenStack elseStack startId =
  mergeMultiBranchDefs inStack [thenStack, elseStack] startId

mergeMultiBranchDefs :: ScopeStack -> [ScopeStack] -> NodeId -> ([DFGNode], [DFGEdge], ScopeStack, NodeId)
mergeMultiBranchDefs inStack branchStacks startId =
  let allVars = Set.toList (Set.unions (map Map.keysSet branchTops))
      diffVars = filter isDiff allVars
      (phiNodesDL, phiEdgesDL, newDefs, nextId) = foldl' step (dlEmpty, dlEmpty, inTop, startId) diffVars
      finalStack = case inStack of
        (_:rest) -> newDefs : rest
        []       -> [newDefs]
  in (dlToList phiNodesDL, dlToList phiEdgesDL, finalStack, nextId)
  where
    inTop = case inStack of (s:_) -> s; [] -> Map.empty
    branchTops = [case s of (t:_) -> t; [] -> Map.empty | s <- branchStacks]

    isDiff v =
      let defs = [Map.lookup v t | t <- branchTops]
          firstDef = case defs of (d:_) -> d; [] -> Nothing
      in any (/= firstDef) defs || any (/= Map.lookup v inTop) defs

    step (nsAcc, esAcc, defsAcc, cId) v =
      let incomingDefs = Set.toList $ Set.fromList
            [ nid
            | t <- branchTops
            , let mDef = case Map.lookup v t of
                           Just d  -> Just d
                           Nothing -> Map.lookup v inTop
            , Just nid <- [mDef]
            ]
      in if length incomingDefs < 2 && all (== Map.lookup v inTop) (map Just incomingDefs)
         then (nsAcc, esAcc, defsAcc, cId)
         else
           let phiNode = DFGNode cId (DefPhi incomingDefs) (Just (ExprId v))
               phiEdges = [DFGEdge src cId v | src <- incomingDefs]
               newDefsAcc = Map.insert v cId defsAcc
           in (nsAcc `dlAppend` dlSingleton phiNode, esAcc `dlAppend` dlFromList phiEdges, newDefsAcc, cId + 1)

-- | Collect variables modified anywhere inside a statement list (dominance-frontier
-- iterated phi candidates for loop headers).
collectModifiedVars :: [Stmt] -> Set Text
collectModifiedVars = foldl' (\acc s -> Set.union acc (stmtDefs s)) Set.empty
  where
    stmtDefs = \case
      StmtAssign targets val ->
        Set.fromList (concatMap extractTargetVars targets ++ collectWalrusDefs val)
      StmtAnnAssign target _ mVal ->
        Set.fromList (extractTargetVars target ++ maybe [] collectWalrusDefs mVal)
      StmtAugAssign target _ val ->
        Set.fromList (extractTargetVars target ++ collectWalrusDefs val)
      StmtExpr e ->
        Set.fromList (collectWalrusDefs e)
      StmtIf c t e ->
        Set.unions [Set.fromList (collectWalrusDefs c), collectModifiedVars t, collectModifiedVars e]
      StmtWhile c b e ->
        Set.unions [Set.fromList (collectWalrusDefs c), collectModifiedVars b, collectModifiedVars e]
      StmtFor t _ b e ->
        Set.unions [Set.fromList (extractTargetVars t), collectModifiedVars b, collectModifiedVars e]
      StmtAsyncFor t _ b e ->
        Set.unions [Set.fromList (extractTargetVars t), collectModifiedVars b, collectModifiedVars e]
      StmtTry b hs e f ->
        Set.unions (collectModifiedVars b : collectModifiedVars e : collectModifiedVars f : [collectModifiedVars hb | (_, _, hb) <- hs])
      StmtWith items b ->
        Set.union (Set.fromList [v | (_, Just tgt) <- items, v <- extractTargetVars tgt]) (collectModifiedVars b)
      StmtAsyncWith items b ->
        Set.union (Set.fromList [v | (_, Just tgt) <- items, v <- extractTargetVars tgt]) (collectModifiedVars b)
      StmtSwitch _ cs d ->
        Set.union (foldMap (collectModifiedVars . snd) cs) (collectModifiedVars d)
      StmtMatch _ cs ->
        foldMap (collectModifiedVars . mcBody) cs
      StmtLoop b ->
        collectModifiedVars b
      _ -> Set.empty

-- | Compute the ordered list of loop-carried variables requiring SSA phi placement
-- at a loop header, given the pre-loop scope and loop body statements.
computeLoopPhiVars :: ScopeStack -> [Stmt] -> Set Text -> [(Text, NodeId)]
computeLoopPhiVars stack body excludeSet =
  let modVars = Set.difference (collectModifiedVars body) excludeSet
  in [ (v, preId)
     | v <- Set.toAscList modVars
     , Just preId <- [lookupStack v stack]
     ]

allocLoopHeaderPhis
  :: ScopeStack
  -> Set Text
  -> Set Text
  -> NodeId
  -> ([(Text, NodeId, NodeId)], ScopeStack, NodeId)
allocLoopHeaderPhis stack modVars excludeSet startId =
  let candidates = Set.toAscList (Set.difference modVars excludeSet)
      step (acc, sAcc, cId) v = case lookupStack v stack of
        Just preId ->
          ((v, preId, cId) : acc, updateStack v cId sAcc, cId + 1)
        Nothing ->
          (acc, sAcc, cId)
      (revHeaders, headerStack, nextId) = foldl' step ([], stack, startId) candidates
  in (reverse revHeaders, headerStack, nextId)

finalizeLoopHeaderPhis
  :: [(Text, NodeId, NodeId)]
  -> ScopeStack
  -> ([DFGNode], [DFGEdge])
finalizeLoopHeaderPhis headers bodyStack =
  let step (nsAcc, esAcc) (v, preId, phiId) =
        let mBodyId = lookupStack v bodyStack
            incoming = case mBodyId of
              Just bId | bId /= phiId -> [preId, bId]
              _                       -> [preId]
            node = DFGNode phiId (DefPhi incoming) (Just (ExprId v))
            edges =
              DFGEdge preId phiId v
                : [DFGEdge bId phiId v | Just bId <- [mBodyId], bId /= phiId]
        in (nsAcc `dlAppend` dlSingleton node, esAcc `dlAppend` dlFromList edges)
      (nsDL, esDL) = foldl' step (dlEmpty, dlEmpty) headers
  in (dlToList nsDL, dlToList esDL)

extractExprUses :: Map Text NodeId -> Expr -> NodeId -> ([DFGNode], [DFGEdge], NodeId)
extractExprUses activeDefs expr startId = extractExprUsesStack [activeDefs] expr startId

extractExprUsesStack :: ScopeStack -> Expr -> NodeId -> ([DFGNode], [DFGEdge], NodeId)
extractExprUsesStack stack expr startId =
  let readVars = collectVarReads expr
      (nodesDL, edgesDL, nextId) = foldl' step (dlEmpty, dlEmpty, startId) (Set.toList readVars)
  in (dlToList nodesDL, dlToList edgesDL, nextId)
  where
    step (ns, es, curId) v =
      let useNode = DFGNode curId (UseRead v) (Just expr)
          edges' = case lookupStack v stack of
            Just defNodeId -> dlSingleton (DFGEdge defNodeId curId v)
            Nothing        -> dlEmpty
      in (ns `dlAppend` dlSingleton useNode, es `dlAppend` edges', curId + 1)

collectWalrusDefs :: Expr -> [Text]
collectWalrusDefs = \case
  ExprWalrus v e          -> v : collectWalrusDefs e
  ExprBinary _ e1 e2      -> collectWalrusDefs e1 ++ collectWalrusDefs e2
  ExprUnary _ e           -> collectWalrusDefs e
  ExprCall f args kw      -> collectWalrusDefs f ++ concatMap collectWalrusDefs args ++ concatMap (collectWalrusDefs . snd) kw
  ExprList es             -> concatMap collectWalrusDefs es
  ExprTuple es            -> concatMap collectWalrusDefs es
  ExprTernary c t f       -> collectWalrusDefs c ++ collectWalrusDefs t ++ collectWalrusDefs f
  ExprListComp item comps -> collectWalrusDefs item ++ concatMap compWalrus comps
  ExprDictComp k v comps  -> collectWalrusDefs k ++ collectWalrusDefs v ++ concatMap compWalrus comps
  ExprSetComp item comps  -> collectWalrusDefs item ++ concatMap compWalrus comps
  ExprGenerator item comps-> collectWalrusDefs item ++ concatMap compWalrus comps
  _                       -> []
  where
    compWalrus (CompFor _ iter ifs) = collectWalrusDefs iter ++ concatMap collectWalrusDefs ifs

collectVarReads :: Expr -> Set Text
collectVarReads = \case
  ExprId v           -> Set.singleton v
  ExprBinary _ e1 e2 -> Set.union (collectVarReads e1) (collectVarReads e2)
  ExprUnary _ e      -> collectVarReads e
  ExprCall t args kw -> Set.unions (collectVarReads t : map collectVarReads args ++ map (collectVarReads . snd) kw)
  ExprAttr e _       -> collectVarReads e
  ExprSubscript e idx-> Set.union (collectVarReads e) (collectVarReads idx)
  ExprTernary c t f  -> Set.unions [collectVarReads c, collectVarReads t, collectVarReads f]
  ExprList es        -> foldMap collectVarReads es
  ExprTuple es       -> foldMap collectVarReads es
  ExprDict pairs     -> foldMap (\(k, v) -> Set.union (collectVarReads k) (collectVarReads v)) pairs
  ExprSet es         -> foldMap collectVarReads es
  _                  -> Set.empty

formatDFG :: DataFlowGraph -> Text
formatDFG dfg =
  T.unlines $
    [ "DFG: " <> dfgFunction dfg <> " (Nodes: " <> T.pack (show (length (dfgNodes dfg))) <> ", Edges: " <> T.pack (show (length (dfgEdges dfg))) <> ")"
    , "---------------------------------------------------------"
    ] ++
    map formatNode (dfgNodes dfg) ++
    [ "Edges:" ] ++
    map formatEdge (dfgEdges dfg)
  where
    formatNode n =
      "  [Node " <> T.pack (show (dfgNodeId n)) <> "] " <> formatKind (dfgKind n)

    formatKind = \case
      DefParam idx      -> "DefParam (" <> T.pack (show idx) <> ")"
      DefAssignment v   -> "DefAssignment (" <> v <> ")"
      DefPhi _          -> "DefPhi"
      UseRead v         -> "UseRead (" <> v <> ")"
      UseArgument idx   -> "UseArgument (" <> T.pack (show idx) <> ")"
      UseBranchGuard    -> "UseBranchGuard"

    formatEdge e =
      "    " <> T.pack (show (dfgSource e)) <> " ---> " <> T.pack (show (dfgTarget e)) <> " (var: " <> dfgVarName e <> ")"