Midstream changes for performance improvement related to superclasses and functional...
[ghc-hetmet.git] / compiler / typecheck / TcInteract.lhs
index 807dd61..e7b03d1 100644 (file)
@@ -1,8 +1,7 @@
 \begin{code}
 module TcInteract ( 
      solveInteract, AtomicInert, 
-     InertSet, emptyInert, updInertSet, extractUnsolved, solveOne,
-     listToWorkList
+     InertSet, emptyInert, updInertSet, extractUnsolved, solveOne 
   ) where  
 
 #include "HsVersions.h"
@@ -15,6 +14,7 @@ import Type
 import TypeRep 
 
 import Id 
+import VarEnv
 import Var
 
 import TcType
@@ -35,7 +35,7 @@ import Outputable
 import TcRnTypes 
 import TcErrors
 import TcSMonad 
-import qualified Bag as Bag
+import Bag
 import qualified Data.Map as Map 
 import Maybes 
 
@@ -110,46 +110,60 @@ solving. See Note [Loopy Spontaneous Solving]
 
 -- See Note [InertSet invariants]
 data InertSet 
-  = IS { inert_cts  :: Bag.Bag CanonicalCt 
+  = IS { inert_eqs  :: Bag.Bag CanonicalCt  -- Equalities only (CTyEqCan,CFunEqCan)
+       , inert_cts  :: Bag.Bag CanonicalCt  -- Other constraints 
        , inert_fsks :: Map.Map TcTyVar [(TcTyVar,Coercion)] }
        -- See Note [InertSet FlattenSkolemEqClass] 
 
 instance Outputable InertSet where
-  ppr is = vcat [ vcat (map ppr (Bag.bagToList $ inert_cts is))
+  ppr is = vcat [ vcat (map ppr (Bag.bagToList $ inert_eqs is))
+                , vcat (map ppr (Bag.bagToList $ inert_cts is))
                 , vcat (map (\(v,rest) -> ppr v <+> text "|->" <+> hsep (map (ppr.fst) rest)) 
                        (Map.toList $ inert_fsks is)
                        )
                 ]
                        
 emptyInert :: InertSet
-emptyInert = IS { inert_cts = Bag.emptyBag, inert_fsks = Map.empty } 
+emptyInert = IS { inert_eqs = Bag.emptyBag
+                , inert_cts = Bag.emptyBag, inert_fsks = Map.empty } 
 
 updInertSet :: InertSet -> AtomicInert -> InertSet 
 -- Introduces an element in the inert set for the first time 
-updInertSet (IS { inert_cts = cts, inert_fsks = fsks })  
+updInertSet (IS { inert_eqs = eqs, inert_cts = cts, inert_fsks = fsks })  
             item@(CTyEqCan { cc_id    = cv
                            , cc_tyvar = tv1 
                            , cc_rhs   = xi })
   | Just tv2 <- tcGetTyVar_maybe xi,
     FlatSkol {} <- tcTyVarDetails tv1, 
     FlatSkol {} <- tcTyVarDetails tv2 
-  = let cts'  = cts `Bag.snocBag` item 
+  = let eqs'  = eqs `Bag.snocBag` item 
         fsks' = Map.insertWith (++) tv2 [(tv1, mkCoVarCoercion cv)] fsks
         -- See Note [InertSet FlattenSkolemEqClass] 
-    in IS { inert_cts = cts', inert_fsks = fsks' }
-updInertSet (IS { inert_cts = cts
+    in IS { inert_eqs = eqs', inert_cts = cts, inert_fsks = fsks' }
+updInertSet (IS { inert_eqs = eqs, inert_cts = cts
                 , inert_fsks = fsks }) item 
+  | isEqCCan item 
+  = let eqs' = eqs `Bag.snocBag` item 
+    in IS { inert_eqs = eqs', inert_cts = cts, inert_fsks = fsks } 
+  | otherwise 
   = let cts' = cts `Bag.snocBag` item
-    in IS { inert_cts = cts', inert_fsks = fsks } 
+    in IS { inert_eqs = eqs, inert_cts = cts', inert_fsks = fsks } 
 
 foldlInertSetM :: (Monad m) => (a -> AtomicInert -> m a) -> a -> InertSet -> m a 
-foldlInertSetM k z (IS { inert_cts = cts }) 
-  = Bag.foldlBagM k z cts
+-- Prioritize over the equalities see Note [Prioritizing Equalities]
+foldlInertSetM k z (IS { inert_eqs = eqs, inert_cts = cts }) 
+  = do { z' <- Bag.foldlBagM k z eqs
+       ; Bag.foldlBagM k z' cts } 
 
 extractUnsolved :: InertSet -> (InertSet, CanonicalCts)
-extractUnsolved is@(IS {inert_cts = cts}) 
-  = (is { inert_cts = cts'}, unsolved)
-  where (unsolved, cts') = Bag.partitionBag isWantedCt cts
+extractUnsolved is@(IS {inert_eqs = eqs, inert_cts = cts}) 
+  = let is_init  = is { inert_eqs = emptyCCan 
+                      , inert_cts = solved_cts, inert_fsks = Map.empty }
+        is_final = Bag.foldlBag updInertSet is_init solved_eqs -- Add equalities carefully
+    in (is_final, unsolved) 
+  where (unsolved_cts, solved_cts) = Bag.partitionBag isWantedCt cts
+        (unsolved_eqs, solved_eqs) = Bag.partitionBag isWantedCt eqs
+        unsolved                   = unsolved_cts `unionBags` unsolved_eqs
 
 
 getFskEqClass :: InertSet -> TcTyVar -> [(TcTyVar,Coercion)] 
@@ -246,27 +260,49 @@ Note [Basic plan]
 type AtomicInert = CanonicalCt     -- constraint pulled from InertSet
 type WorkItem    = CanonicalCt     -- constraint pulled from WorkList
 
-type WorkList    = CanonicalCts    -- A mixture of Given, Wanted, and Solved
-type SWorkList   = WorkList        -- A worklist of solved 
-                   
-
-listToWorkList :: [WorkItem] -> WorkList
-listToWorkList = Bag.listToBag
+-- A mixture of Given, Wanted, and Derived constraints. 
+-- We split between equalities and the rest to process equalities first. 
+data WorkList    = WL { wl_eqs   :: CanonicalCts -- Equalities (CTyEqCan, CFunEqCan) 
+                      , wl_other :: CanonicalCts   -- Other 
+                      }
+type SWorkList         = WorkList        -- A worklist of solved 
 
 unionWorkLists :: WorkList -> WorkList -> WorkList 
-unionWorkLists = Bag.unionBags 
+unionWorkLists wl1 wl2 
+  = WL { wl_eqs   = andCCan (wl_eqs wl1) (wl_eqs wl2)
+       , wl_other = andCCan (wl_other wl1) (wl_other wl2) }
 
 foldlWorkListM :: (Monad m) => (a -> WorkItem -> m a) -> a -> WorkList -> m a 
-foldlWorkListM = Bag.foldlBagM 
+-- This fold prioritizes equalities 
+foldlWorkListM f r wl 
+  = do { r' <- Bag.foldlBagM f r (wl_eqs wl) 
+       ; Bag.foldlBagM f r' (wl_other wl) }
 
 isEmptyWorkList :: WorkList -> Bool 
-isEmptyWorkList = Bag.isEmptyBag
+isEmptyWorkList wl = isEmptyCCan (wl_eqs wl) && isEmptyCCan (wl_other wl) 
 
 emptyWorkList :: WorkList
-emptyWorkList = Bag.emptyBag
+emptyWorkList = WL { wl_eqs = emptyCCan, wl_other = emptyCCan } 
+
+mkEqWorkList :: CanonicalCts -> WorkList
+-- Precondition: *ALL* equalities
+mkEqWorkList eqs = WL { wl_eqs = eqs, wl_other = emptyCCan } 
+
+mkNonEqWorkList :: CanonicalCts -> WorkList 
+-- Precondition: *NO* equalities 
+mkNonEqWorkList cts = WL { wl_eqs = emptyCCan, wl_other = cts } 
+
+workListFromCCans :: CanonicalCts -> WorkList 
+-- Generic, no precondition 
+workListFromCCans cts = WL eqs others 
+  where (eqs, others) = Bag.partitionBag isEqCCan cts
+
+-- Convenience 
+singleEqWL    :: CanonicalCt -> WorkList 
+singleNonEqWL :: CanonicalCt -> WorkList 
+singleEqWL    = mkEqWorkList . singleCCan 
+singleNonEqWL = mkNonEqWorkList . singleCCan 
 
-singletonWorkList :: CanonicalCt -> WorkList 
-singletonWorkList ct = singleCCan ct 
 
 data StopOrContinue 
   = Stop                       -- Work item is consumed
@@ -295,6 +331,9 @@ instance Outputable StageResult where
                  , ptext (sLit "new work =") <+> ppr work <> comma
                  , ptext (sLit "stop =") <+> ppr stop])
 
+instance Outputable WorkList where 
+  ppr (WL eqcts othercts) = vcat [ppr eqcts, ppr othercts] 
+
 type SimplifierStage = WorkItem -> InertSet -> TcS StageResult 
 
 -- Combine a sequence of simplifier 'stages' to create a pipeline 
@@ -361,10 +400,11 @@ React with (F Int ~ b) ==> IR Stop True []    -- after substituting we re-canoni
 -- returning an extended inert set.
 --
 -- See Note [Touchables and givens].
-solveInteract :: InertSet -> WorkList -> TcS InertSet
+solveInteract :: InertSet -> CanonicalCts -> TcS InertSet
 solveInteract inert ws 
   = do { dyn_flags <- getDynFlags
-       ; solveInteractWithDepth (ctxtStkDepth dyn_flags,0,[]) inert ws 
+       ; let worklist = workListFromCCans ws 
+       ; solveInteractWithDepth (ctxtStkDepth dyn_flags,0,[]) inert worklist
        }
 solveOne :: InertSet -> WorkItem -> TcS InertSet 
 solveOne inerts workItem 
@@ -425,17 +465,17 @@ thePipeline = [ ("interact with inerts", interactWithInertsStage)
 \begin{code}
 spontaneousSolveStage :: SimplifierStage 
 spontaneousSolveStage workItem inerts 
-  = do { mSolve <- trySpontaneousSolve workItem inerts 
+  = do { mSolve <- trySpontaneousSolve workItem inerts
        ; case mSolve of 
            Nothing -> -- no spontaneous solution for him, keep going
-               return $ SR { sr_new_work   = emptyWorkList 
-                           , sr_inerts     = inerts 
+               return $ SR { sr_new_work   = emptyWorkList
+                           , sr_inerts     = inerts
                            , sr_stop       = ContinueWith workItem }
 
-           Just workList' -> -- He has been solved; workList' are all givens 
+           Just workList' -> -- He has been solved; workList' are all givens
                return $ SR { sr_new_work = workList'
                            , sr_inerts   = inerts 
-                           , sr_stop     = Stop } 
+                           , sr_stop     = Stop }
        }
 
 {-- This is all old code, but does not quite work now. The problem is that due to 
@@ -478,17 +518,18 @@ spontaneousSolveStage workItem inerts
 --   * Nothing if we were not able to solve it
 --   * Just wi' if we solved it, wi' (now a "given") should be put in the work list.
 --                 See Note [Touchables and givens] 
--- Note, just passing the inerts through for the skolem equivalence classes
+-- NB: just passing the inerts through for the skolem equivalence classes
 trySpontaneousSolve :: WorkItem -> InertSet -> TcS (Maybe SWorkList)
 trySpontaneousSolve (CTyEqCan { cc_id = cv, cc_flavor = gw, cc_tyvar = tv1, cc_rhs = xi }) inerts 
+  | isGiven gw
+  = return Nothing
   | Just tv2 <- tcGetTyVar_maybe xi
   = do { tch1 <- isTouchableMetaTyVar tv1
        ; tch2 <- isTouchableMetaTyVar tv2
        ; case (tch1, tch2) of
            (True,  True)  -> trySpontaneousEqTwoWay inerts cv gw tv1 tv2
            (True,  False) -> trySpontaneousEqOneWay inerts cv gw tv1 xi
-           (False, True)  | tyVarKind tv1 `isSubKind` tyVarKind tv2
-                          -> trySpontaneousEqOneWay inerts cv gw tv2 (mkTyVarTy tv1)
+           (False, True)  -> trySpontaneousEqOneWay inerts cv gw tv2 (mkTyVarTy tv1)
           _ -> return Nothing }
   | otherwise
   = do { tch1 <- isTouchableMetaTyVar tv1
@@ -504,9 +545,9 @@ trySpontaneousSolve _ _ = return Nothing
 trySpontaneousEqOneWay :: InertSet -> CoVar -> CtFlavor -> TcTyVar -> Xi
                        -> TcS (Maybe SWorkList)
 -- tv is a MetaTyVar, not untouchable
--- Precondition: kind(xi) is a sub-kind of kind(tv)
 trySpontaneousEqOneWay inerts cv gw tv xi      
-  | not (isSigTyVar tv) || isTyVarTy xi
+  | not (isSigTyVar tv) || isTyVarTy xi, 
+    typeKind xi `isSubKind` tyVarKind tv 
   = solveWithIdentity inerts cv gw tv xi
   | otherwise
   = return Nothing
@@ -517,16 +558,45 @@ trySpontaneousEqTwoWay :: InertSet -> CoVar -> CtFlavor -> TcTyVar -> TcTyVar
 -- Both tyvars are *touchable* MetaTyvars
 -- By the CTyEqCan invariant, k2 `isSubKind` k1
 trySpontaneousEqTwoWay inerts cv gw tv1 tv2
-  | k1 `eqKind` k2
+  | k1 `isSubKind` k2
   , nicer_to_update_tv2 = solveWithIdentity inerts cv gw tv2 (mkTyVarTy tv1)
-  | otherwise           = ASSERT( k2 `isSubKind` k1 )
-                          solveWithIdentity inerts cv gw tv1 (mkTyVarTy tv2)
+  | k2 `isSubKind` k1 
+  = solveWithIdentity inerts cv gw tv1 (mkTyVarTy tv2) 
+  | otherwise = return Nothing 
   where
     k1 = tyVarKind tv1
     k2 = tyVarKind tv2
     nicer_to_update_tv2 = isSigTyVar tv1 || isSystemName (Var.varName tv2)
 \end{code}
 
+
+Note [Spontaneous solving and kind compatibility] 
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Note that our canonical constraints insist that only *given* equalities (tv ~ xi) 
+or (F xis ~ rhs) require the LHS and the RHS to have exactly the same kinds. 
+
+  - We have to require this because: 
+        Given equalities can be freely used to rewrite inside 
+        other types or constraints.
+  - We do not have to do the same for wanteds because:
+        First, wanted equations (tv ~ xi) where tv is a touchable unification variable
+        may have kinds that do not agree (the kind of xi must be a sub kind of the kind of tv). 
+        Second, any potential kind mismatch will result in the constraint not being soluble, 
+        which will be reported anyway. This is the reason that @trySpontaneousOneWay@ and 
+        @trySpontaneousTwoWay@ will perform a kind compatibility check, and only then will 
+        they proceed to @solveWithIdentity@. 
+
+Caveat: 
+  - Givens from higher-rank, such as: 
+          type family T b :: * -> * -> * 
+          type instance T Bool = (->) 
+
+          f :: forall a. ((T a ~ (->)) => ...) -> a -> ... 
+          flop = f (...) True 
+     Whereas we would be able to apply the type instance, we would not be able to 
+     use the given (T Bool ~ (->)) in the body of 'flop' 
+
 Note [Loopy spontaneous solving] 
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 Consider the original wanted: 
@@ -583,23 +653,17 @@ The spontaneous solver has to return a given which mentions the unified unificat
 variable *on the left* of the equality. Here is what happens if not: 
   Original wanted:  (a ~ alpha),  (alpha ~ Int) 
 We spontaneously solve the first wanted, without changing the order! 
-      given : a ~ alpha      [having unifice alpha := a] 
+      given : a ~ alpha      [having unified alpha := a] 
 Now the second wanted comes along, but he cannot rewrite the given, so we simply continue.
 At the end we spontaneously solve that guy, *reunifying*  [alpha := Int] 
 
-We avoid this problem by orienting the given so that the unification variable is on the left. 
-[Note that alternatively we could attempt to enforce this at canonicalization] 
+We avoid this problem by orienting the given so that the unification
+variable is on the left.  [Note that alternatively we could attempt to
+enforce this at canonicalization]
 
-Avoiding double unifications is yet another reason to disallow touchable unification variables
-as RHS of type family equations: F xis ~ alpha. Consider having already spontaneously solved 
-a wanted (alpha ~ [b]) by setting alpha := [b]. So the inert set looks like: 
-         given : alpha ~ [b]
-And now a new wanted (F tau ~ alpha) comes along. Since it does not react with anything 
-we will be left with a constraint (F tau ~ alpha) that must cause a unification of 
-(alpha := F tau) at some point (either in spontaneous solving, or at the end). But alpha 
-is *already* unified so we must not do anything to it. By disallowing naked touchables in 
-the RHS of constraints (in favor of introduced flatten skolems) we do not have to worry at 
-all about unifying or spontaneously solving (F xis ~ alpha) by unification. 
+See also Note [No touchables as FunEq RHS] in TcSMonad; avoiding
+double unifications is the main reason we disallow touchable
+unification variables as RHS of type family equations: F xis ~ alpha.
 
 \begin{code}
 ----------------
@@ -608,117 +672,122 @@ solveWithIdentity :: InertSet
                   -> TcS (Maybe SWorkList)
 -- Solve with the identity coercion 
 -- Precondition: kind(xi) is a sub-kind of kind(tv)
--- See [New Wanted Superclass Work] to see why we do this for *given* as well
+-- Precondition: CtFlavor is Wanted or Derived
+-- See [New Wanted Superclass Work] to see why solveWithIdentity 
+--     must work for Derived as well as Wanted
 solveWithIdentity inerts cv gw tv xi 
-  | not (isGiven gw)
-  = do { tybnds <- getTcSTyBindsBag 
-       ; case occ_check_ok tybnds xi of 
-           Nothing -> return Nothing 
-           Just (xi_unflat,coi) -- coi : xi_unflat ~ xi  
-               -> do { traceTcS "Sneaky unification:" $ 
+  = do { tybnds <- getTcSTyBindsMap
+       ; case occurCheck tybnds inerts tv xi of 
+           Nothing              -> return Nothing 
+           Just (xi_unflat,coi) -> solve_with xi_unflat coi }
+  where
+    solve_with xi_unflat coi  -- coi : xi_unflat ~ xi  
+      = do { traceTcS "Sneaky unification:" $ 
                        vcat [text "Coercion variable:  " <+> ppr gw, 
                              text "Coercion:           " <+> pprEq (mkTyVarTy tv) xi,
                              text "Left  Kind is     : " <+> ppr (typeKind (mkTyVarTy tv)),
                              text "Right Kind is     : " <+> ppr (typeKind xi)
-                            ]
-                     ; setWantedTyBind tv xi_unflat        -- Set tv := xi_unflat
-                     ; cv_given <- newGivOrDerCoVar (mkTyVarTy tv) xi_unflat xi_unflat
-                     ; let flav = mkGivenFlavor gw UnkSkol 
-                     ; (cts, co) <- case coi of 
-                         ACo co  -> do { can_eqs <- canEq flav cv_given (mkTyVarTy tv) xi_unflat
-                                       ; return (can_eqs, co) }
-                         IdCo co -> return $ 
-                                    (singleCCan (CTyEqCan { cc_id = cv_given 
-                                                          , cc_flavor = mkGivenFlavor gw UnkSkol
-                                                          , cc_tyvar = tv, cc_rhs = xi }
-                                                          -- xi, *not* xi_unflat because 
-                                                          -- xi_unflat may require flattening!
-                                                ), co)
-                     ; case gw of 
-                         Wanted  {} -> setWantedCoBind  cv co
-                         Derived {} -> setDerivedCoBind cv co 
-                         _          -> pprPanic "Can't spontaneously solve *given*" empty 
-
-       -- See Note [Avoid double unifications] 
-
-                     ; return (Just cts) }
-       }
-  | otherwise 
-  = return Nothing 
-
-  where occ_check_ok :: Bag.Bag (TcTyVar, TcType) -> TcType -> Maybe (TcType,CoercionI) 
-        occ_check_ok ty_binds_bag ty = ok ty 
-           where 
-           -- @ok ty@
-           -- Traverse @ty@ to make sure that @tv@ does not appear under some flatten skolem. 
-           -- If it appears under some flatten skolem look in that flatten skolem equivalence class 
-           -- (see Note [InertSet FlattenSkolemEqClass], [Loopy Spontaneous Solving]) to see if you 
-           -- can find a different flatten skolem to use, that is, one that does not mention @tv@.
-           -- 
-           -- Postcondition: Just (ty',coi) <- ok ty 
-           --       coi :: ty' ~ ty 
-           -- 
-           -- NB: The returned type may not be flat!
-           --    
-           -- NB: There is no need to do the tcView thing here to expand synonyms, because
-           -- expanded synonyms have the same or fewer variables than their expanded definitions, 
-           -- but never more.
-           -- See Note [Type synonyms and the occur check] in TcUnify for the handling of type synonyms.
-                 ok this_ty@(TyConApp tc tys) 
-                   | Just tys_cois <- allMaybes (map ok tys) 
-                   = let (tys',cois') = unzip tys_cois
-                     in Just (TyConApp tc tys', mkTyConAppCoI tc cois') 
-                   | isSynTyCon tc, Just ty_expanded <- tcView this_ty
-                   = ok ty_expanded
-                 ok (PredTy sty) 
-                   | Just (sty',coi) <- ok_pred sty 
-                   = Just (PredTy sty', coi) 
-                   where ok_pred (ClassP cn tys)
-                           | Just tys_cois <- allMaybes $ map ok tys 
-                           = let (tys', cois') = unzip tys_cois 
-                             in Just (ClassP cn tys', mkClassPPredCoI cn cois')
-                         ok_pred (IParam nm ty)   
-                           | Just (ty',co') <- ok ty 
-                           = Just (IParam nm ty', mkIParamPredCoI nm co') 
-                         ok_pred (EqPred ty1 ty2) 
-                           | Just (ty1',coi1) <- ok ty1, Just (ty2',coi2) <- ok ty2
-                           = Just (EqPred ty1' ty2', mkEqPredCoI coi1 coi2) 
-                         ok_pred _ = Nothing 
-                 ok (FunTy arg res) 
-                   | Just (arg', coiarg) <- ok arg, Just (res', coires) <- ok res
-                   = Just (FunTy arg' res', mkFunTyCoI coiarg coires) 
-                 ok (AppTy fun arg) 
-                   | Just (fun', coifun) <- ok fun, Just (arg', coiarg) <- ok arg 
-                   = Just (AppTy fun' arg', mkAppTyCoI coifun coiarg) 
-                 ok (ForAllTy tv1 ty1) 
-                 -- WARNING: What if it is a (t1 ~ t2) => t3? It's not handled properly at the moment. 
-                   | Just (ty1', coi) <- ok ty1 
-                   = Just (ForAllTy tv1 ty1', mkForAllTyCoI tv1 coi) 
-
-                 -- Variable cases 
-                 ok this_ty@(TyVarTy tv') 
-                   | not $ isTcTyVar tv' = Just (this_ty, IdCo this_ty) -- Bound variable
-                   | tv == tv'           = Nothing                      -- Occurs check error
-                 -- Flatten skolem 
-                 ok (TyVarTy fsk) | FlatSkol zty <- tcTyVarDetails fsk
-                   = case ok zty of 
-                       Nothing         -> go_down_eq_class $ getFskEqClass inerts fsk
-                       Just (zty',ico) -> Just (zty',ico) 
-                   where go_down_eq_class [] = Nothing 
-                         go_down_eq_class ((fsk1,co1):rest) 
-                           = case ok (TyVarTy fsk1) of 
-                               Nothing -> go_down_eq_class rest 
-                               Just (ty1,co1i') -> Just (ty1, mkTransCoI co1i' (ACo co1)) 
-                 -- Finally, check if bound already 
-                 ok this_ty@(TyVarTy tv0) 
-                   = case Bag.foldlBag find_bind Nothing ty_binds_bag of 
-                       Nothing -> Just (this_ty, IdCo this_ty)
-                       Just ty0 -> ok ty0 
-                   where find_bind Nothing (tvx,tyx) | tv0 == tvx = Just tyx
-                         find_bind m _ = m 
-                 -- Fall through
-                 ok _ty = Nothing 
-
+                  ]
+           ; setWantedTyBind tv xi_unflat        -- Set tv := xi_unflat
+           ; cv_given <- newGivOrDerCoVar (mkTyVarTy tv) xi_unflat xi_unflat
+           ; let flav = mkGivenFlavor gw UnkSkol 
+           ; (cts, co) <- case coi of 
+               ACo co  -> do { can_eqs <- canEq flav cv_given (mkTyVarTy tv) xi_unflat
+                             ; return (can_eqs, co) }
+               IdCo co -> return $ 
+                          (singleCCan (CTyEqCan { cc_id = cv_given 
+                                                , cc_flavor = mkGivenFlavor gw UnkSkol
+                                                , cc_tyvar = tv, cc_rhs = xi }
+                                                -- xi, *not* xi_unflat because 
+                                                -- xi_unflat may require flattening!
+                                      ), co)
+           ; case gw of 
+               Wanted  {} -> setWantedCoBind  cv co
+               Derived {} -> setDerivedCoBind cv co 
+               _          -> pprPanic "Can't spontaneously solve *given*" empty 
+                     -- See Note [Avoid double unifications] 
+           ; return $ Just (mkEqWorkList cts)  }
+
+occurCheck :: VarEnv (TcTyVar, TcType) -> InertSet
+           -> TcTyVar -> TcType -> Maybe (TcType,CoercionI) 
+-- Traverse @ty@ to make sure that @tv@ does not appear under some flatten skolem. 
+-- If it appears under some flatten skolem look in that flatten skolem equivalence class 
+-- (see Note [InertSet FlattenSkolemEqClass], [Loopy Spontaneous Solving]) to see if you 
+-- can find a different flatten skolem to use, that is, one that does not mention @tv@.
+-- 
+-- Postcondition: Just (ty', coi) = occurCheck binds inerts tv ty 
+--       coi :: ty' ~ ty 
+-- NB: The returned type ty' may not be flat!
+
+occurCheck ty_binds inerts the_tv the_ty
+  = ok emptyVarSet the_ty 
+  where 
+    -- If (fsk `elem` bad) then tv occurs in any rendering
+    -- of the type under the expansion of fsk
+    ok bad this_ty@(TyConApp tc tys) 
+      | Just tys_cois <- allMaybes (map (ok bad) tys) 
+      , (tys',cois') <- unzip tys_cois
+      = Just (TyConApp tc tys', mkTyConAppCoI tc cois') 
+      | isSynTyCon tc, Just ty_expanded <- tcView this_ty
+      = ok bad ty_expanded   -- See Note [Type synonyms and the occur check] in TcUnify
+    ok bad (PredTy sty) 
+      | Just (sty',coi) <- ok_pred bad sty 
+      = Just (PredTy sty', coi) 
+    ok bad (FunTy arg res) 
+      | Just (arg', coiarg) <- ok bad arg, Just (res', coires) <- ok bad res
+      = Just (FunTy arg' res', mkFunTyCoI coiarg coires) 
+    ok bad (AppTy fun arg) 
+      | Just (fun', coifun) <- ok bad fun, Just (arg', coiarg) <- ok bad arg 
+      = Just (AppTy fun' arg', mkAppTyCoI coifun coiarg) 
+    ok bad (ForAllTy tv1 ty1) 
+    -- WARNING: What if it is a (t1 ~ t2) => t3? It's not handled properly at the moment. 
+      | Just (ty1', coi) <- ok bad ty1 
+      = Just (ForAllTy tv1 ty1', mkForAllTyCoI tv1 coi) 
+
+    -- Variable cases 
+    ok bad this_ty@(TyVarTy tv) 
+      | tv == the_tv                                   = Nothing             -- Occurs check error
+      | not (isTcTyVar tv)                     = Just (this_ty, IdCo this_ty) -- Bound var
+      | FlatSkol zty <- tcTyVarDetails tv       = ok_fsk bad tv zty
+      | Just (_,ty) <- lookupVarEnv ty_binds tv = ok bad ty 
+      | otherwise                               = Just (this_ty, IdCo this_ty)
+
+    -- Check if there exists a ty bind already, as a result of sneaky unification. 
+    -- Fall through
+    ok _bad _ty = Nothing 
+
+    -----------
+    ok_pred bad (ClassP cn tys)
+      | Just tys_cois <- allMaybes $ map (ok bad) tys 
+      = let (tys', cois') = unzip tys_cois 
+        in Just (ClassP cn tys', mkClassPPredCoI cn cois')
+    ok_pred bad (IParam nm ty)   
+      | Just (ty',co') <- ok bad ty 
+      = Just (IParam nm ty', mkIParamPredCoI nm co') 
+    ok_pred bad (EqPred ty1 ty2) 
+      | Just (ty1',coi1) <- ok bad ty1, Just (ty2',coi2) <- ok bad ty2
+      = Just (EqPred ty1' ty2', mkEqPredCoI coi1 coi2) 
+    ok_pred _ _ = Nothing 
+
+    -----------
+    ok_fsk bad fsk zty
+      | fsk `elemVarSet` bad 
+            -- We are already trying to find a rendering of fsk, 
+           -- and to do that it seems we need a rendering, so fail
+      = Nothing
+      | otherwise 
+      = firstJusts (ok new_bad zty : map (go_under_fsk new_bad) fsk_equivs)
+      where
+        fsk_equivs = getFskEqClass inerts fsk 
+        new_bad    = bad `extendVarSetList` (fsk : map fst fsk_equivs)
+
+    -----------
+    go_under_fsk bad_tvs (fsk,co)
+      | FlatSkol zty <- tcTyVarDetails fsk
+      = case ok bad_tvs zty of
+           Nothing        -> Nothing
+           Just (ty,coi') -> Just (ty, mkTransCoI coi' (ACo co)) 
+      | otherwise = pprPanic "go_down_equiv" (ppr fsk)
 \end{code}
 
 
@@ -757,10 +826,10 @@ mkIRStop :: Monad m => InertAction -> WorkList -> m InteractResult
 mkIRStop keep newWork = return $ IR Stop keep newWork
 
 dischargeWorkItem :: Monad m => m InteractResult
-dischargeWorkItem = mkIRStop KeepInert emptyCCan
+dischargeWorkItem = mkIRStop KeepInert emptyWorkList
 
 noInteraction :: Monad m => WorkItem -> m InteractResult
-noInteraction workItem = mkIRContinue workItem KeepInert emptyCCan
+noInteraction workItem = mkIRContinue workItem KeepInert emptyWorkList
 
 data WhichComesFromInert = LeftComesFromInert | RightComesFromInert 
 
@@ -777,7 +846,7 @@ interactWithInertsStage workItem inert
   = foldlInertSetM interactNext initITR inert
   where 
     initITR = SR { sr_inerts   = emptyInert
-                 , sr_new_work = emptyCCan
+                 , sr_new_work = emptyWorkList
                  , sr_stop     = ContinueWith workItem }
 
 
@@ -844,11 +913,28 @@ doInteractWithInert
              inert_pred_loc     = (ClassP cls1 tys1, ppr d1)
             loc                = combineCtLoc fl1 fl2
              eqn_pred_locs = improveFromAnother work_item_pred_loc inert_pred_loc         
+
        ; wevvars <- mkWantedFunDepEqns loc eqn_pred_locs 
+       ; fd_cts <- canWanteds wevvars 
+       ; let fd_work = mkEqWorkList fd_cts 
                 -- See Note [Generating extra equalities]
-       ; workList <- canWanteds wevvars 
-       ; mkIRContinue workItem KeepInert workList -- Keep the inert there so we avoid 
-                                                  -- re-introducing the fundep equalities
+       ; if isEmptyCCan fd_cts || not (isWanted fl2) then -- || or impr. had previously kicked in
+             -- No improvement kicked in, keep going
+             mkIRContinue workItem KeepInert fd_work 
+         else -- Improvement kicked in, throw him back into the worklist so that he
+              -- gets rewritten. The reason is that we do not want to let him fall off 
+              -- at the end and then add its potential un-improved superclasses. This 
+              -- optimisation crucially relies on prioritizing the equalities in the 
+              -- worklist.
+
+              -- The termination of this relies on wanteds being able to rewrite wanteds. 
+              -- Since the class may be at the bottom of an equality worklist, which may
+              -- consist of insoluble wanteds, if these wanteds *never* become solved or given
+              -- (because they mention untouchables), the workitem will *never* be rewritten
+              -- so next time we meet him we will be once again producing FunDep equalities
+              -- for ever and ever! 
+             mkIRStop KeepInert $ fd_work `unionWorkLists` singleNonEqWL workItem
+
          -- See Note [FunDep Reactions] 
        }
 
@@ -873,14 +959,14 @@ doInteractWithInert (CTyEqCan { cc_id = cv, cc_flavor = ifl, cc_tyvar = tv, cc_r
     -- set again, to find that it can now be discharged by the given D
     -- Int instance.
   = do { rewritten_dict <- rewriteDict (cv,tv,xi) (dv,wfl,cl,xis)
-       ; mkIRStop KeepInert (singleCCan rewritten_dict) }
+       ; mkIRStop KeepInert $ singleNonEqWL rewritten_dict }
     
 doInteractWithInert (CDictCan { cc_id = dv, cc_flavor = ifl, cc_class = cl, cc_tyargs = xis }) 
            workItem@(CTyEqCan { cc_id = cv, cc_flavor = wfl, cc_tyvar = tv, cc_rhs = xi })
   | wfl `canRewrite` ifl
   , tv `elemVarSet` tyVarsOfTypes xis
   = do { rewritten_dict <- rewriteDict (cv,tv,xi) (dv,ifl,cl,xis) 
-       ; mkIRContinue workItem DropInert (singleCCan rewritten_dict) }
+       ; mkIRContinue workItem DropInert (singleNonEqWL rewritten_dict) }
 
 -- Class constraint and given equality: use the equality to rewrite
 -- the class constraint.
@@ -889,14 +975,14 @@ doInteractWithInert (CTyEqCan { cc_id = cv, cc_flavor = ifl, cc_tyvar = tv, cc_r
   | ifl `canRewrite` wfl
   , tv `elemVarSet` tyVarsOfType ty 
   = do { rewritten_ip <- rewriteIP (cv,tv,xi) (ipid,wfl,nm,ty) 
-       ; mkIRStop KeepInert (singleCCan rewritten_ip) }
+       ; mkIRStop KeepInert (singleNonEqWL rewritten_ip) }
 
 doInteractWithInert (CIPCan { cc_id = ipid, cc_flavor = ifl, cc_ip_nm = nm, cc_ip_ty = ty }) 
            workItem@(CTyEqCan { cc_id = cv, cc_flavor = wfl, cc_tyvar = tv, cc_rhs = xi })
   | wfl `canRewrite` ifl
   , tv `elemVarSet` tyVarsOfType ty
   = do { rewritten_ip <- rewriteIP (cv,tv,xi) (ipid,ifl,nm,ty) 
-       ; mkIRContinue workItem DropInert (singleCCan rewritten_ip) } 
+       ; mkIRContinue workItem DropInert (singleNonEqWL rewritten_ip) }
 
 -- Two implicit parameter constraints.  If the names are the same,
 -- but their types are not, we generate a wanted type equality 
@@ -909,7 +995,7 @@ doInteractWithInert (CIPCan { cc_id = id1, cc_flavor = ifl, cc_ip_nm = nm1, cc_i
   =    -- See Note [Overriding implicit parameters]
         -- Dump the inert item, override totally with the new one
        -- Do not require type equality
-    mkIRContinue workItem DropInert emptyCCan
+    mkIRContinue workItem DropInert emptyWorkList
 
   | nm1 == nm2 && ty1 `tcEqType` ty2 
   = solveOneFromTheOther (id1,ifl) workItem 
@@ -918,7 +1004,8 @@ doInteractWithInert (CIPCan { cc_id = id1, cc_flavor = ifl, cc_ip_nm = nm1, cc_i
   =    -- See Note [When improvement happens]
     do { co_var <- newWantedCoVar ty1 ty2 
        ; let flav = Wanted (combineCtLoc ifl wfl) 
-       ; mkCanonical flav co_var >>= mkIRContinue workItem KeepInert } 
+       ; cans <- mkCanonical flav co_var 
+       ; mkIRContinue workItem KeepInert (mkEqWorkList cans) }
 
 
 -- Inert: equality, work item: function equality
@@ -936,7 +1023,7 @@ doInteractWithInert (CTyEqCan { cc_id = cv1, cc_flavor = ifl, cc_tyvar = tv, cc_
   | ifl `canRewrite` wfl 
   , tv `elemVarSet` tyVarsOfTypes args
   = do { rewritten_funeq <- rewriteFunEq (cv1,tv,xi1) (cv2,wfl,tc,args,xi2) 
-       ; mkIRStop KeepInert (singleCCan rewritten_funeq) }
+       ; mkIRStop KeepInert (singleEqWL rewritten_funeq) }
 
 -- Inert: function equality, work item: equality
 
@@ -946,18 +1033,18 @@ doInteractWithInert (CFunEqCan {cc_id = cv1, cc_flavor = ifl, cc_fun = tc
   | wfl `canRewrite` ifl
   , tv `elemVarSet` tyVarsOfTypes args
   = do { rewritten_funeq <- rewriteFunEq (cv2,tv,xi2) (cv1,ifl,tc,args,xi1) 
-       ; mkIRContinue workItem DropInert (singleCCan rewritten_funeq) } 
+       ; mkIRContinue workItem DropInert (singleEqWL rewritten_funeq) } 
 
 doInteractWithInert (CFunEqCan { cc_id = cv1, cc_flavor = fl1, cc_fun = tc1
                                , cc_tyargs = args1, cc_rhs = xi1 }) 
            workItem@(CFunEqCan { cc_id = cv2, cc_flavor = fl2, cc_fun = tc2
                                , cc_tyargs = args2, cc_rhs = xi2 })
-  | fl1 `canRewrite` fl2 && lhss_match
+  | fl1 `canSolve` fl2 && lhss_match
   = do { cans <- rewriteEqLHS LeftComesFromInert  (mkCoVarCoercion cv1,xi1) (cv2,fl2,xi2) 
-       ; mkIRStop KeepInert cans } 
-  | fl2 `canRewrite` fl1 && lhss_match
+       ; mkIRStop KeepInert (mkEqWorkList cans) } 
+  | fl2 `canSolve` fl1 && lhss_match
   = do { cans <- rewriteEqLHS RightComesFromInert (mkCoVarCoercion cv2,xi2) (cv1,fl1,xi1) 
-       ; mkIRContinue workItem DropInert cans }
+       ; mkIRContinue workItem DropInert (mkEqWorkList cans) }
   where
     lhss_match = tc1 == tc2 && and (zipWith tcEqType args1 args2) 
 
@@ -965,21 +1052,21 @@ doInteractWithInert
            inert@(CTyEqCan { cc_id = cv1, cc_flavor = fl1, cc_tyvar = tv1, cc_rhs = xi1 }) 
            workItem@(CTyEqCan { cc_id = cv2, cc_flavor = fl2, cc_tyvar = tv2, cc_rhs = xi2 })
 -- Check for matching LHS 
-  | fl1 `canRewrite` fl2 && tv1 == tv2 
+  | fl1 `canSolve` fl2 && tv1 == tv2 
   = do { cans <- rewriteEqLHS LeftComesFromInert (mkCoVarCoercion cv1,xi1) (cv2,fl2,xi2) 
-       ; mkIRStop KeepInert cans } 
+       ; mkIRStop KeepInert (mkEqWorkList cans) } 
 
-  | fl2 `canRewrite` fl1 && tv1 == tv2 
+  | fl2 `canSolve` fl1 && tv1 == tv2 
   = do { cans <- rewriteEqLHS RightComesFromInert (mkCoVarCoercion cv2,xi2) (cv1,fl1,xi1) 
-       ; mkIRContinue workItem DropInert cans } 
+       ; mkIRContinue workItem DropInert (mkEqWorkList cans) } 
 
 -- Check for rewriting RHS 
   | fl1 `canRewrite` fl2 && tv1 `elemVarSet` tyVarsOfType xi2 
   = do { rewritten_eq <- rewriteEqRHS (cv1,tv1,xi1) (cv2,fl2,tv2,xi2) 
-       ; mkIRStop KeepInert rewritten_eq }
+       ; mkIRStop KeepInert (mkEqWorkList rewritten_eq) }
   | fl2 `canRewrite` fl1 && tv2 `elemVarSet` tyVarsOfType xi1
   = do { rewritten_eq <- rewriteEqRHS (cv2,tv2,xi2) (cv1,fl1,tv1,xi1) 
-       ; mkIRContinue workItem DropInert rewritten_eq } 
+       ; mkIRContinue workItem DropInert (mkEqWorkList rewritten_eq) } 
 
 -- Finally, if workitem is a Flatten Equivalence Class constraint and the 
 -- inert is a wanted constraint, even when the workitem cannot rewrite the 
@@ -991,20 +1078,13 @@ doInteractWithInert
     isMetaTyVar tv1,                    -- and has a unification variable lhs
     FlatSkol {} <- tcTyVarDetails tv2,  -- And workitem is a flatten skolem equality
     Just tv2'   <- tcGetTyVar_maybe xi2, FlatSkol {} <- tcTyVarDetails tv2' 
-  = mkIRContinue workItem DropInert (singletonWorkList inert)
+  = mkIRContinue workItem DropInert (singleEqWL inert)   
 
 
 -- Fall-through case for all other situations
 doInteractWithInert _ workItem = noInteraction workItem
 
---------------------------------------------
-combineCtLoc :: CtFlavor -> CtFlavor -> WantedLoc
--- Precondition: At least one of them should be wanted 
-combineCtLoc (Wanted loc) _ = loc 
-combineCtLoc _ (Wanted loc) = loc 
-combineCtLoc _ _ = panic "Expected one of wanted constraints (BUG)" 
-
-
+-------------------------
 -- Equational Rewriting 
 rewriteDict  :: (CoVar, TcTyVar, Xi) -> (DictId, CtFlavor, Class, [Xi]) -> TcS CanonicalCt
 rewriteDict (cv,tv,xi) (dv,gw,cl,xis) 
@@ -1081,7 +1161,7 @@ rewriteEqRHS (cv1,tv1,xi1) (cv2,gw,tv2,xi2)
        ; return (singleCCan $ CTyEqCan { cc_id = cv2' 
                                        , cc_flavor = gw 
                                        , cc_tyvar = tv2 
-                                       , cc_rhs   = xi2'' }) 
+                                       , cc_rhs   = xi2'' })
        }
   where 
     xi2' = substTyWith [tv1] [xi1] xi2 
@@ -1092,7 +1172,7 @@ rewriteEqLHS :: WhichComesFromInert -> (Coercion,Xi) -> (CoVar,CtFlavor,Xi) -> T
 -- Used to ineratct two equalities of the following form: 
 -- First Equality:   co1: (XXX ~ xi1)  
 -- Second Equality:  cv2: (XXX ~ xi2) 
--- Where the cv1 `canRewrite` cv2 equality 
+-- Where the cv1 `canSolve` cv2 equality 
 -- We have an option of creating new work (xi1 ~ xi2) OR (xi2 ~ xi1). This 
 -- depends on whether the left or the right equality comes from the inert set. 
 -- We must:  
@@ -1116,10 +1196,9 @@ rewriteEqLHS which (co1,xi1) (cv2,gw,xi2)
                    (False,RightComesFromInert) -> 
                         newGivOrDerCoVar xi1 xi2 $ 
                         mkSymCoercion co1 `mkTransCoercion` mkCoVarCoercion cv2
-       ; mkCanonical gw cv2' }
-
-
-
+       ; mkCanonical gw cv2'
+       }
+                                           
 solveOneFromTheOther :: (EvVar, CtFlavor) -> CanonicalCt -> TcS InteractResult 
 -- First argument inert, second argument workitem. They both represent 
 -- wanted/given/derived evidence for the *same* predicate so we try here to 
@@ -1135,15 +1214,15 @@ solveOneFromTheOther (iid,ifl) workItem
   | isDerived ifl && isDerived wfl 
   = noInteraction workItem 
 
-  | ifl `canRewrite` wfl
+  | ifl `canSolve` wfl
   = do { unless (isGiven wfl) $ setEvBind wid (EvId iid) 
            -- Overwrite the binding, if one exists
           -- For Givens, which are lambda-bound, nothing to overwrite,
        ; dischargeWorkItem }
 
-  | otherwise  -- wfl `canRewrite` ifl 
+  | otherwise  -- wfl `canSolve` ifl 
   = do { unless (isGiven ifl) $ setEvBind iid (EvId wid)
-       ; mkIRContinue workItem DropInert emptyCCan }
+       ; mkIRContinue workItem DropInert emptyWorkList }
 
   where 
      wfl = cc_flavor workItem
@@ -1567,15 +1646,16 @@ doTopReact workItem@(CDictCan { cc_id = dv, cc_flavor = Wanted loc
                     -- Solved in one step and no new wanted work produced. 
                     -- i.e we directly matched a top-level instance
                    -- No point in caching this in 'inert', nor in adding superclasses
-                    then return $ SomeTopInt { tir_new_work  = emptyCCan 
+                    then return $ SomeTopInt { tir_new_work  = emptyWorkList 
                                              , tir_new_inert = Stop }
 
                     -- Solved and new wanted work produced, you may cache the 
                    -- (tentatively solved) dictionary as Derived and its superclasses
                     else do { let solved = makeSolved workItem
                             ; sc_work <- newSCWorkFromFlavored dv (Derived loc) cls xis 
+                            ; let inst_work = workListFromCCans workList
                             ; return $ SomeTopInt 
-                                  { tir_new_work = workList `unionWorkLists` sc_work 
+                                  { tir_new_work  = inst_work `unionWorkLists` sc_work 
                                   , tir_new_inert = ContinueWith solved } }
                   }
        }
@@ -1589,10 +1669,20 @@ doTopReact workItem@(CDictCan { cc_id = dv, cc_flavor = Wanted loc
            ; wevvars <- mkWantedFunDepEqns loc eqn_pred_locs 
                      -- NB: fundeps generate some wanted equalities, but 
                      --     we don't use their evidence for anything
-           ; fd_work <- canWanteds wevvars 
-           ; sc_work <- newSCWorkFromFlavored dv (Derived loc) cls xis
-           ; return $ SomeTopInt { tir_new_work = fd_work `unionWorkLists` sc_work
-                                 , tir_new_inert = ContinueWith workItem }
+           ; fd_cts <- canWanteds wevvars 
+           ; let fd_work = mkEqWorkList fd_cts
+
+           ; if isEmptyCCan fd_cts then 
+                 do { sc_work <- newSCWorkFromFlavored dv (Derived loc) cls xis
+                    ; return $ SomeTopInt { tir_new_work = fd_work `unionWorkLists` sc_work
+                                          , tir_new_inert = ContinueWith workItem }
+                    }
+             else -- More fundep work produced, don't do any superlcass stuff, just 
+                  -- thow him back in the worklist prioritizing the solution of fd equalities
+                 return $ 
+                 SomeTopInt { tir_new_work = fd_work `unionWorkLists` singleNonEqWL workItem
+                            , tir_new_inert = Stop }
+
            -- NB: workItem is inert, but it isn't solved
           -- keep it as inert, although it's not solved because we
            -- have now reacted all its top-level fundep-induced equalities!
@@ -1632,7 +1722,8 @@ doTopReact (CFunEqCan { cc_id = cv, cc_flavor = fl
                               _ -> newGivOrDerCoVar xi rhs_ty $ 
                                    mkSymCoercion (mkCoVarCoercion cv) `mkTransCoercion` coe 
 
-                   ; workList <- mkCanonical fl cv'
+                   ; can_cts <- mkCanonical fl cv'
+                   ; let workList = mkEqWorkList can_cts
                    ; return $ SomeTopInt workList Stop }
            _ 
              -> panicTcS $ text "TcSMonad.matchFam returned multiple instances!"
@@ -1671,7 +1762,17 @@ might dischard d2 directly:
         d2 := d1 |> D Int cv
 
 But in general it's a bit painful to figure out the necessary coercion,
-so we just take the first approach.
+so we just take the first approach. Here is a better example. Consider:
+    class C a b c | a -> b 
+And: 
+     [Given]  d1 : C T Int Char 
+     [Wanted] d2 : C T beta Int 
+In this case, it's *not even possible* to solve the wanted immediately. 
+So we should simply output the functional dependency and add this guy
+[but NOT its superclasses] back in the worklist. Even worse: 
+     [Given] d1 : C T Int beta 
+     [Wanted] d2: C T beta Int 
+Then it is solvable, but its very hard to detect this on the spot. 
 
 It's exactly the same with implicit parameters, except that the
 "aggressive" approach would be much easier to implement.
@@ -1783,19 +1884,18 @@ new given work. There are several reasons for this:
         Now suppose that we have: 
                given: C a b 
                wanted: C a beta 
-        By interacting the given we will get that (F a ~ b) which is not 
+        By interacting the given we will get given (F a ~ b) which is not 
         enough by itself to make us discharge (C a beta). However, we 
-        may create a new given equality from the super-class that we promise
-        to solve: (F a ~ beta). Now we may interact this with the rest of 
-        constraint to finally get: 
-                  given :  beta ~ b 
-        
+        may create a new derived equality from the super-class of the
+        wanted constraint (C a beta), namely derived (F a ~ beta). 
+        Now we may interact this with given (F a ~ b) to get: 
+                  derived :  beta ~ b 
         But 'beta' is a touchable unification variable, and hence OK to 
-        unify it with 'b', replacing the given evidence with the identity. 
+        unify it with 'b', replacing the derived evidence with the identity. 
 
-        This requires trySpontaneousSolve to solve given equalities that
-        have a touchable in their RHS, *in addition* to solving wanted 
-        equalities. 
+        This requires trySpontaneousSolve to solve *derived*
+        equalities that have a touchable in their RHS, *in addition*
+        to solving wanted equalities.
 
 Here is another example where this is useful. 
 
@@ -1848,7 +1948,9 @@ newSCWorkFromFlavored ev flavor cls xis
              -- Add *all* its superclasses (equalities or not) as new given work 
              -- See Note [New Wanted Superclass Work] 
        ; sc_vars <- zipWithM inst_one sc_theta1 [0..]
-       ; mkCanonicals flavor sc_vars } 
+       ; can_cts <- mkCanonicals flavor sc_vars 
+       ; return $ workListFromCCans can_cts 
+       }
   where
     inst_one pred n = newGivOrDerEvVar pred (EvSuperClass ev n)
 
@@ -1884,5 +1986,3 @@ matchClassInst clas tys loc
                  }
         }
 \end{code}
-
-