A few more wibbles on ghc-new-co
[ghc-hetmet.git] / compiler / types / OptCoercion.lhs
1 %\r
2 % (c) The University of Glasgow 2006\r
3 %\r
4 \r
5 \begin{code}\r
6 module OptCoercion ( optCoercion ) where \r
7 \r
8 #include "HsVersions.h"\r
9 \r
10 import Coercion\r
11 import Type hiding( substTyVarBndr, substTy, extendTvSubst )\r
12 import TyCon\r
13 import Var\r
14 import VarSet\r
15 import VarEnv\r
16 import StaticFlags      ( opt_NoOptCoercion )\r
17 import Outputable\r
18 import Pair\r
19 import Maybes( allMaybes )\r
20 import FastString\r
21 \end{code}\r
22 \r
23 %************************************************************************\r
24 %*                                                                      *\r
25                  Optimising coercions                                                                   \r
26 %*                                                                      *\r
27 %************************************************************************\r
28 \r
29 Note [Subtle shadowing in coercions]\r
30 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r
31 Supose we optimising a coercion\r
32     optCoercion (forall (co_X5:t1~t2). ...co_B1...)\r
33 The co_X5 is a wild-card; the bound variable of a coercion for-all\r
34 should never appear in the body of the forall. Indeed we often\r
35 write it like this\r
36     optCoercion ( (t1~t2) => ...co_B1... )\r
37 \r
38 Just because it's a wild-card doesn't mean we are free to choose\r
39 whatever variable we like.  For example it'd be wrong for optCoercion\r
40 to return\r
41    forall (co_B1:t1~t2). ...co_B1...\r
42 because now the co_B1 (which is really free) has been captured, and\r
43 subsequent substitutions will go wrong.  That's why we can't use\r
44 mkCoPredTy in the ForAll case, where this note appears.  \r
45 \r
46 \begin{code}\r
47 optCoercion :: CvSubst -> Coercion -> NormalCo\r
48 -- ^ optCoercion applies a substitution to a coercion, \r
49 --   *and* optimises it to reduce its size\r
50 optCoercion env co \r
51   | opt_NoOptCoercion = substCo env co\r
52   | otherwise         = opt_co env False co\r
53 \r
54 type NormalCo = Coercion\r
55   -- Invariants: \r
56   --  * The substitution has been fully applied\r
57   --  * For trans coercions (co1 `trans` co2)\r
58   --       co1 is not a trans, and neither co1 nor co2 is identity\r
59   --  * If the coercion is the identity, it has no CoVars of CoTyCons in it (just types)\r
60 \r
61 type NormalNonIdCo = NormalCo  -- Extra invariant: not the identity\r
62 \r
63 opt_co, opt_co' :: CvSubst\r
64                 -> Bool        -- True <=> return (sym co)\r
65                 -> Coercion\r
66                 -> NormalCo     \r
67 opt_co = opt_co'\r
68 {-\r
69 opt_co env sym co\r
70  = pprTrace "opt_co {" (ppr sym <+> ppr co $$ ppr env) $\r
71    co1 `seq`\r
72    pprTrace "opt_co done }" (ppr co1) $\r
73    (WARN( not same_co_kind, ppr co  <+> dcolon <+> pprEqPred (Pair s1 t1)\r
74                          $$ ppr co1 <+> dcolon <+> pprEqPred (Pair s2 t2) )\r
75     WARN( not (coreEqCoercion co1 simple_result),\r
76            (text "env=" <+> ppr env) $$\r
77            (text "input=" <+> ppr co) $$\r
78            (text "simple=" <+> ppr simple_result) $$\r
79            (text "opt=" <+> ppr co1) )\r
80    co1)\r
81  where\r
82    co1 = opt_co' env sym co\r
83    same_co_kind = s1 `eqType` s2 && t1 `eqType` t2\r
84    Pair s t = coercionKind (substCo env co)\r
85    (s1,t1) | sym = (t,s)\r
86            | otherwise = (s,t)\r
87    Pair s2 t2 = coercionKind co1\r
88 \r
89    simple_result | sym = mkSymCo (substCo env co)\r
90                  | otherwise = substCo env co\r
91 -}\r
92 \r
93 opt_co' env _   (Refl ty)           = Refl (substTy env ty)\r
94 opt_co' env sym (SymCo co)          = opt_co env (not sym) co\r
95 opt_co' env sym (TyConAppCo tc cos) = mkTyConAppCo tc (map (opt_co env sym) cos)\r
96 opt_co' env sym (PredCo cos)        = mkPredCo (fmap (opt_co env sym) cos)\r
97 opt_co' env sym (AppCo co1 co2)     = mkAppCo (opt_co env sym co1) (opt_co env sym co2)\r
98 opt_co' env sym (ForAllCo tv co)    = case substTyVarBndr env tv of\r
99                                          (env', tv') -> ForAllCo tv' (opt_co env' sym co)\r
100 opt_co' env sym (CoVarCo cv)\r
101   | Just co <- lookupCoVar env cv\r
102   = opt_co (zapCvSubstEnv env) sym co\r
103 \r
104   | Just cv1 <- lookupInScope (getCvInScope env) cv\r
105   = ASSERT( isCoVar cv1 ) wrapSym sym (CoVarCo cv1)\r
106                 -- cv1 might have a substituted kind!\r
107 \r
108   | otherwise = WARN( True, ptext (sLit "opt_co: not in scope:") <+> ppr cv $$ ppr env)\r
109                 ASSERT( isCoVar cv )\r
110                 wrapSym sym (CoVarCo cv)\r
111 \r
112 opt_co' env sym (AxiomInstCo con cos)\r
113     -- Do *not* push sym inside top-level axioms\r
114     -- e.g. if g is a top-level axiom\r
115     --   g a : f a ~ a\r
116     -- then (sym (g ty)) /= g (sym ty) !!\r
117   = wrapSym sym $ AxiomInstCo con (map (opt_co env False) cos)\r
118       -- Note that the_co does *not* have sym pushed into it\r
119 \r
120 opt_co' env sym (UnsafeCo ty1 ty2)\r
121   | ty1' `eqType` ty2' = Refl ty1'\r
122   | sym                = mkUnsafeCo ty2' ty1'\r
123   | otherwise          = mkUnsafeCo ty1' ty2'\r
124   where\r
125     ty1' = substTy env ty1\r
126     ty2' = substTy env ty2\r
127 \r
128 opt_co' env sym (TransCo co1 co2)\r
129   | sym       = opt_trans opt_co2 opt_co1   -- sym (g `o` h) = sym h `o` sym g\r
130   | otherwise = opt_trans opt_co1 opt_co2\r
131   where\r
132     opt_co1 = opt_co env sym co1\r
133     opt_co2 = opt_co env sym co2\r
134 \r
135 opt_co' env sym (NthCo n co)\r
136   | TyConAppCo tc cos <- co'\r
137   , isDecomposableTyCon tc              -- Not synonym families\r
138   = ASSERT( n < length cos )\r
139     cos !! n\r
140   | otherwise\r
141   = NthCo n co'\r
142   where\r
143     co' = opt_co env sym co\r
144 \r
145 opt_co' env sym (InstCo co ty)\r
146     -- See if the first arg is already a forall\r
147     -- ...then we can just extend the current substitution\r
148   | Just (tv, co_body) <- splitForAllCo_maybe co\r
149   = opt_co (extendTvSubst env tv ty') sym co_body\r
150 \r
151     -- See if it is a forall after optimization\r
152   | Just (tv, co'_body) <- splitForAllCo_maybe co'\r
153   = substCoWithTy tv ty' co'_body   -- An inefficient one-variable substitution\r
154 \r
155   | otherwise = InstCo co' ty'\r
156 \r
157   where\r
158     co' = opt_co env sym co\r
159     ty' = substTy env ty\r
160 \r
161 -------------\r
162 opt_transList :: [NormalCo] -> [NormalCo] -> [NormalCo]\r
163 opt_transList = zipWith opt_trans\r
164 \r
165 opt_trans :: NormalCo -> NormalCo -> NormalCo\r
166 opt_trans co1 co2\r
167   | isReflCo co1 = co2\r
168   | otherwise    = opt_trans1 co1 co2\r
169 \r
170 opt_trans1 :: NormalNonIdCo -> NormalCo -> NormalCo\r
171 -- First arg is not the identity\r
172 opt_trans1 co1 co2\r
173   | isReflCo co2 = co1\r
174   | otherwise    = opt_trans2 co1 co2\r
175 \r
176 opt_trans2 :: NormalNonIdCo -> NormalNonIdCo -> NormalCo\r
177 -- Neither arg is the identity\r
178 opt_trans2 (TransCo co1a co1b) co2\r
179     -- Don't know whether the sub-coercions are the identity\r
180   = opt_trans co1a (opt_trans co1b co2)  \r
181 \r
182 opt_trans2 co1 co2 \r
183   | Just co <- opt_trans_rule co1 co2\r
184   = co\r
185 \r
186 opt_trans2 co1 (TransCo co2a co2b)\r
187   | Just co1_2a <- opt_trans_rule co1 co2a\r
188   = if isReflCo co1_2a\r
189     then co2b\r
190     else opt_trans1 co1_2a co2b\r
191 \r
192 opt_trans2 co1 co2\r
193   = mkTransCo co1 co2\r
194 \r
195 ------\r
196 -- Optimize coercions with a top-level use of transitivity.\r
197 opt_trans_rule :: NormalNonIdCo -> NormalNonIdCo -> Maybe NormalCo\r
198 \r
199 -- push transitivity down through matching top-level constructors.\r
200 opt_trans_rule in_co1@(TyConAppCo tc1 cos1) in_co2@(TyConAppCo tc2 cos2)\r
201   | tc1 == tc2 = fireTransRule "PushTyConApp" in_co1 in_co2 $\r
202                  TyConAppCo tc1 (opt_transList cos1 cos2)\r
203 \r
204 -- push transitivity through matching destructors\r
205 opt_trans_rule in_co1@(NthCo d1 co1) in_co2@(NthCo d2 co2)\r
206   | d1 == d2\r
207   , co1 `compatible_co` co2\r
208   = fireTransRule "PushNth" in_co1 in_co2 $\r
209     mkNthCo d1 (opt_trans co1 co2)\r
210 \r
211 -- Push transitivity inside instantiation\r
212 opt_trans_rule in_co1@(InstCo co1 ty1) in_co2@(InstCo co2 ty2)\r
213   | ty1 `eqType` ty2\r
214   , co1 `compatible_co` co2\r
215   = fireTransRule "TrPushInst" in_co1 in_co2 $\r
216     mkInstCo (opt_trans co1 co2) ty1\r
217  \r
218 -- Push transitivity inside apply\r
219 opt_trans_rule in_co1@(AppCo co1a co1b) in_co2@(AppCo co2a co2b)\r
220   = fireTransRule "TrPushApp" in_co1 in_co2 $\r
221     mkAppCo (opt_trans co1a co2a) (opt_trans co1b co2b)\r
222 \r
223 -- Push transitivity inside PredCos\r
224 opt_trans_rule in_co1@(PredCo pco1) in_co2@(PredCo pco2)\r
225   | Just pco' <- opt_trans_pred pco1 pco2\r
226   = fireTransRule "TrPushPrd" in_co1 in_co2 $\r
227     mkPredCo pco'\r
228 \r
229 opt_trans_rule co1@(TyConAppCo tc cos1) co2\r
230   | Just cos2 <- etaTyConAppCo_maybe tc co2\r
231   = ASSERT( length cos1 == length cos2 )\r
232     fireTransRule "EtaCompL" co1 co2 $\r
233     TyConAppCo tc (zipWith opt_trans cos1 cos2)\r
234 \r
235 opt_trans_rule co1 co2@(TyConAppCo tc cos2)\r
236   | Just cos1 <- etaTyConAppCo_maybe tc co1\r
237   = ASSERT( length cos1 == length cos2 )\r
238     fireTransRule "EtaCompR" co1 co2 $\r
239     TyConAppCo tc (zipWith opt_trans cos1 cos2)\r
240 \r
241 \r
242 {- BAY: think harder about this.  do we still need it?\r
243 -- Push transitivity inside (s~t)=>r\r
244 -- We re-use the CoVar rather than using mkCoPredTy\r
245 -- See Note [Subtle shadowing in coercions]\r
246 opt_trans_rule co1 co2\r
247   | Just (cv1,r1) <- splitForAllTy_maybe co1\r
248   , isCoVar cv1\r
249   , Just (s1,t1) <- coVarKind_maybe cv1\r
250   , Just (s2,t2,r2) <- etaCoPred_maybe co2\r
251   = Just (ForAllTy (mkCoVar (coVarName cv1) (mkCoType (opt_trans s1 s2) (opt_trans t1 t2)))\r
252                    (opt_trans r1 r2))\r
253 \r
254   | Just (cv2,r2) <- splitForAllTy_maybe co2\r
255   , isCoVar cv2\r
256   , Just (s2,t2) <- coVarKind_maybe cv2\r
257   , Just (s1,t1,r1) <- etaCoPred_maybe co1\r
258   = Just (ForAllTy (mkCoVar (coVarName cv2) (mkCoType (opt_trans s1 s2) (opt_trans t1 t2)))\r
259                    (opt_trans r1 r2))\r
260 -}\r
261 \r
262 -- Push transitivity inside forall\r
263 opt_trans_rule co1 co2\r
264   | Just (tv1,r1) <- splitForAllCo_maybe co1\r
265   , Just (tv2,r2) <- etaForAllCo_maybe co2\r
266   , let r2' = substCoWithTy tv2 (mkTyVarTy tv1) r2\r
267   = fireTransRule "EtaAllL" co1 co2 $\r
268     mkForAllCo tv1 (opt_trans2 r1 r2')\r
269 \r
270   | Just (tv2,r2) <- splitForAllCo_maybe co2\r
271   , Just (tv1,r1) <- etaForAllCo_maybe co1\r
272   , let r1' = substCoWithTy tv1 (mkTyVarTy tv2) r1\r
273   = fireTransRule "EtaAllR" co1 co2 $\r
274     mkForAllCo tv1 (opt_trans2 r1' r2)\r
275 \r
276 -- Push transitivity inside axioms\r
277 opt_trans_rule co1 co2\r
278 \r
279   -- TrPushAxR/TrPushSymAxR\r
280   | Just (sym, con, cos1) <- co1_is_axiom_maybe\r
281   , Just cos2 <- matchAxiom sym con co2\r
282   = fireTransRule "TrPushAxR" co1 co2 $\r
283     if sym \r
284     then SymCo $ AxiomInstCo con (opt_transList (map mkSymCo cos2) cos1)\r
285     else         AxiomInstCo con (opt_transList cos1 cos2)\r
286 \r
287   -- TrPushAxL/TrPushSymAxL\r
288   | Just (sym, con, cos2) <- co2_is_axiom_maybe\r
289   , Just cos1 <- matchAxiom (not sym) con co1\r
290   = fireTransRule "TrPushAxL" co1 co2 $\r
291     if sym \r
292     then SymCo $ AxiomInstCo con (opt_transList cos2 (map mkSymCo cos1))\r
293     else         AxiomInstCo con (opt_transList cos1 cos2)\r
294 \r
295   -- TrPushAxSym/TrPushSymAx\r
296   | Just (sym1, con1, cos1) <- co1_is_axiom_maybe\r
297   , Just (sym2, con2, cos2) <- co2_is_axiom_maybe\r
298   , con1 == con2\r
299   , sym1 == not sym2\r
300   , let qtvs = co_ax_tvs con1\r
301         lhs  = co_ax_lhs con1 \r
302         rhs  = co_ax_rhs con1 \r
303         pivot_tvs = exactTyVarsOfType (if sym2 then rhs else lhs)\r
304   , all (`elemVarSet` pivot_tvs) qtvs\r
305   = fireTransRule "TrPushAxSym" co1 co2 $\r
306     if sym2\r
307     then liftCoSubstWith qtvs (opt_transList cos1 (map mkSymCo cos2)) lhs  -- TrPushAxSym\r
308     else liftCoSubstWith qtvs (opt_transList (map mkSymCo cos1) cos2) rhs  -- TrPushSymAx\r
309   where\r
310     co1_is_axiom_maybe = isAxiom_maybe co1\r
311     co2_is_axiom_maybe = isAxiom_maybe co2\r
312 \r
313 opt_trans_rule co1 co2  -- Identity rule\r
314   | Pair ty1 _ <- coercionKind co1\r
315   , Pair _ ty2 <- coercionKind co2\r
316   , ty1 `eqType` ty2\r
317   = fireTransRule "RedTypeDirRefl" co1 co2 $\r
318     Refl ty2\r
319 \r
320 opt_trans_rule _ _ = Nothing\r
321 \r
322 opt_trans_pred :: Pred Coercion -> Pred Coercion -> Maybe (Pred Coercion)\r
323 opt_trans_pred (EqPred co1a co1b) (EqPred co2a co2b)\r
324   = Just (EqPred (opt_trans co1a co2a) (opt_trans co1b co2b))\r
325 opt_trans_pred (ClassP cls1 cos1) (ClassP cls2 cos2)\r
326   | cls1 == cls2\r
327   = Just (ClassP cls1 (opt_transList cos1 cos2))\r
328 opt_trans_pred (IParam n1 co1) (IParam n2 co2)\r
329   | n1 == n2\r
330   = Just (IParam n1 (opt_trans co1 co2))\r
331 opt_trans_pred _ _ = Nothing\r
332 \r
333 fireTransRule :: String -> Coercion -> Coercion -> Coercion -> Maybe Coercion\r
334 fireTransRule _rule _co1 _co2 res\r
335   = -- pprTrace ("Trans rule fired: " ++ _rule) (vcat [ppr _co1, ppr _co2, ppr res]) $\r
336     Just res\r
337 \r
338 -----------\r
339 wrapSym :: Bool -> Coercion -> Coercion\r
340 wrapSym sym co | sym       = SymCo co\r
341                | otherwise = co\r
342 \r
343 -----------\r
344 isAxiom_maybe :: Coercion -> Maybe (Bool, CoAxiom, [Coercion])\r
345 isAxiom_maybe (SymCo co) \r
346   | Just (sym, con, cos) <- isAxiom_maybe co\r
347   = Just (not sym, con, cos)\r
348 isAxiom_maybe (AxiomInstCo con cos)\r
349   = Just (False, con, cos)\r
350 isAxiom_maybe _ = Nothing\r
351 \r
352 matchAxiom :: Bool -- True = match LHS, False = match RHS\r
353            -> CoAxiom -> Coercion -> Maybe [Coercion]\r
354 -- If we succeed in matching, then *all the quantified type variables are bound*\r
355 -- E.g.   if tvs = [a,b], lhs/rhs = [b], we'll fail\r
356 matchAxiom sym (CoAxiom { co_ax_tvs = qtvs, co_ax_lhs = lhs, co_ax_rhs = rhs }) co\r
357   = case liftCoMatch (mkVarSet qtvs) (if sym then lhs else rhs) co of\r
358       Nothing    -> Nothing\r
359       Just subst -> allMaybes (map (liftCoSubstTyVar subst) qtvs)\r
360 \r
361 -------------\r
362 compatible_co :: Coercion -> Coercion -> Bool\r
363 -- Check whether (co1 . co2) will be well-kinded\r
364 compatible_co co1 co2\r
365   = x1 `eqType` x2              \r
366   where\r
367     Pair _ x1 = coercionKind co1\r
368     Pair x2 _ = coercionKind co2\r
369 \r
370 -------------\r
371 etaForAllCo_maybe :: Coercion -> Maybe (TyVar, Coercion)\r
372 -- Try to make the coercion be of form (forall tv. co)\r
373 etaForAllCo_maybe co\r
374   | Just (tv, r) <- splitForAllCo_maybe co\r
375   = Just (tv, r)\r
376 \r
377   | Pair ty1 ty2  <- coercionKind co\r
378   , Just (tv1, _) <- splitForAllTy_maybe ty1\r
379   , Just (tv2, _) <- splitForAllTy_maybe ty2\r
380   , tyVarKind tv1 `eqKind` tyVarKind tv2\r
381   = Just (tv1, mkInstCo co (mkTyVarTy tv1))\r
382 \r
383   | otherwise\r
384   = Nothing\r
385 \r
386 etaTyConAppCo_maybe :: TyCon -> Coercion -> Maybe [Coercion]\r
387 -- If possible, split a coercion \r
388 --       g :: T s1 .. sn ~ T t1 .. tn\r
389 -- into [ Nth 0 g :: s1~t1, ..., Nth (n-1) g :: sn~tn ] \r
390 etaTyConAppCo_maybe tc (TyConAppCo tc2 cos2)\r
391   = ASSERT( tc == tc2 ) Just cos2\r
392 \r
393 etaTyConAppCo_maybe tc co\r
394   | isDecomposableTyCon tc\r
395   , Pair ty1 ty2     <- coercionKind co\r
396   , Just (tc1, tys1) <- splitTyConApp_maybe ty1\r
397   , Just (tc2, tys2) <- splitTyConApp_maybe ty2\r
398   , tc1 == tc2\r
399   , let n = length tys1\r
400   = ASSERT( tc == tc1 ) \r
401     ASSERT( n == length tys2 )\r
402     Just (decomposeCo n co)  \r
403     -- NB: n might be <> tyConArity tc\r
404     -- e.g.   data family T a :: * -> *\r
405     --        g :: T a b ~ T c d\r
406 \r
407   | otherwise\r
408   = Nothing\r
409 \end{code}  \r