[Git][ghc/ghc][wip/rafl/hpc-tixdir] 3 commits: Add a coverage flavour transformer
by Florian Ragwitz (@rafl) 18 Oct '26
by Florian Ragwitz (@rafl) 18 Oct '26
18 Oct '26
Florian Ragwitz pushed to branch wip/rafl/hpc-tixdir at Glasgow Haskell Compiler / GHC
Commits:
84362071 by Florian Ragwitz at 2026-10-17T17:27:32-07:00
Add a coverage flavour transformer
- - - - -
d494ba4d by Florian Ragwitz at 2026-10-17T17:33:31-07:00
hpc: Write tix data in a more compact format
- - - - -
b44b9e40 by Florian Ragwitz at 2026-10-17T18:33:52-07:00
Collect coverage information
This is LLM slop.
- - - - -
4 changed files:
- .gitlab/ci.sh
- .gitlab/generate-ci/gen_ci.hs
- hadrian/src/Flavour.hs
- rts/Hpc.c
Changes:
=====================================
.gitlab/ci.sh
=====================================
@@ -54,6 +54,7 @@ Common Modes:
clean Clean the tree
shell Run an interactive shell with a configured build environment.
save_test_output Generate unexpected-test-output.tar.gz
+ save_hpc_coverage Generate ghc-hpc-coverage.tar.gz
save_cache Preserve the cabal cache
build_hadrian Build GHC via the Hadrian build system
test_hadrian Test GHC via the Hadrian build system
@@ -649,6 +650,13 @@ function install_bindist() {
}
function test_hadrian() {
+ if [[ "${BUILD_FLAVOUR:-}" == *+coverage* ]]; then
+ export HPCTIX2=1
+ # GHC invocations run in per-test working directories.
+ export HPCTIXDIR="$TOP/_build/ghc-tix"
+ mkdir -p "$HPCTIXDIR"
+ fi
+
check_msys2_deps _build/stage1/bin/ghc --version
check_release_build
@@ -898,6 +906,16 @@ function save_test_output() {
tar -czf unexpected-test-output.tar.gz unexpected-test-output
}
+function save_hpc_coverage() {
+ # Keep whatever has been generated even if the build or tests failed.
+ if [[ -d _build/ghc-hpc || -d _build/ghc-tix ]]; then
+ mkdir -p _build/ghc-hpc _build/ghc-tix
+ tar -czf ghc-hpc-coverage.tar.gz _build/ghc-hpc _build/ghc-tix
+ else
+ warn "No HPC coverage directories found"
+ fi
+}
+
function save_cache () {
info "Storing cabal cache from $CABAL_DIR to $CABAL_CACHE..."
rm -Rf "$CABAL_CACHE"
@@ -934,7 +952,8 @@ function clean() {
--exclude=ci_timings.txt \
--exclude=ghc-*.tar.xz \
--exclude=junit.xml \
- --exclude=unexpected-test-output.tar.gz
+ --exclude=unexpected-test-output.tar.gz \
+ --exclude=ghc-hpc-coverage.tar.gz
fi
}
=====================================
.gitlab/generate-ci/gen_ci.hs
=====================================
@@ -998,7 +998,21 @@ delVariable k j = j { jobVariables = MonoidalMap $ Map.delete k $ unMonoidalMap
-- | Make a normal validate CI job
validate :: Arch -> Opsys -> BuildConfig -> NamedJob Job
-validate = job
+validate arch opsys bc =
+ let NamedJob n j = job arch opsys bc
+ covered = setVariable "BUILD_FLAVOUR"
+ (flavourString (mkJobFlavour bc) ++ "+coverage") j
+ saveCoverage = (if opsys == Windows then "bash " else "")
+ ++ ".gitlab/ci.sh save_hpc_coverage"
+ in NamedJob
+ { name = n
+ , jobInfo = covered
+ { jobAfterScript = saveCoverage : jobAfterScript covered
+ , jobArtifacts = (jobArtifacts covered)
+ { artifactPaths = artifactPaths (jobArtifacts covered)
+ ++ ["ghc-hpc-coverage.tar.gz"] }
+ }
+ }
-- Nightly and release apply the FastCI configuration to all jobs so that they all run in
-- the pipeline (not conditional on the full-ci label)
=====================================
hadrian/src/Flavour.hs
=====================================
@@ -86,6 +86,7 @@ flavourTransformers = M.fromList
, "dump_stg" =: enableDumpStg
, "hash_unit_ids" =: enableHashUnitIds
, "hie_files" =: enableHieFiles
+ , "coverage" =: enableCoverage
]
where (=:) = (,)
@@ -383,6 +384,11 @@ enableHashUnitIds flavour = flavour { hashUnitIds = True }
enableHieFiles :: Flavour -> Flavour
enableHieFiles flavour = flavour { ghcHieFiles = (>= Stage1) }
+enableCoverage :: Flavour -> Flavour
+enableCoverage =
+ addArgs $ stage1 ? builder (Ghc CompileHs) ? packageOneOf [compiler, ghc] ?
+ pure ["-fhpc", "-hpcdir", "_build/ghc-hpc"]
+
-- | Build stage2 compiler with -fomit-interface-pragmas to reduce
-- recompilation.
omitPragmas :: Flavour -> Flavour
=====================================
rts/Hpc.c
=====================================
@@ -314,6 +314,57 @@ hs_hpc_module(char *modName,
}
}
+static void writeULEB128(FILE *f, StgWord64 value) {
+ do {
+ unsigned int byte = (unsigned int)(value & 0x7f);
+ value >>= 7;
+ if (value != 0) byte |= 0x80;
+ fputc(byte, f);
+ } while (value != 0);
+}
+
+static void writeLE32(FILE *f, StgWord32 value) {
+ for (unsigned int shift = 0; shift < 32; shift += 8)
+ fputc((int)((value >> shift) & 0xff), f);
+}
+
+static void writeTix2(FILE *f) {
+ if (f == NULL) return;
+
+ StgWord64 moduleCount = 0;
+ for (HpcModuleInfo *m = modules; m != NULL; m = m->next)
+ moduleCount++;
+
+ fwrite("HPCTIX\0", 1, 7, f);
+ writeULEB128(f, moduleCount);
+
+ for (HpcModuleInfo *m = modules; m != NULL; m = m->next) {
+ size_t nameLength = strlen(m->modName);
+ writeULEB128(f, (StgWord64)nameLength);
+ fwrite(m->modName, 1, nameLength, f);
+ writeLE32(f, m->hashNo);
+ writeULEB128(f, m->tickCount);
+
+ const StgWord64 *counts = m->tixArr;
+ StgWord32 i = 0;
+
+ while (i < m->tickCount) {
+ StgWord32 zeroStart = i;
+ while (i < m->tickCount && (counts == NULL || counts[i] == 0)) i++;
+ StgWord32 nonzeroStart = i;
+ while (i < m->tickCount && counts != NULL && counts[i] != 0) i++;
+ writeULEB128(f, nonzeroStart - zeroStart);
+ writeULEB128(f, i - nonzeroStart);
+ for (StgWord32 j = nonzeroStart; j < i; j++)
+ writeULEB128(f, counts[j]);
+ }
+ }
+
+ bool writeFailed = ferror(f) != 0;
+ if (fclose(f) != 0 || writeFailed)
+ failure("could not write binary .tix file");
+}
+
static void
writeTix(FILE *f) {
HpcModuleInfo *tmpModule;
@@ -387,7 +438,7 @@ static FILE *uniqueFile(const char *dir) {
FILE *f = NULL;
for (unsigned int i = 0; i < UINT_MAX; i++) {
snprintf(name, (size_t)len + 1, fmt, dir, prog_name, (int)hpc_pid, i);
- f = __rts_fopen(name, "wx");
+ f = __rts_fopen(name, "wbx");
if (f != NULL || errno != EEXIST)
break;
}
@@ -418,7 +469,8 @@ exitHpc(void) {
#endif
if (!is_subprocess && RtsFlags.HpcFlags.writeTixFile) {
FILE *f = tixDir != NULL ? uniqueFile(tixDir) : __rts_fopen(tixFilename, "w+");
- writeTix(f);
+ if (getenv("HPCTIX2")) writeTix2(f);
+ else writeTix(f);
}
freeStrHashTable(moduleHash, (void (*)(void *))freeHpcModuleInfo);
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/4b9e24a9bba79cdd9d4549290af5c7…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/4b9e24a9bba79cdd9d4549290af5c7…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
17 Oct '26
Marge Bot pushed to branch master at Glasgow Haskell Compiler / GHC
Commits:
7dedcf13 by Alan Zimmerman at 2026-10-16T19:03:17-04:00
EPA: Add TTG fields to FamilyInfo
This commit is a simple add, with unused extension fields.
It lays the groundwork for using them for exact print annotations
- - - - -
22 changed files:
- compiler/GHC/Hs/Decls.hs
- compiler/GHC/Hs/Utils.hs
- compiler/GHC/HsToCore/Quote.hs
- compiler/GHC/Iface/Ext/Ast.hs
- compiler/GHC/Parser.y
- compiler/GHC/Parser/PostProcess.hs
- compiler/GHC/Rename/Module.hs
- compiler/GHC/Tc/TyCl.hs
- compiler/GHC/ThToHs.hs
- compiler/Language/Haskell/Syntax/Decls.hs
- compiler/Language/Haskell/Syntax/Extension.hs
- testsuite/tests/haddock/should_compile_flag_haddock/T17544.stderr
- testsuite/tests/parser/should_compile/DumpParsedAst.stderr
- testsuite/tests/parser/should_compile/DumpRenamedAst.stderr
- testsuite/tests/parser/should_compile/KindSigs.stderr
- utils/check-exact/ExactPrint.hs
- utils/haddock/haddock-api/src/Haddock/Backends/Hoogle.hs
- utils/haddock/haddock-api/src/Haddock/Backends/LaTeX.hs
- utils/haddock/haddock-api/src/Haddock/Backends/Xhtml/Decl.hs
- utils/haddock/haddock-api/src/Haddock/Convert.hs
- utils/haddock/haddock-api/src/Haddock/Interface/Rename.hs
- utils/haddock/haddock-api/src/Haddock/Types.hs
Changes:
=====================================
compiler/GHC/Hs/Decls.hs
=====================================
@@ -482,12 +482,12 @@ instance NoAnn AnnSynDecl where
------------- Pretty printing FamilyDecls -----------
-pprFlavour :: FamilyInfo pass -> SDoc
-pprFlavour DataFamily = text "data"
-pprFlavour OpenTypeFamily = text "type"
+pprFlavour :: FamilyInfo (GhcPass pass) -> SDoc
+pprFlavour DataFamily {} = text "data"
+pprFlavour OpenTypeFamily {} = text "type"
pprFlavour (ClosedTypeFamily {}) = text "type"
-instance Outputable (FamilyInfo pass) where
+instance Outputable (FamilyInfo (GhcPass pass)) where
ppr info = pprFlavour info <+> text "family"
@@ -642,8 +642,8 @@ tyClDeclFlavour (ClassDecl {}) = ClassFlavour
tyClDeclFlavour (SynDecl {}) = TypeSynonymFlavour
tyClDeclFlavour (FamDecl { tcdFam = FamilyDecl { fdInfo = info }})
= case info of
- DataFamily -> OpenFamilyFlavour (IAmData DataType) Nothing
- OpenTypeFamily -> OpenFamilyFlavour IAmType Nothing
+ DataFamily {} -> OpenFamilyFlavour (IAmData DataType) Nothing
+ OpenTypeFamily {} -> OpenFamilyFlavour IAmType Nothing
ClosedTypeFamily {} -> ClosedTypeFamilyFlavour
tyClDeclFlavour (DataDecl { tcdDataDefn = HsDataDefn { dd_cons = nd } })
= case dataDefnConsNewOrData nd of
@@ -742,6 +742,11 @@ resultVariableName _ = Nothing
type instance XCInjectivityAnn (GhcPass _) = TokRarrow
type instance XXInjectivityAnn (GhcPass _) = DataConCantHappen
+type instance XDataFamily (GhcPass _) = NoExtField
+type instance XOpenTypeFamily (GhcPass _) = NoExtField
+type instance XClosedTypeFamily (GhcPass _) = NoExtField
+type instance XXFamilyInfo (GhcPass _) = DataConCantHappen
+
instance OutputableBndrId p
=> Outputable (FamilyDecl (GhcPass p)) where
ppr (FamilyDecl { fdInfo = info, fdLName = ltycon
@@ -768,7 +773,7 @@ instance OutputableBndrId p
hsep [ vbar, ppr lhs, arrow, hsep (map ppr rhs) ]
Nothing -> empty
(pp_where, pp_eqns) = case info of
- ClosedTypeFamily mb_eqns ->
+ ClosedTypeFamily _ mb_eqns ->
( text "where"
, case mb_eqns of
Nothing -> text ".."
=====================================
compiler/GHC/Hs/Utils.hs
=====================================
@@ -1543,15 +1543,15 @@ hsLTyClDeclBinders (L loc (DataDecl { tcdLName = (L _ name)
familyInfoTyConFlavour
:: Maybe tc -- ^ Just cls <=> this is an associated family of class cls
- -> FamilyInfo pass
+ -> FamilyInfo (GhcPass pass)
-> TyConFlavour tc
familyInfoTyConFlavour mb_parent_tycon info =
case info of
- DataFamily -> OpenFamilyFlavour (IAmData DataType) mb_parent_tycon
- OpenTypeFamily -> OpenFamilyFlavour IAmType mb_parent_tycon
- ClosedTypeFamily _ -> assert (isNothing mb_parent_tycon)
- -- See Note [Closed type family mb_parent_tycon]
- ClosedTypeFamilyFlavour
+ DataFamily _ -> OpenFamilyFlavour (IAmData DataType) mb_parent_tycon
+ OpenTypeFamily _ -> OpenFamilyFlavour IAmType mb_parent_tycon
+ ClosedTypeFamily _ _ -> assert (isNothing mb_parent_tycon)
+ -- See Note [Closed type family mb_parent_tycon]
+ ClosedTypeFamilyFlavour
-------------------
hsForeignDeclsBinders :: forall p a. (UnXRec (GhcPass p), IsSrcSpanAnn p a)
=====================================
compiler/GHC/HsToCore/Quote.hs
=====================================
@@ -554,19 +554,19 @@ repFamilyDecl decl@(L loc (FamilyDecl { fdInfo = info
; dec <- addQTyVarBinds ReuseBoundNames tvs $ \bndrs ->
addSimpleTyVarBinds ReuseBoundNames (maybeToList res_tv) $
case info of
- ClosedTypeFamily Nothing ->
+ ClosedTypeFamily _ Nothing ->
notHandled (ThAbstractClosedTypeFamily decl)
- ClosedTypeFamily (Just eqns) ->
+ ClosedTypeFamily _ (Just eqns) ->
do { eqns1 <- mapM (repTyFamEqn . unLoc) eqns
; eqns2 <- coreListM tySynEqnTyConOcc eqns1
; result <- repFamilyResultSig resultSig
; inj <- repInjectivityAnn injectivity
; repClosedFamilyD tc1 bndrs result inj eqns2 }
- OpenTypeFamily ->
+ OpenTypeFamily _ ->
do { result <- repFamilyResultSig resultSig
; inj <- repInjectivityAnn injectivity
; repOpenFamilyD tc1 bndrs result inj }
- DataFamily ->
+ DataFamily _ ->
do { kind <- repFamilyResultSigToMaybeKind resultSig
; repDataFamilyD tc1 bndrs kind }
; return (locA loc, dec)
=====================================
compiler/GHC/Iface/Ext/Ast.hs
=====================================
@@ -1669,7 +1669,7 @@ instance ToHie (LocatedA (FamilyDecl GhcRn)) where
injSpan = maybe NoScope (mkScope . getLocA) inj
instance ToHie (FamilyInfo GhcRn) where
- toHie (ClosedTypeFamily (Just eqns)) = concatM $
+ toHie (ClosedTypeFamily _ (Just eqns)) = concatM $
[ concatMapM (locOnly . getLocA) eqns
, toHie $ map go eqns
]
=====================================
compiler/GHC/Parser.y
=====================================
@@ -1389,7 +1389,7 @@ ty_decl :: { LTyClDecl GhcPs }
-- data/newtype family
| 'data' 'family' type opt_datafam_kind_sig
{% do { let { tdcolon = fst $ unLoc $4 }
- ; mkFamDecl (comb4 $1 $2 $3 $4) DataFamily TopLevel $3
+ ; mkFamDecl (comb4 $1 $2 $3 $4) (DataFamily noExtField) TopLevel $3
(snd $ unLoc $4) Nothing
(AnnFamilyDecl [] [] noAnn (epTok $1) (epTok $2) tdcolon noAnn noAnn noAnn noAnn noAnn noAnn) }}
@@ -1523,10 +1523,10 @@ inj_varids :: { Located [LocatedN RdrName] }
-- Closed type families
where_type_family :: { Located ((EpToken "where", (EpToken "{", EpToken "..", EpToken "}")),FamilyInfo GhcPs) }
- : {- empty -} { noLoc (noAnn,OpenTypeFamily) }
+ : {- empty -} { noLoc (noAnn,OpenTypeFamily noExtField) }
| 'where' ty_fam_inst_eqn_list
{ sLL $1 $> ((epTok $1,(fst $ unLoc $2))
- ,ClosedTypeFamily (fmap reverse $ snd $ unLoc $2)) }
+ , ClosedTypeFamily noExtField (fmap reverse $ snd $ unLoc $2)) }
ty_fam_inst_eqn_list :: { Located ((EpToken "{", EpToken "..", EpToken "}"),Maybe [LTyFamInstEqn GhcPs]) }
: '{' ty_fam_inst_eqns '}' { sLL $1 $> ((epTok $1,noAnn, epTok $3)
@@ -1578,7 +1578,7 @@ at_decl_cls :: { LHsDecl GhcPs }
: -- data family declarations, with optional 'family' keyword
'data' opt_family type opt_datafam_kind_sig
{% do { let { tdcolon = fst $ unLoc $4 }
- ; liftM mkTyClD (mkFamDecl (comb3 $1 $3 $4) DataFamily NotTopLevel $3
+ ; liftM mkTyClD (mkFamDecl (comb3 $1 $3 $4) (DataFamily noExtField) NotTopLevel $3
(snd $ unLoc $4) Nothing
(AnnFamilyDecl [] [] noAnn (epTok $1) $2 tdcolon noAnn noAnn noAnn noAnn noAnn noAnn)) }}
@@ -1587,14 +1587,14 @@ at_decl_cls :: { LHsDecl GhcPs }
| 'type' type opt_at_kind_inj_sig
{% do { let { (tdcolon, tequal, tvbar) = fst $ unLoc $3 }
; liftM mkTyClD
- (mkFamDecl (comb3 $1 $2 $3) OpenTypeFamily NotTopLevel $2
+ (mkFamDecl (comb3 $1 $2 $3) (OpenTypeFamily noExtField) NotTopLevel $2
(fst . snd $ unLoc $3)
(snd . snd $ unLoc $3)
(AnnFamilyDecl [] [] (epTok $1) noAnn noAnn tdcolon tequal tvbar noAnn noAnn noAnn noAnn)) }}
| 'type' 'family' type opt_at_kind_inj_sig
{% do { let { (tdcolon, tequal, tvbar) = fst $ unLoc $4 }
; liftM mkTyClD
- (mkFamDecl (comb3 $1 $3 $4) OpenTypeFamily NotTopLevel $3
+ (mkFamDecl (comb3 $1 $3 $4) (OpenTypeFamily noExtField) NotTopLevel $3
(fst . snd $ unLoc $4)
(snd . snd $ unLoc $4)
(AnnFamilyDecl [] [] (epTok $1) noAnn (epTok $2) tdcolon tequal tvbar noAnn noAnn noAnn noAnn)) }}
=====================================
compiler/GHC/Parser/PostProcess.hs
=====================================
@@ -384,8 +384,8 @@ mkFamDecl loc info topLevel lhs ksig injAnn annsIn
, fdInjectivityAnn = injAnn }))) }
where
equals_or_where = case info of
- DataFamily -> empty
- OpenTypeFamily -> empty
+ DataFamily {} -> empty
+ OpenTypeFamily {} -> empty
ClosedTypeFamily {} -> whereDots
mkSpliceDecl :: LHsExpr GhcPs -> (LHsDecl GhcPs)
=====================================
compiler/GHC/Rename/Module.hs
=====================================
@@ -2437,15 +2437,15 @@ rnFamDecl mb_cls (FamilyDecl { fdLName = tycon, fdTyVars = tyvars
----------------------
rn_info :: FamilyInfo GhcPs -> RnM (FamilyInfo GhcRn, FreeNames)
- rn_info (ClosedTypeFamily (Just eqns))
+ rn_info (ClosedTypeFamily x (Just eqns))
= do { (eqns', fvs)
<- rnList (rnTyFamInstEqn (NonAssocTyFamEqn ClosedTyFam)) eqns
-- no class context
- ; return (ClosedTypeFamily (Just eqns'), fvs) }
- rn_info (ClosedTypeFamily Nothing)
- = return (ClosedTypeFamily Nothing, emptyFNs)
- rn_info OpenTypeFamily = return (OpenTypeFamily, emptyFNs)
- rn_info DataFamily = return (DataFamily, emptyFNs)
+ ; return (ClosedTypeFamily x (Just eqns'), fvs) }
+ rn_info (ClosedTypeFamily x Nothing)
+ = return (ClosedTypeFamily x Nothing, emptyFNs)
+ rn_info (OpenTypeFamily x) = return (OpenTypeFamily x, emptyFNs)
+ rn_info (DataFamily x) = return (DataFamily x, emptyFNs)
rnFamResultSig :: HsDocContext
-> FamilyResultSig GhcPs
=====================================
compiler/GHC/Tc/TyCl.hs
=====================================
@@ -2196,7 +2196,7 @@ kcTyClDecl (FamDecl _ (FamilyDecl { fdInfo = fd_info })) fam_tc
-- closed type families look at their equations, but other families don't
-- do anything here
= case fd_info of
- ClosedTypeFamily (Just eqns) -> mapM_ (kcTyFamInstEqn fam_tc) eqns
+ ClosedTypeFamily _ (Just eqns) -> mapM_ (kcTyFamInstEqn fam_tc) eqns
_ -> return ()
-------------------
@@ -3387,7 +3387,7 @@ tcFamDecl1 parent (FamilyDecl { fdInfo = fam_info
, fdLName = tc_lname@(L _ tc_name)
, fdResultSig = L _ sig
, fdInjectivityAnn = inj })
- | DataFamily <- fam_info
+ | DataFamily _ <- fam_info
= bindTyClTyVarsAndZonk tc_name $ \ kind tc_bndrs nb_eta res_kind -> do
{ traceTc "tcFamDecl1 data family:" (ppr tc_name)
; checkFamFlag tc_name
@@ -3413,7 +3413,7 @@ tcFamDecl1 parent (FamilyDecl { fdInfo = fam_info
parent inj
; return (tycon, []) }
- | OpenTypeFamily <- fam_info
+ | OpenTypeFamily _ <- fam_info
= bindTyClTyVarsAndZonk tc_name $ \ kind tc_bndrs _nb_eta res_kind -> do
{ traceTc "tcFamDecl1 open type family:" (ppr tc_name)
; checkFamFlag tc_name
@@ -3424,7 +3424,7 @@ tcFamDecl1 parent (FamilyDecl { fdInfo = fam_info
parent inj'
; return (tycon, []) }
- | ClosedTypeFamily mb_eqns <- fam_info
+ | ClosedTypeFamily _ mb_eqns <- fam_info
= -- Closed type families are a little tricky, because they contain the definition
-- of both the type family and the equations for a CoAxiom.
do { traceTc "tcFamDecl1 Closed type family:" (ppr tc_name)
=====================================
compiler/GHC/ThToHs.hs
=====================================
@@ -373,7 +373,7 @@ cvtDec (DataFamilyD tc tvs kind)
= do { (_, tc', tvs') <- cvt_tycl_hdr [] tc tvs
; result <- cvtMaybeKindToFamilyResultSig kind
; returnJustLA $ TyClD noExtField $ FamDecl noExtField $
- FamilyDecl noAnn DataFamily TopLevel tc' tvs' Prefix result Nothing }
+ FamilyDecl noAnn (DataFamily noExtField) TopLevel tc' tvs' Prefix result Nothing }
cvtDec (DataInstD ctxt bndrs tys ksig constrs derivs)
= do { (ctxt', tc', bndrs', typats') <- cvt_datainst_hdr ctxt bndrs tys
@@ -427,14 +427,14 @@ cvtDec (TySynInstD eqn)
cvtDec (OpenTypeFamilyD head)
= do { (tc', tyvars', result', injectivity') <- cvt_tyfam_head head
; returnJustLA $ TyClD noExtField $ FamDecl noExtField $
- FamilyDecl noAnn OpenTypeFamily TopLevel tc' tyvars' Prefix result' injectivity'
+ FamilyDecl noAnn (OpenTypeFamily noExtField) TopLevel tc' tyvars' Prefix result' injectivity'
}
cvtDec (ClosedTypeFamilyD head eqns)
= do { (tc', tyvars', result', injectivity') <- cvt_tyfam_head head
; eqns' <- mapM cvtTySynEqn eqns
; returnJustLA $ TyClD noExtField $ FamDecl noExtField $
- FamilyDecl noAnn (ClosedTypeFamily (Just eqns')) TopLevel tc' tyvars' Prefix
+ FamilyDecl noAnn (ClosedTypeFamily noExtField (Just eqns')) TopLevel tc' tyvars' Prefix
result' injectivity' }
cvtDec (TH.RoleAnnotD tc roles)
=====================================
compiler/Language/Haskell/Syntax/Decls.hs
=====================================
@@ -503,15 +503,15 @@ isFamilyDecl _other = False
-- | type family declaration
isTypeFamilyDecl :: TyClDecl pass -> Bool
isTypeFamilyDecl (FamDecl _ (FamilyDecl { fdInfo = info })) = case info of
- OpenTypeFamily -> True
+ OpenTypeFamily {} -> True
ClosedTypeFamily {} -> True
_ -> False
isTypeFamilyDecl _ = False
-- | open type family info
isOpenTypeFamilyInfo :: FamilyInfo pass -> Bool
-isOpenTypeFamilyInfo OpenTypeFamily = True
-isOpenTypeFamilyInfo _ = False
+isOpenTypeFamilyInfo OpenTypeFamily {} = True
+isOpenTypeFamilyInfo _ = False
-- | closed type family info
isClosedTypeFamilyInfo :: FamilyInfo pass -> Bool
@@ -520,7 +520,7 @@ isClosedTypeFamilyInfo _ = False
-- | data family declaration
isDataFamilyDecl :: TyClDecl pass -> Bool
-isDataFamilyDecl (FamDecl _ (FamilyDecl { fdInfo = DataFamily })) = True
+isDataFamilyDecl (FamDecl _ (FamilyDecl { fdInfo = DataFamily _ })) = True
isDataFamilyDecl _other = False
-- Dealing with names
@@ -771,11 +771,12 @@ data InjectivityAnn pass
| XInjectivityAnn !(XXInjectivityAnn pass)
data FamilyInfo pass
- = DataFamily
- | OpenTypeFamily
+ = DataFamily (XDataFamily pass)
+ | OpenTypeFamily (XOpenTypeFamily pass)
-- | 'Nothing' if we're in an hs-boot file and the user
-- said "type family Foo x where .."
- | ClosedTypeFamily (Maybe [LTyFamInstEqn pass])
+ | ClosedTypeFamily (XClosedTypeFamily pass) (Maybe [LTyFamInstEqn pass])
+ | XFamilyInfo !(XXFamilyInfo pass)
{- Note [Closed type family mb_parent_tycon]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
=====================================
compiler/Language/Haskell/Syntax/Extension.hs
=====================================
@@ -473,6 +473,13 @@ type family XXRoleAnnotDecl x
type family XCInjectivityAnn x
type family XXInjectivityAnn x
+-- -------------------------------------
+-- FamilyInfo type families
+type family XDataFamily x
+type family XOpenTypeFamily x
+type family XClosedTypeFamily x
+type family XXFamilyInfo x
+
-- =====================================================================
-- Type families for the HsModule extension points
=====================================
testsuite/tests/haddock/should_compile_flag_haddock/T17544.stderr
=====================================
@@ -930,7 +930,8 @@
(EpTok
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
- (DataFamily)
+ (DataFamily
+ (NoExtField))
(NotTopLevel)
(L
(EpAnn
@@ -1325,7 +1326,8 @@
(EpTok
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
- (DataFamily)
+ (DataFamily
+ (NoExtField))
(NotTopLevel)
(L
(EpAnn
@@ -1720,7 +1722,8 @@
(EpTok
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
- (DataFamily)
+ (DataFamily
+ (NoExtField))
(NotTopLevel)
(L
(EpAnn
@@ -2115,7 +2118,8 @@
(EpTok
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
- (DataFamily)
+ (DataFamily
+ (NoExtField))
(NotTopLevel)
(L
(EpAnn
@@ -2510,7 +2514,8 @@
(EpTok
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
- (DataFamily)
+ (DataFamily
+ (NoExtField))
(NotTopLevel)
(L
(EpAnn
@@ -2905,7 +2910,8 @@
(EpTok
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
- (DataFamily)
+ (DataFamily
+ (NoExtField))
(NotTopLevel)
(L
(EpAnn
=====================================
testsuite/tests/parser/should_compile/DumpParsedAst.stderr
=====================================
@@ -364,6 +364,7 @@
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
(ClosedTypeFamily
+ (NoExtField)
(Just
[(L
(EpAnn
@@ -1148,6 +1149,7 @@
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
(ClosedTypeFamily
+ (NoExtField)
(Just
[(L
(EpAnn
@@ -1545,7 +1547,8 @@
(EpTok
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
- (DataFamily)
+ (DataFamily
+ (NoExtField))
(TopLevel)
(L
(EpAnn
=====================================
testsuite/tests/parser/should_compile/DumpRenamedAst.stderr
=====================================
@@ -311,6 +311,7 @@
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
(ClosedTypeFamily
+ (NoExtField)
(Just
[(L
(EpAnn
@@ -798,7 +799,8 @@
(EpTok
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
- (DataFamily)
+ (DataFamily
+ (NoExtField))
(TopLevel)
(L
(EpAnn
@@ -1183,6 +1185,7 @@
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
(ClosedTypeFamily
+ (NoExtField)
(Just
[(L
(EpAnn
@@ -1766,7 +1769,8 @@
(EpTok
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
- (OpenTypeFamily)
+ (OpenTypeFamily
+ (NoExtField))
(NotTopLevel)
(L
(EpAnn
=====================================
testsuite/tests/parser/should_compile/KindSigs.stderr
=====================================
@@ -113,6 +113,7 @@
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
(ClosedTypeFamily
+ (NoExtField)
(Just
[(L
(EpAnn
=====================================
utils/check-exact/ExactPrint.hs
=====================================
@@ -3844,7 +3844,7 @@ instance ExactPrint (FamilyDecl GhcPs) where
return (vb', Just inj')
(w', oc', dd', cc', info') <-
case info of
- ClosedTypeFamily mb_eqns -> do
+ ClosedTypeFamily x mb_eqns -> do
w' <- markEpToken w
oc' <- markEpToken oc
(dd', mb_eqns') <-
@@ -3856,7 +3856,7 @@ instance ExactPrint (FamilyDecl GhcPs) where
eqns' <- mapM markAnnotated eqns
return (dd, Just eqns')
cc' <- markEpToken cc
- return (w',oc',dd',cc', ClosedTypeFamily mb_eqns')
+ return (w',oc',dd',cc', ClosedTypeFamily x mb_eqns')
_ -> return (w,oc,dd,cc, info)
return (FamilyDecl { fdExt = AnnFamilyDecl [] [] t' d' f' dc' eq' vb' w' oc' dd' cc'
, fdInfo = info'
@@ -3890,8 +3890,8 @@ instance ExactPrint (FamilyDecl GhcPs) where
exactFlavour :: (Monad m, Monoid w) => (EpToken "data", EpToken "type") -> FamilyInfo GhcPs -> EP w m (EpToken "data", EpToken "type")
-exactFlavour (td,tt) DataFamily = (\td' -> (td',tt)) <$> markEpToken td
-exactFlavour (td,tt) OpenTypeFamily = (td,) <$> markEpToken tt
+exactFlavour (td,tt) DataFamily {} = (\td' -> (td',tt)) <$> markEpToken td
+exactFlavour (td,tt) OpenTypeFamily {} = (td,) <$> markEpToken tt
exactFlavour (td,tt) (ClosedTypeFamily {}) = (td,) <$> markEpToken tt
-- ---------------------------------------------------------------------
=====================================
utils/haddock/haddock-api/src/Haddock/Backends/Hoogle.hs
=====================================
@@ -254,7 +254,7 @@ ppFam sDocContext decl@(FamilyDecl{fdInfo = info}) =
decl' = case info of
-- We don't need to print out a closed type family's equations
-- for Hoogle, so pretend it doesn't have any.
- ClosedTypeFamily{} -> decl{fdInfo = OpenTypeFamily}
+ ClosedTypeFamily{} -> decl{fdInfo = OpenTypeFamily noExtField}
_ -> decl
ppInstance :: DynFlags -> UnitState -> ClsInst -> [String]
=====================================
utils/haddock/haddock-api/src/Haddock/Backends/LaTeX.hs
=====================================
@@ -373,11 +373,11 @@ ppFamDecl associated doc instances decl@(FamDecl{}) unicode =
body = Maybe.catMaybes [familyEqns, documentationToLaTeX doc]
whereBit = case fdInfo (tcdFam decl) of
- ClosedTypeFamily _ -> keyword "where"
+ ClosedTypeFamily _ _ -> keyword "where"
_ -> empty
familyEqns
- | FamilyDecl{fdInfo = ClosedTypeFamily (Just eqns)} <- tcdFam decl
+ | FamilyDecl{fdInfo = ClosedTypeFamily _ (Just eqns)} <- tcdFam decl
, not (null eqns) =
Just
( text "\\haddockbeginargs"
@@ -429,9 +429,9 @@ ppFamHeader
famly leader <+> famName <+> famSig <+> injAnn
where
leader = case info of
- OpenTypeFamily -> keyword "type"
- ClosedTypeFamily _ -> keyword "type"
- DataFamily -> keyword "data"
+ OpenTypeFamily _ -> keyword "type"
+ ClosedTypeFamily _ _ -> keyword "type"
+ DataFamily _ -> keyword "data"
famly
| associated = id
=====================================
utils/haddock/haddock-api/src/Haddock/Backends/Xhtml/Decl.hs
=====================================
@@ -548,7 +548,7 @@ ppFamDecl summary associated links instances fixities loc doc decl splice unicod
ppFamHeader summary associated decl unicode qual <+> ppFixities fixities qual
instancesBit
- | FamilyDecl{fdInfo = ClosedTypeFamily mb_eqns} <- decl
+ | FamilyDecl{fdInfo = ClosedTypeFamily _ mb_eqns} <- decl
, not summary =
subEquations pkg qual $ map (ppFamDeclEqn . unLoc) $ Maybe.fromMaybe [] mb_eqns
| otherwise =
@@ -603,7 +603,7 @@ ppFamHeader
]
where
whereBit = case info of
- ClosedTypeFamily _ -> keyword "where ..."
+ ClosedTypeFamily _ _ -> keyword "where ..."
_ -> noHtml
injAnn = case injectivity of
@@ -622,9 +622,9 @@ ppFamilyLeader :: Bool -> FamilyInfo DocNameI -> Html
ppFamilyLeader assoc info = keyword (typ ++ if assoc then "" else " family")
where
typ = case info of
- OpenTypeFamily -> "type"
- ClosedTypeFamily _ -> "type"
- DataFamily -> "data"
+ OpenTypeFamily _ -> "type"
+ ClosedTypeFamily _ _ -> "type"
+ DataFamily _ -> "data"
-- | Print the signature attached to a family
ppResultSig :: FamilyResultSig DocNameI -> Unicode -> Qualification -> Html
=====================================
utils/haddock/haddock-api/src/Haddock/Convert.hs
=====================================
@@ -306,20 +306,20 @@ synifyTyCon _prr _coax tc
| Just flav <- famTyConFlav_maybe tc =
case flav of
DataFamilyTyCon{} ->
- mkFamDecl DataFamily
- OpenTypeFamilyTyCon -> mkFamDecl OpenTypeFamily
+ mkFamDecl (DataFamily noExtField)
+ OpenTypeFamilyTyCon -> mkFamDecl (OpenTypeFamily noExtField)
ClosedTypeFamilyTyCon ctf ->
case ctf of
CTF mb
| Just (CoAxiom{co_ax_branches = branches}) <- mb
-> mkFamDecl $
- ClosedTypeFamily $
+ ClosedTypeFamily noExtField $
Just $
map (noLocA . synifyAxBranch tc) (fromBranches branches)
| otherwise
- -> mkFamDecl $ ClosedTypeFamily $ Just []
- CTF_BuiltIn {} -> mkFamDecl $ ClosedTypeFamily $ Just []
- CTF_Abstract -> mkFamDecl $ ClosedTypeFamily Nothing
+ -> mkFamDecl $ ClosedTypeFamily noExtField $ Just []
+ CTF_BuiltIn {} -> mkFamDecl $ ClosedTypeFamily noExtField $ Just []
+ CTF_Abstract -> mkFamDecl $ ClosedTypeFamily noExtField Nothing
where
resultVar = tyConFamilyResVar_maybe tc
mkFamDecl i =
=====================================
utils/haddock/haddock-api/src/Haddock/Interface/Rename.hs
=====================================
@@ -686,12 +686,12 @@ renameFamilyDecl
)
renameFamilyInfo :: FamilyInfo GhcRn -> RnM (FamilyInfo DocNameI)
-renameFamilyInfo DataFamily = return DataFamily
-renameFamilyInfo OpenTypeFamily = return OpenTypeFamily
-renameFamilyInfo (ClosedTypeFamily eqns) =
+renameFamilyInfo (DataFamily x) = return (DataFamily x)
+renameFamilyInfo (OpenTypeFamily x) = return (OpenTypeFamily x)
+renameFamilyInfo (ClosedTypeFamily x eqns) =
do
eqns' <- mapM (mapM (mapM renameTyFamInstEqn)) eqns
- return $ ClosedTypeFamily eqns'
+ return $ ClosedTypeFamily x eqns'
renameDataDefn :: HsDataDefn GhcRn -> RnM (HsDataDefn DocNameI)
renameDataDefn
=====================================
utils/haddock/haddock-api/src/Haddock/Types.hs
=====================================
@@ -1036,6 +1036,11 @@ type instance XSplicePat DocNameI = DataConCantHappen
type instance XCInjectivityAnn DocNameI = NoExtField
+type instance XDataFamily DocNameI = NoExtField
+type instance XOpenTypeFamily DocNameI = NoExtField
+type instance XClosedTypeFamily DocNameI = NoExtField
+type instance XXFamilyInfo DocNameI = DataConCantHappen
+
type instance XCFunDep DocNameI = NoExtField
type instance XCTyFamInstDecl DocNameI = NoExtField
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/7dedcf135eeab1598af85bf319a398b…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/7dedcf135eeab1598af85bf319a398b…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
Marge Bot pushed to branch master at Glasgow Haskell Compiler / GHC
Commits:
8c947573 by Simon Peyton Jones at 2026-10-16T13:11:53+01:00
Improve exprOkForSpeculation
Fixes #27910, which exposed an infelicity in exprOkForSpeculation
The new story is carefully described in new Note [exprOkForSpeculation],
esp (a-c) and (EOKS1).
- - - - -
6 changed files:
- compiler/GHC/Core.hs
- compiler/GHC/Core/Type.hs
- compiler/GHC/Core/Utils.hs
- + testsuite/tests/simplCore/should_compile/T27910.hs
- + testsuite/tests/simplCore/should_compile/T27910.stderr
- testsuite/tests/simplCore/should_compile/all.T
Changes:
=====================================
compiler/GHC/Core.hs
=====================================
@@ -490,7 +490,7 @@ This is a well-kinded type, in an environment-based scheme. But `typeKind`
will panic, because the kind of the body of a forall must not mention
the forall'd variable (and the inner forall's body appears to do so).
-It might be possible to make `exprType` and `typeKind`` more complicated, so that
+It might be possible to make `exprType` and `typeKind` more complicated, so that
they do renaming on the fly. But instead we impose
INVARIANT (NoTypeShadowing):
=====================================
compiler/GHC/Core/Type.hs
=====================================
@@ -55,7 +55,7 @@ module GHC.Core.Type (
splitForAllForAllTyBinders, splitForAllForAllTyBinder_maybe,
splitForAllTyCoVar_maybe, splitForAllTyCoVar,
splitForAllTyVar_maybe, splitForAllCoVar_maybe,
- splitPiTy_maybe, splitPiTy, splitPiTys, collectPiTyBinders,
+ splitPiTy_maybe, splitPiTy, splitPiTys, splitUninstantiatedValArgTys,
getRuntimeArgTys,
mkTyConBindersPreferAnon,
mkPiTy, mkPiTys,
@@ -263,7 +263,6 @@ import GHC.Utils.Monad.StrictReader
import GHC.Data.FastString
import GHC.Data.Maybe ( orElse, isJust )
-import GHC.List (build)
-- $type_classification
-- #type_classification#
@@ -1599,17 +1598,20 @@ splitPiTys ty = split ty ty []
split orig_ty ty bs | Just ty' <- coreView ty = split orig_ty ty' bs
split orig_ty _ bs = (reverse bs, orig_ty)
-collectPiTyBinders :: Type -> [PiTyBinder]
-collectPiTyBinders ty = build $ \c n ->
- let
- split (ForAllTy b res) = Named b `c` split res
- split (FunTy { ft_af = af, ft_mult = w, ft_arg = arg, ft_res = res })
- = Anon (Scaled w arg) af `c` split res
- split ty | Just ty' <- coreView ty = split ty'
- split _ = n
- in
- split ty
-{-# INLINE collectPiTyBinders #-}
+splitUninstantiatedValArgTys :: Type -> [Type]
+-- This function takes a type apart, returning all its /value/
+-- argument types (including (forall (co::t1~t2).t)
+-- doing no instantiation at all.
+-- E.g. splitUinstantiatedValArgTys (forall a. a -> Int -> T a)
+-- returns [a, Int]
+-- It's a pretty specialised function, hence its long name
+splitUninstantiatedValArgTys ty = go ty
+ where
+ go (ForAllTy (Bndr b _) res) | isCoVar b = varType b : go res
+ | otherwise = go res
+ go (FunTy { ft_arg = arg, ft_res = res }) = arg : go res
+ go ty | Just ty' <- coreView ty = go ty'
+ go _ = []
-- | Extracts a list of run-time arguments from a function type,
-- looking through newtypes to the right of arrows.
=====================================
compiler/GHC/Core/Utils.hs
=====================================
@@ -2207,6 +2207,8 @@ fun_always_ok _ = True
-- | A special version of 'exprOkForSpeculation' used during
-- Note [Speculative evaluation]. When the predicate arg `fun_ok` returns False
-- for `b`, then `b` is never considered ok-for-spec.
+--
+-- This is the whole reason for the fun_ok arg to expr_ok.
exprOkForSpecEval :: (Id -> Bool) -> CoreExpr -> Bool
exprOkForSpecEval fun_ok = expr_ok fun_ok primOpOkForSpeculation
@@ -2240,10 +2242,9 @@ expr_ok fun_ok primop_ok (Case scrut bndr _ alts)
&& altsAreExhaustive alts
expr_ok fun_ok primop_ok other_expr
- | (expr, args) <- collectArgs other_expr
+ | (expr, val_args) <- collectValArgs other_expr
= case stripTicksTopE (not . tickishCounts) expr of
- Var f ->
- app_ok fun_ok primop_ok f args
+ Var f -> app_ok fun_ok primop_ok f val_args
-- 'LitRubbish' is the only literal that can occur in the head of an
-- application and will not be matched by the above case (Var /= Lit).
@@ -2258,9 +2259,10 @@ expr_ok fun_ok primop_ok other_expr
-----------------------------
app_ok :: (Id -> Bool) -> (PrimOp -> Bool) -> Id -> [CoreArg] -> Bool
-app_ok fun_ok primop_ok fun args
+app_ok fun_ok primop_ok fun val_args
| not (fun_ok fun)
- = False -- This code path is only taken for Note [Speculative evaluation]
+ = False -- This code path is only taken for exprOkForSpecEval
+ -- See Note [Speculative evaluation]
| idArity fun > n_val_args
-- Partial application: just check passing the arguments is OK
@@ -2281,17 +2283,18 @@ app_ok fun_ok primop_ok fun args
ClassOpId _ is_terminating_result
| is_terminating_result -- See Note [exprOkForSpeculation and type classes]
- -> assertPpr (n_val_args == 1) (ppr fun $$ ppr args) $
+ -> assertPpr (n_val_args == 1) (ppr fun $$ ppr val_args) $
True
-- assert: terminating result type => can't be applied;
-- c.f the _other case below
PrimOpId op _
| primOpIsDiv op
- , Lit divisor <- last args
+ , Lit divisor <- last val_args
-- there can be 2 args (most div primops) or 3 args
-- (WordQuotRem2Op), hence the use of last/init
- -> not (isZeroLit divisor) && all (expr_ok fun_ok primop_ok) (init args)
+ -> not (isZeroLit divisor) &&
+ all ok_for_spec (init val_args)
-- Special case for dividing operations that fail
-- In general they are NOT ok-for-speculation
-- (which primop_ok will catch), but they ARE OK
@@ -2300,12 +2303,14 @@ app_ok fun_ok primop_ok fun args
-- can get rid of a thunk in an inner loop
| otherwise -> primop_ok op && args_ok
+ -- Assumes that the primop does not evaluate its
+ -- definitely-lifted arguments
_other -- Unlifted and terminating types;
-- Also c.f. the Var case of exprIsHNF
| isTerminatingType fun_ty -- See Note [exprOkForSpeculation and type classes]
|| definitelyUnliftedType fun_ty
- -> assertPpr (n_val_args == 0) (ppr fun $$ ppr args)
+ -> assertPpr (n_val_args == 0) (ppr fun $$ ppr val_args)
True -- Both terminating types (e.g. Eq a), and unlifted types (e.g. Int#)
-- are non-functions and so will have no value args. The assert is
-- just to check this.
@@ -2321,32 +2326,43 @@ app_ok fun_ok primop_ok fun args
-- for evaluated-ness of the fun;
-- see Note [exprOkForSpeculation and evaluated variables]
where
- fun_ty = idType fun
- n_val_args = valArgCount args
- (arg_tys, _) = splitPiTys fun_ty
+ ok_for_spec = expr_ok fun_ok primop_ok -- Used for recursive calls
+
+ fun_ty = idType fun
+ n_val_args = length val_args
+ val_arg_tys = splitUninstantiatedValArgTys fun_ty
+ -- val_arg_tys are /uninstantiated/; see (EOKS1)
-- Even if a function call itself is OK, any unlifted
-- args are still evaluated eagerly and must be checked
- args_ok = all2Prefix arg_ok arg_tys args
- arg_ok :: PiTyVarBinder -> CoreExpr -> Bool
- arg_ok (Named _) _ = True -- A type argument
- arg_ok (Anon ty _) arg -- A term argument
- | definitelyLiftedType (scaledThing ty)
- = True -- lifted args are not evaluated eagerly
- | otherwise
- = expr_ok fun_ok primop_ok arg
+ -- arg_ok bndr arg = field_ok bndr NotMarkedStrict arg
+ -- See Note [exprOkForSpeculation] (a,b)
+ args_ok = all2Prefix arg_ok val_arg_tys val_args
+ arg_ok :: Type -> CoreExpr -> Bool
+ arg_ok arg_ty arg = ok_for_spec arg || definitely_lifted arg_ty arg
-- Used for strict DataCon worker arguments
-- See (SFC1) of Note [Strict fields in Core]
- fields_ok str_marks = all3Prefix field_ok arg_tys str_marks args
- field_ok :: PiTyVarBinder -> StrictnessMark -> CoreExpr -> Bool
- field_ok (Named _) _ _ = True
- field_ok (Anon ty _) str arg
- | NotMarkedStrict <- str -- iff it's a lazy field
- , definitelyLiftedType (scaledThing ty) -- and its type is lifted
- = True -- then the worker app does not eval
- | otherwise
- = expr_ok fun_ok primop_ok arg
+ -- See Note [exprOkForSpeculation] (a,b)
+ fields_ok str_marks = all3Prefix field_ok val_arg_tys str_marks val_args
+ field_ok :: Type -> StrictnessMark -> CoreExpr -> Bool
+ field_ok arg_ty str arg
+ = ok_for_spec arg || (definitely_lifted arg_ty arg && str==NotMarkedStrict)
+ -- The (ok_for_spec arg) test works for /both/ for unlifted types, /and/
+ -- for lifted but strict fields. E.g. K (I# 3) is ok-for-spec,
+ -- even if K is strict
+
+ -- We want to see if the argument type is definitely lifted.
+ -- But consider
+ -- (#,#) @rep1 @rep2 @ty1 @ty2 arg1 arg2
+ -- We don't /instantiate/ the type of (#,#) (although we could) so we don't
+ -- know if the argument type is lifted or not. So we look at the type of
+ -- the /actual/ argument (it's usually a variable) instead.
+ definitely_lifted uninstantiated_arg_ty arg
+ = case typeLevity_maybe uninstantiated_arg_ty of
+ Just Lifted -> True
+ Just Unlifted -> False
+ Nothing -> definitelyLiftedType (exprType arg)
-----------------------------
altsAreExhaustive :: [Alt b] -> Bool
@@ -2390,8 +2406,42 @@ cantEtaReduceFun fun
-- Don't undersaturate StrictWorkerIds.
-- See Note [CBV Function Ids: overview] in GHC.Types.Id.Info.
-{- Note [exprOkForSpeculation and type classes]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+{- Note [exprOkForSpeculation]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Suppose we have
+ data T a = K !a Int# a
+
+Is the call (K e1 e2 e3) ok-for-speculation? Look at the arguments e1..e3,
+and their types. The call is ok-for-speculation if each argument satisfies
+`field_ok`, namely:
+ (a) (exprOkForSpeculation arg) holds, OR
+ (b) Arg type is definitely lifted and it is not marked strict
+
+For (a) we conservatively assume we are going to evaluate the argument.
+If it is ok-for-spec, then fine.
+
+But if the argument is of a lifted type, and not marked strict (notably by
+a data constructor) then (b) holds. For example
+ Just (reverse xs)
+is ok-for-spec. See (EOKS1) for the argument liftedness test.
+
+If we have a plain variable `x`, is that ok-for-spec? Not if it is lifted:
+it might be a thunk! Hence the (definitelyUnliftedType fun_ty) test.
+Remember, a naked variable `x` will land in `app_ok x []` with no arguments.
+See Note [exprOkForSpeculation and evaluated variables].
+
+(EOKS1) To get the lifted-ness or otherwise of the arguments we just look at the
+ /uninstantiated/ type of the data constructor or primop. We'd get better information
+ if we instantiated, but it's also more expensive. Example:
+ (#,#) :: forall r1 r2 (a::TYPE r1) (b::TYPE r2). a -> b -> (# a, b #)
+ If we have a call
+ (#,#) @LiftedRep @IntRep @Int @Int# 3 4#
+ then we could see accurate liftedness by instantiation, but we don't try.
+ Instead we get the actual type from (exprType arg). That could be expensive,
+ but it really only happens for unboxed tuples.
+
+Note [exprOkForSpeculation and type classes]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider (#22745, #15205)
\(d :: C a b). case eq_sel (sc_sel d) of
@@ -2674,8 +2724,7 @@ exprIsHNFlike is_con is_con_unf rubbish_lit_result e
-- PAP: Check unlifted val_args
args_hnf = all2Prefix check_arg val_arg_tys val_args
- fun_ty = idType id
- val_arg_tys = mapMaybe anonPiTyBinderType_maybe (collectPiTyBinders fun_ty)
+ val_arg_tys = splitUninstantiatedValArgTys (idType id)
-- val_arg_tys = map exprType val_args, but much less costly.
-- The obvious definition regresses T16577 by 30% so we don't do it.
@@ -2700,7 +2749,6 @@ exprIsHNFlike is_con is_con_unf rubbish_lit_result e
| otherwise
= Nothing
-
{-
Note [exprIsHNF Tick]
~~~~~~~~~~~~~~~~~~~~~
=====================================
testsuite/tests/simplCore/should_compile/T27910.hs
=====================================
@@ -0,0 +1,17 @@
+{-# LANGUAGE UnboxedTuples, MagicHash #-}
+module T27910 where
+import GHC.Exts
+
+k1 :: (# Int, Bool #) -> (# Int, Bool #) -> Int
+{-# NOINLINE k1 #-}
+k1 _ _ = 3
+
+k2 :: (# Int#, Int# #) -> (# Int#, Int# #) -> Int
+{-# NOINLINE k2 #-}
+k2 _ _ = 3
+
+lifted :: Int -> Bool -> Int
+lifted x y = case (# x, y #) of r -> k1 r r
+
+unlifted :: Int# -> Int# -> Int
+unlifted x y = case (# x, y #) of r -> k2 r r
=====================================
testsuite/tests/simplCore/should_compile/T27910.stderr
=====================================
@@ -0,0 +1,49 @@
+
+==================== FloatOut stats: ====================
+2 Lets floated to top level; 0 Lets floated elsewhere; from 4 Lambda groups
+
+
+
+==================== FloatOut stats: ====================
+4 Lets floated to top level; 0 Lets floated elsewhere; from 6 Lambda groups
+
+
+
+==================== Grand total simplifier statistics ====================
+Total ticks: 30
+
+8 PreInlineUnconditionally
+ 1 ds
+ 1 ds
+ 1 ds
+ 1 ds
+ 1 ds
+ 1 ds
+ 1 ds
+ 1 ds
+2 PostInlineUnconditionally
+ 1 r
+ 1 r
+4 UnfoldingDone
+ 2 GHC.Internal.Prim.void#
+ 1 T27910.k1
+ 1 T27910.k2
+8 BetaReduction
+ 1 ds
+ 1 ds
+ 1 ds
+ 1 ds
+ 1 ds
+ 1 ds
+ 1 ds
+ 1 ds
+4 KnownBranch
+ 2 wild
+ 1 ww
+ 1 ww
+4 CaseElim
+ 2 ww
+ 2 ww
+9 SimplifierDone 9
+
+
=====================================
testsuite/tests/simplCore/should_compile/all.T
=====================================
@@ -627,5 +627,5 @@ test('T27749',
compile, ['-O -g3 -ddump-simpl -dsuppress-uniques'])
test('T27629', only_ways(['optasm']), makefile_test, ['T27629'])
-
test('T27936', normal, compile, [''])
+test('T27910', grep_errmsg(r'KnownBranch'), compile, ['-O -dno-typeable-binds -ddump-simpl-stats -dsuppress-uniques'])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/8c9475738abd6403dec943653f5cd48…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/8c9475738abd6403dec943653f5cd48…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc][wip/jeltsch/ghc-9-14-building-base] 119 commits: Reorder cmm decls in HeapStackCheck for a better logical grouping
by Wolfgang Jeltsch (@jeltsch) 16 Oct '26
by Wolfgang Jeltsch (@jeltsch) 16 Oct '26
16 Oct '26
Wolfgang Jeltsch pushed to branch wip/jeltsch/ghc-9-14-building-base at Glasgow Haskell Compiler / GHC
Commits:
430967ab by Duncan Coutts at 2026-09-09T11:07:01+01:00
Reorder cmm decls in HeapStackCheck for a better logical grouping
And put more section headers in to deliniate the groups.
We're about to add more here, so better to organise it first.
- - - - -
344080fd by Duncan Coutts at 2026-09-09T11:07:01+01:00
Add raisePrimIOException and add it to RTS<->ghc-internal API
The raisePrimIOException is a new helper function that I/O primops will
use to help them report I/O errors. This is implemented in Haskell
(since that's a lot easier), but has a calling convention that is
easy(ish) to use from Cmm in the I/O primops.
So we add it to the RTS API struct, and since we'll use it from Cmm we
also need a field accessor macro for cmm (in deriveConstants).
See the Note about how we cannot have nice things due to async
exceptions and thunks preventing us from using catch.
- - - - -
cfdb3399 by Duncan Coutts at 2026-09-09T11:07:01+01:00
Add new blocking functions for I/O primops
See the Note [Thread blocking for new I/O primops],
and the Note [Calling convention for raisePrimIOException].
The point is, it will allow us to report synchronous exceptions from I/O
primops, and do so much more flexibly.
Previously the I/O managers could only report async exceptions and only
nullary exceptions. This was OK historically, but no good as we add
more I/O managers and expand the range of I/O operations we support.
- - - - -
f09c09d8 by Duncan Coutts at 2026-09-09T11:07:01+01:00
Change the encoding of results from the I/O manager to I/O primops
Previously we just had async continue or heap overflow.
We now extend what we can report with synchronous success, and
synchronous failure with an errno.
See Note [Encoding of result of I/O manager operations]
We don't use these two new cases yet, but we will. In particular an
epoll I/O manager needs to be able to report synchronous success or
failure for waitRead#/waitWrite#.
- - - - -
30f074d9 by Duncan Coutts at 2026-09-09T11:07:01+01:00
Switch waitRead/Write# to use new blocking return frames
and update the I/O managers to set the result before resuming the
blocked threads.
This makes it possible for I/O managers to report synchronous exceptions
from the I/O primops, but that will be done in a subsequent commit.
- - - - -
a8786ced by Duncan Coutts at 2026-09-09T11:07:01+01:00
Switch Poll and Select I/O managers to report sync exceptions
rather than using raiseAsync with blockedOnBadFD_closure.
This uses the new mechanism in the blocking frame return code to report
synchronous exceptions.
- - - - -
7a9df79a by Duncan Coutts at 2026-09-09T11:07:01+01:00
Remove now-unused blockedOnBadFD
It was previously thrown by the select and poll I/O managers, but now
they use raisePrimIOException (with an EBADF errno).
- - - - -
6b0424e3 by Duncan Coutts at 2026-09-09T11:07:01+01:00
Improve the docs for delay# waitRead# and waitWrite#
Document that the waitRead/Write# can throw exceptions (this was true
before too), and that all of them are async exception cancellation
points.
- - - - -
afeb2c30 by Duncan Coutts at 2026-09-09T20:08:58-04:00
Enable printf warnings for trace functions and fix resulting warnings
Most of the existing printf-style functions are annotated with
attributes to enable gcc/clang warnings for the printf format string,
but several trace functions in Trace.h were missing this annotation.
Enable them, and fix the resulting warnings.
- - - - -
9a442c93 by Alan Zimmerman at 2026-09-09T20:09:36-04:00
EPA: Exact print ConDeclGADT without custom enterAnn
!16321 brought in explicit capture of parens in a ConDeclGADT.
The ExactPrint update introduced a modification of the fundamental
function in exact printing, `enterAnn`, by splitting it into a version
allowing injection of functionality normally handled by the
ExactPrint class methods.
This commit refactors that code, to restore the prior `enterAnn`
version, by following the convention in ExactPrint of introducing a
helper data structure with its own `ExactPrint` instance to achieve
the same effect.
- - - - -
4e9297ea by Simon Jakobi at 2026-09-11T08:32:45-04:00
ci: Actually pass --ignore-perf-failures to the testsuite driver
684c0018d9 changed the IGNORE_PERF_FAILURES handling to append to
RUNTEST_ARGS with bash array syntax, but the three use sites still
expand RUNTEST_ARGS as a scalar, which yields only the first array
element. The appended flag was therefore dropped in every job, so
perf improvements kept failing Marge Bot batches and master pipelines,
contrary to #19562.
Append as a string instead, matching the existing --force-colors
append in test_hadrian.
Fixes #27563.
Assisted-by: Claude Fable 5.1
- - - - -
4f78dfdf by Simon Jakobi at 2026-09-11T08:33:24-04:00
testsuite: Give T26537 a 1.5x compile timeout
Its -fregs-graph compile step tends to time out in unoptimized builds
(#27188, #27776).
Assisted-by: Claude Fable 5.1
- - - - -
130286e3 by Alan Zimmerman at 2026-09-11T08:34:08-04:00
EPA: Remove ListBanana / ListParens from AnnListBrackets
This is a step towards making AnnList only represent
lists of items which can have either braces or layout.
- - - - -
a9827d13 by Simon Jakobi at 2026-09-11T18:53:32-04:00
Reject ~, UNPACK and multiplicity annotations on type data fields
Only `!` was rejected so far. `~`, UNPACK and multiplicity annotations
were silently accepted. None of them make sense at the type level, so
restriction (R3) of Note [Type data declarations] now covers all of
them.
Fixes #27732.
Assisted-by: Claude Fable 5.1
- - - - -
c71d5e23 by Alan Zimmerman at 2026-09-11T18:54:11-04:00
EPA: Add a Note for the exact print main loop
- - - - -
7a108e43 by Simon Jakobi at 2026-09-12T18:35:59-04:00
FastString: Drop mkFastStringWith's constructor callback
All three callers passed the same callback, a partial application of
mkNewFastStringShortByteString to the string being interned. That
partial application is allocated as a closure before the table lookup,
on the common hit path too, although the callback is needed only after
a miss.
Drop the parameter and call mkNewFastStringShortByteString directly
after a miss. Since nothing is passed "with" anymore, rename the
function to internSB.
Suggested by Simon PJ in #27528:
https://gitlab.haskell.org/ghc/ghc/-/work_items/27528#note_687031
Assisted-by: Claude Fable 5
- - - - -
82c73b22 by Alan Zimmerman at 2026-09-12T18:36:38-04:00
EPA: More targeted HsDo exact print annotation
HsDo is multi-purpose, as encoded in its HsDoFlavour field. Some of
these are in a layout context (DoExpr, MDoExpr), others are not
(ListComp, MonadComp).
We are moving towards using AnnList only in layout contexts, so we
switch the HsDo TTG annotation from holding an AnnList for this, to
holding
Either (EpToken "[", EpToken "]") AnnList
This also allows us to trim down AnnListBrackets to only have braces
or None, thereby opening the door for unification with the existing
layout context data type EpLayout.
- - - - -
749d2448 by Luite Stegeman at 2026-09-15T14:07:01-04:00
rts: handle large CONSTR closures in compacting GC
The function update_fwd_large in the compacting GC could run into
an unexpected object with the following error:
internal error: update_fwd_large: unknown/strange object 1
Closure type 1 is CONSTR. This patch adds cases for CONSTR and
CONSTR_NOCAF.
This is the same problem as #27434 (large AP closures, fixed by
cca0d58963), which missed this case.
Fixes #27649
- - - - -
177d6155 by Luite Stegeman at 2026-09-15T14:07:02-04:00
testsuite: fix T27434 test with compacting GC
Ensure that the interpreter is actually run with the compacting GC
- - - - -
5796aa63 by Luite Stegeman at 2026-09-15T14:07:49-04:00
rts: initialise the stack frame header for mask_frame and apply_mask_frame
We must leave the stack in consistent state before jumping to
mask_frame or apply_mask_frame because they may result. Failing
to do so could lead to a crash if there were waiting exceptions.
Fixes #27651
- - - - -
2486cc92 by Simon Peyton Jones at 2026-09-15T14:08:36-04:00
Re-introduce the "weird SpecDict" case
In this commit
commit f80375dd4945350a1d784e436975b48b9c736eaf
Author: Simon Peyton Jones <simon.peytonjones(a)gmail.com>
Date: Sun Jun 29 15:26:58 2025 +0100
Refactor of Specialise.hs
I removed a test for a dictionary with unbound type variables. This
turned out to be wrong; see #27629.
So this MR re-introduces it.
- - - - -
8e09a46f by Duncan Coutts at 2026-09-15T20:11:35-04:00
Refactor (and rename) removeFromQueues, to simplify I/O managers
Rename it to unblockAndAppendToRunQueue which better reflects what it is
intended to do.
The post-condition for unblockAndAppendToRunQueue is that the TSO is on
the run queue or it is in the process of migrating to another cap.
Previously it achieved that by always directly adding the TSO to the run
queue itself.
But this actually made things more complicated for the I/O managers,
because it meant they needed a separate code path for notifying for
cancellation compared to notifying for completion. The general
notification code would always add the TSO to the run queue itself.
So the improvement is to allow different cases in
unblockAndAppendToRunQueue to achieve the same outcome in different
ways: either directly adding to the run queue or calling helper
functions that do so themselves.
This then allows the new I/O managers to share code between the sync and
async cancellation, and to reuse their notifyIOCompletion helpers for
cancellation. This avoids a source of bugs where the completion path may
be updated but the cancellation path may be forgotten, or similarly in
future for sync/async operations.
Update all the existing in-RTS I/O managers, and the posix timeout code.
- - - - -
d668782c by Duncan Coutts at 2026-09-15T20:11:35-04:00
Document that awaitCompletedTimeoutsOrIO expects an empty run queue
This was true before but implicit and not relied on much. It's better to
be explicit, and allow things to depend on it.
- - - - -
11d938bb by Duncan Coutts at 2026-09-15T20:11:35-04:00
Store the I/O opcode and fd in the StgAsyncIOOp
This will be useful in several I/O managers and it is handy for logging
and debugging.
It also doesn't increase the size of the StgAsyncIOOp structure. There
was enough spare padding space already.
Update the poll I/O manager to set the new fields.
Add a helper function to convert the enum IOReadOrWrite into the enum
IOOpCode. Also change IOReadOrWrite to be an enum without a typedef, for
consistency with other enumerations in IOManager.h
- - - - -
bfa87882 by Duncan Coutts at 2026-09-15T20:11:36-04:00
Add a new I/O manager based on select()
Yes, this is the second such I/O manager, but it is a modern
re-implementation based on the new in-RTS I/O manager infrastructure. So
it is cleaner and faster than the old select I/O manager.
Why do we need another I/O manager based on select? Why isn't the poll()
one good enough as a baseline portable unix I/O manager? Because macOS.
Apple Inc. is why we cannot have nice things.
The man page for poll on macOS documents the fact that it does not work.
At least, it does not work for all files. Specifically, it does not work
for device files. Whereas macOS select() does work for device files.
Aaaaarg!
We _do_ want to deprecate and remove the old select I/O manager, but due to
macOS we cannot do that until we have a replacement. This is that
replacement. Until of course a nice new k-queue I/O manager arrives,
which could become the new default for macOS and FreeBSD.
Interestingly, this select I/O manager is actually faster than the poll
one, on Linix, in some circumstances: specifically when many Haskell
threads are waiting on the same fd. The poll I/O manager does O(n) work
for n threads waiting on I/O, whereas the select one does O(fds) work
for the number of fds that threads are waiting on. Usually this is 1:1,
so it's not noticable, but one can concoct extreme benchmarks to show
the difference.
- - - - -
8e9de15a by Duncan Coutts at 2026-09-15T20:11:36-04:00
Minor updates in the poll I/O manager to keep in sync with select
This keeps it in sync with select one. The changes are based on code review
while implementing the new select I/O manager. The two I/O managers are so
similar in structure that it makes sense to try to minimise the diff between
them. This should aid understanding, and fixes to both in future.
- - - - -
222668bb by Duncan Coutts at 2026-09-15T20:11:36-04:00
Document the new select I/O manager in the user guide
in the RTS section about I/O managers.
And add a changelog entry.
- - - - -
0f48735b by Cheng Shao at 2026-09-15T20:12:23-04:00
Revert "wasm: workaround WebKit bug in dyld"
This reverts commit c9b8465c2c338176fcab9d197e9d31f4aee11f68. The
underlying webkit bug has been fixed in
https://commits.webkit.org/314219@main. Closes #27564.
- - - - -
809294f1 by Luite Stegeman at 2026-09-15T20:13:08-04:00
rts: make stg_threadLabelzh return a valid pointer for unlabeled threads.
This fixes a segfault in the GC caused by stg_threadLabelzh returning
a 0 pointer in a GC pointer field.
stg_threadLabelzh returns a tuple of type (# Int#, ByteArray# #). If a
thread has no label, the second field is unused. We must still return
a valid heap object pointer.
Instead of returning 0, we now return stg_DEAD_SLOT_closure.
fixes #27618
- - - - -
e2d57026 by Luite Stegeman at 2026-09-15T20:13:54-04:00
JS: fix selector thunk handling
fix a bug where entering a selector thunk could lead to a crash
if the selected field was still a thunk.
fixes #27788
- - - - -
1b4a622f by sheaf at 2026-09-17T02:39:13-04:00
Improvements to type/data family handling
This commit makes several improvements to the treatment of type and data
families in GHC:
- We consistently use "type family" instead of "type synonym family"
to avoid a confusion with type synonyms. For example:
- OpenSynFamilyTyCon ==> OpenTypeFamilyTyCon
- ClosedSynFamilyTyCon => ClosedTypeFamilyTyCon
- Various functions that were specific to data families have been
renamed to make this clear. For example:
- tyConFamInst_maybe ==> tyConDataFamInst_maybe
- isFamInstTyCon ==> isDataFamInstTyCon
- 'FamTyConFlav' has been refactored so that all closed type families
share a single 'ClosedTypeFamilyTyCon' constructor.
The corresponding 'IfaceFamTyConFlav' type was updated similarly.
This is then used to tidy up the implementation of
GHC.Core.FamInstEnv.reduceTyFamApp_maybe.
- - - - -
c5aa9098 by sheaf at 2026-09-17T02:39:13-04:00
Small refactor of lookupFamInstEnv
This commit reworks the code for looking up family instances in
GHC.Core.FamInstEnv, reducing duplication a little bit.
No change in behaviour.
- - - - -
a3ad4588 by sheaf at 2026-09-17T02:39:14-04:00
Use a type family for boxing unboxed types
This commit overhauls the way in which unboxed types are boxed, as per
the updated Note [Boxing constructors] in GHC.Builtin.WiredIn.Types.Box.
The main change is to allow boxing to be parametrised by representation,
e.g. making 'Box ty' a valid type. We achieve this by implementing 'Box'
using a closed type family:
newtype Box (a :: TYPE r) = Box (BoxTF r)
type BoxTF :: RuntimeRep -> Type
type family BoxTF r where
BoxTF IntRep = BoxInt
BoxTF Int8Rep = BoxInt8
BoxTF WordRep = BoxWord
BoxTF LiftedRep = Any @Type
BoxTF (TupleRep [r1, r2]) = (BoxTF r1, BoxTF r2)
...
BoxTF (SumRep rs) = BoxSum rs
This new design solves the following problems:
- It allows boxing a type whose 'RuntimeRep' has not yet been
determined (e.g. because we only learn the 'RuntimeRep' after
constraint solving). That is, 'Box @r a' is a perfectly valid type
even if 'r' is an unfilled metavariable. This is a requirement
to fix #25065 (in which we need to box a type whose 'RuntimeRep'
is only filled in during constraint solving).
- It handles boxing of unboxed tuples and unboxed sums, via recursive
boxing. See Note [Boxing TupleRep and SumRep] in
GHC.Builtin.WiredIn.Types.Box.
'Box', 'BoxTF' and all of the boxing data constructors are defined in
a new 'ghc-internal' module, 'GHC.Internal.Box'. This module contains
nothing but wired-in declarations, and GHC never loads its interface on
account of a wired-in thing (GHC.Builtin.Modules.isWiredInOnlyModule);
see Note [Loading instances for wired-in things] in GHC.Iface.Load.
The individual boxing data constructors are deliberately left as an
internal implementation detail, and not exported. The intended API is
via the two new magic 'Id's:
box :: forall {r} (a :: TYPE r). a -> Box a
unbox :: forall {r} (a :: TYPE r). Box a -> a
exported from 'GHC.PrimOps' (in 'ghc-experimental'). The old boxing
data types (IntBox, WordBox, FloatBox, DoubleBox, DictBox) are no longer
exported from base (CLC proposal #421).
We use this new design to consistently desugar:
- parallel comprehensions (GHC.HsToCore.ListComp.{deListComp,dsMcStmt})
- then/group/using statements (GHC.HsToCore.ListComp.{dsTransStmt,dsMcStmt})
- recursive do blocks (mdo/rec) (GHC.HsToCore.Expr.dsDo)
- arrows (GHC.HsToCore.Arrows)
by consistently using 'box'/'unbox' to deal with unboxed types being put
into big tuples. We also adapt 'GHC.Tc.Gen.Match.{tcMcStmt,tcDoStmt}'
to create fresh /representation-polymorphic/ type variables for the
binders that we are going to put into a big tuple (previously, GHC only
allowed lifted types in that position).
These desugaring of box and unbox is explained in
Note [Desugaring box & unbox] in GHC.Core.Make.Box. Roughly speaking,
the desugaring looks like:
box @r @ty e ==> K e
unbox @r @ty e ==> case e of K x -> x
where 'K' is the boxing data constructor at RuntimeRep 'r'. It's
slightly more complicated than that in practice: we first need to
insert a cast (see Note [The canonical type of a RuntimeRep]) using the
new 'CanonicalProv' 'UnivCoProvenance', and unboxed tuples/sums need
recursive logic explained in Note [box/unbox for unboxed tuples and sums],
including a specific 'BoxSum' datatypes for unboxed sum (which also
needed a wired-in type-level list indexing type family (!!)).
The desugaring happens in two ways:
- Occurrences of 'box'/'unbox' emitted by the typechecker are
eliminated in the 'ds_app_var' case of GHC.HsToCore.Expr.
- Other code that needs to box/unbox emits the appropriate code inline.
This includes the big tuple machinery of GHC.Core.Make used by the
desugarer (GHC.HsToCore.{Utils,Binds,Arrows,ListComp}) as well as
the float-out pass (GHC.Core.Opt.SetLevels).
Core Lint checks that no occurrence of 'box'/'unbox' survives desugaring.
On the way, we overhaul the litany of big tuple functions by introducing
data BigTupleLayout = BoxedElements | BareElements
to distinguish the two kinds of "big tuples" that GHC routinely deals
with; for example 'mkBigCoreVarTupSolo' becomes 'mkBigCoreVarTup BareElements'.
All of this code is moved to the new module GHC.Core.Make.BigTuple.
Fixes #20864 #22336 #22473 #25065 #27331
-------------------------
Metric Decrease:
T9872a
-------------------------
- - - - -
4cf7628a by Evgeny Malyshev at 2026-09-17T02:39:56-04:00
Fix the CompactionFailed documentation link to compact
The old Haddock reference links into base instead of ghc-compact.
Use an explicit URL because ghc-compact depends on base, not vice versa.
Fixes #27558
Assisted-By: OpenAI Codex
- - - - -
098bba70 by Facundo Domínguez at 2026-09-17T14:57:41-04:00
Remove the call to hoistFlag from processCmdLineP
This call was undesirable because it was causing a reconstruction
of the list of flag processors.
Even relying on list fusion would not be sufficient because we want
to replace the list with a data structure with faster lookups to
address #25763.
The removal is done in two moves:
* We move CmdLineP to CmdLine.hs
* Then we move the effect of hoisting to processArgs via a new function
hoistEwM
- - - - -
e01799c7 by Facundo Domínguez at 2026-09-17T14:57:42-04:00
Do not create duplicate flag processors for the -W flag
This makes simpler implementing the command line parser with a trie map
holding flag processors. If we were to allow duplicate flag processors
for any flag, the trie map would need to be a multimap.
- - - - -
3875b257 by Facundo Domínguez at 2026-09-17T14:57:42-04:00
Replace the list of flag processors with a trie map in `processArgs`
Previously `GHC.Driver.CmdLine.findArg` was called for each
command-line argument, doing a linear search on the list of flag
processors each time. This was somewhat costly as the list of flag
processor has near 2000 elements.
A lookup with a trie map is faster in general, but the speed up is
only noticeable when calling `GHC.Driver.CmdLine.processArgs` sufficient
times, so the amount of lookups piles up. This could happen in large
projects with many units each having many dependencies. If only a
module needs to be recompiled, the user still needs to wait for all of
the flag parsing to complete.
The benchmark at testsuite/tests/perf/compiler/cmdline-parser shows a
10x speed up when using the trie.
The trie map is implemented in `GHC.Data.StringTrie`.
The design is explained in Note [Processing command line argument fast]
in GHC.Driver.Session.
The commit also:
* adds two property-based tests for trie map operations,
* adds a benchmark of the command line parser, and
* renames the predicate `arg_ok` to `valid_flag_suffix` to decide what
flag processor should be used when there are multiple matching
prefixes on a flag.
Fixes #25763.
- - - - -
5236634a by Andreas Klebinger at 2026-09-17T14:58:24-04:00
Compile Word64{Map,Set} with -O2 always.
This is the hottest code and even if we build GHC with -O0 otherwise -O2
pays off for these modules.
Fixes #27814.
- - - - -
545fd4fb by ARATA Mizuki at 2026-09-22T15:03:24-04:00
Change the C types of hs_{bitrev,bswap}{16,32} to match the Haskell types
bitReverse{16,32}# and byteSwap{16,32}# have the type
Word# -> Word#, but their C correspondents took and
returned StgWord{16,32}.
The mismatch on bitReverse16# led to the problem reported
in #27299. Although no similar issue is reported for
bitReverse32# and byteSwap{16,32}#, it seemed wise to
change them proactively.
This commit fixes the mismatch by changing the C type.
Fixes #27299
- - - - -
bf17f289 by fendor at 2026-09-22T15:04:05-04:00
Don't lose instances from shadowed imported modules with the same name
When we look for instances below the current module, we need to check
the unit id as well when we check for whether the module is the current
module, otherwise we ignore modules we import that have the same name as
the import module.
Adds regression test.
- - - - -
53eead15 by Wolfgang Jeltsch at 2026-09-24T20:12:03-04:00
Correct the documentation of `explicitUnits`
Resolves #27787.
- - - - -
35bf6f4b by Simon Jakobi at 2026-09-24T20:12:49-04:00
Remove stale specHeader bullet from Note [Don't make fillers for constraint types]
The Note said that Specialise.specHeader also calls mkAbsentFiller.
abfc224a27c removed that call: the specialiser no longer drops dead
arguments at all, see Note [Do not drop dead args from specialisations]
in GHC.Core.Opt.Specialise.
Assisted-by: Claude Fable 5.1
- - - - -
1abef1ef by Wolfgang Jeltsch at 2026-09-25T17:02:07-04:00
Improve the `mhu-closure` makefile
- - - - -
a79a68ea by Wolfgang Jeltsch at 2026-09-25T17:02:07-04:00
Make `ghci-multi` hide all unneeded packages
- - - - -
d6e72450 by Wolfgang Jeltsch at 2026-09-25T17:02:07-04:00
Improve the definition of the home unit closure property
- - - - -
c9a2766d by Wolfgang Jeltsch at 2026-09-25T17:02:07-04:00
Re-implement the home unit closure check
Compared to the previous implementation, the new one has the following
advantages:
* It is correct.
- It distinguishes between units that have the same unit ID but
different ABI hashes.
- When `-hide-all-packages` is not used, it considers as home unit
dependencies also units that are made implicitly available
because they are in the package database.
* It seems to be faster in usual settings.
- In particular, it does not have a preparation phase in which it
merges the dependency information from all home units, so that
its running time does not grow linearly with the size of the
package database in normal Cabal scenarios.
* It is (hopefully) clearer.
* It is better documented.
- - - - -
fa96acf8 by Wolfgang Jeltsch at 2026-09-25T17:02:07-04:00
Remove erroneous GHC flag in `hadrian-multi`
The flag was `-Werror=-Wno-error=incomplete-record-selectors`. Its
purpose was to permit incomplete record selectors, but because of the
illegal combination of `-Werror=` and `-Wno-error` it was ignored,
without any negative consequences.
- - - - -
9f48a5b9 by Alan Zimmerman at 2026-09-25T17:02:50-04:00
EPA: Add specific layout field to AnnList
Up to now AnnList has effectively served to represent lists of things
having layout, regardless of whether they do or not.
In Haskell, layout is optional in many places, as there is also an
alternative syntax using braces and semi-colons, which is free-form.
This commit introduces AnnListLayout, a data structure capturing this
distinction.
It is deliberately set up similarly to EpLayout, so that these two can
be merged in time.
The transition is done mechanically, where AnnListBraces is not used
yet, the original Nothing case maps to AnnListNoLayout, and the Just
case to AnnListLayout.
Later commits will fine tune these against the actual parser layout.
- - - - -
234bab08 by Vladislav Zavialov at 2026-09-29T17:22:54-04:00
Add regression test for #7803
Commit 2effe18ab5, first shipped with GHC 8.2.1, fixed #7803 "Superclass
methods are left unspecialized".
This change turns the example from the ticket description into a regression
test, checking that foo1 is fully specialised at Double, with no calls to the
overloaded exp5Tail.
Closes #7803
Assisted-by: Claude Opus 5
- - - - -
c406135c by Andreas Klebinger at 2026-10-01T06:57:28-04:00
RTS: Update flag parsing/handling:
Using 0 as argument to any of these flags now resets the flags setting to default:
- ``-n0`` disables nursery chunking.
- ``-K0`` (or a bare ``-K``) removes the stack size limit.
- ``-M0`` removes the heap size limit.
- ``-H0`` resets the suggested heap size, including the nursery scaling set by ``-H``.
- ``-AL0`` makes the large object allocation limit follow ``-A`` again.
GC Generations are now limited to 64.
-n larger than -A now emits a warning and disables chunking.
Fixes #27830 #27829
- - - - -
984ee82b by Andreas Klebinger at 2026-10-01T06:58:10-04:00
Fix MultiLayerModules timeout multiplier.
We accidentally used the compile multiplier for ghci commands which
use the run timeout setting to set the timeout.
Fixes #26263 and #27796.
- - - - -
50a9cf26 by Andreas Klebinger at 2026-10-01T06:58:10-04:00
testsuite: Include runtime in JUnit report.
- - - - -
e358619f by Alan Zimmerman at 2026-10-01T06:59:01-04:00
EPA: Use EpaLocation in EpVirtualBraces
Haddock processing uses EpLayout.EpVirtualBraces to record the current
layout column, for allocating haddock comments correctly.
For exact printing, we need the line as well as the col, so we know
how many lines to skip when the indented code block starts.
This commit updates EpLayout.EpVirtualBraces so that it carries an
EpaLocation instead of just the Int column, to allow it to be used for
both purposes.
It is a simple mechanical change, with no other impact, but it allows
us to use EpLayout instead of AnnListLayout in AnnList, in the next
commit in this series.
- - - - -
1d2a26ee by Andrew Lelechenko at 2026-10-01T20:22:04-04:00
Remove bitSize from MINIMAL pragma of class Bits
Cf. https://github.com/haskell/core-libraries-committee/issues/441
The function is deprecated for 12 years and has a default implementation,
yet it was never removed from the MINIMAL pragma, putting library authors
in a very awkward position. Let's finally remove bitSize from MINIMAL.
- - - - -
3cc21e4c by Hannes Siebenhandl at 2026-10-01T20:22:59-04:00
Add regression test for #27641
- - - - -
c35096f5 by Hannes Siebenhandl at 2026-10-01T20:23:00-04:00
Don't `:add` modules the loader will reject
Only home modules can be actually added to the loader context, thus we
only accept the module if it belongs to a home unit.
- - - - -
a563cb27 by Simon Jakobi at 2026-10-02T17:37:36-04:00
ci: accept modified changelog.d entries in lint-changelog
The changelog guide says to extend an existing entry rather than add a
new one when the feature is already documented. lint_changelog only
counted added files, so such MRs failed before the validator ran.
Fixes #27779.
Assisted-by: Claude Fable 5.1
- - - - -
03082cd4 by Simon Jakobi at 2026-10-02T17:38:17-04:00
changelog.d: Fix warning flag name in the semaphore-v2 entry
The entry refers to -Wsemaphore-version-mismatch, which does not exist.
The warning GHC emits when it cannot use a -jsem semaphore, including
on a protocol version mismatch, is -Wsemaphore-open-failure.
Context: !15729, #25087
Assisted-by: Claude Fable 5.1
- - - - -
a93705ee by Simon Jakobi at 2026-10-02T17:38:17-04:00
changelog.d: Fix the CLC proposal link in the T27455 entry
The entry used the Sphinx :ref: role with a URL as its target. :ref:
resolves only internal labels, so the generated release notes would
show the proposal name without a link. Use the plain hyperlink form
like the other entries.
Context: !16274, #27455
Assisted-by: Claude Fable 5.1
- - - - -
54381079 by Hannes Siebenhandl at 2026-10-02T17:39:01-04:00
Extend the `TrustOverlay` for wired-in units
The TrustOverlay only contained the `UnitId` of all on-disk units.
However, wired-in units are referred to by their wired-in unit id, which
is not the same as the on-disk unit id.
Thus, trust checks for wired-in units failed because the lookup was
using the wired-in unit, which wasn't present in the `TrustOverlay`.
We fix #27834, by copying the trust info for wired-in unit ids.
- - - - -
f8cfb1a5 by Hécate Kleidukos at 2026-10-04T19:36:39+02:00
[CLC 341] Strict variants of mutable types
This commit is the implementation of CLC Proposal 341
https://github.com/haskell/core-libraries-committee/issues/341
- - - - -
575c4bc6 by Rodrigo Mesquita at 2026-10-05T12:32:02-04:00
ttg: HsModuleName in the AST, ModuleName in GHC
This commit makes the AST fully independent from GHC by parsing a
"module name" as an `HsModuleName (= HText)` rather than constructing an
`ModuleName (= FastString)` straight away.
In the GHC side, everything remains as a `ModuleName`. We turn AST
`HsModuleName`s into fast strings with the cheap `mkFastStringShortText`
when we process the AST for manipulation within the compiler.
There are no performance regressions introduced by this approach.
This is the final piece of #21592
Alternative plans were discussed in
gitlab.haskell.org/ghc/ghc/-/merge_requests/16546#note_694647,
but the Simon suggested one won in simplicity and performance when
compared against my attempt at implementing my original plan of having
a family `ModuleNameP`.
- - - - -
b3b89d32 by mangoiv at 2026-10-05T22:03:32-04:00
hadrian: Persist the used flavour name in the build root (#20650)
This executes the idea proposed in #20650, teaching Hadrian to persist
the flavour used to build a build root. This both makes use of multiple
build roots more ergonomic (as the user no longer needs to repeat
themselves) and avoids a tiresome foot-gun (forgetting to specify a
flavour, often wholly invalidating a build root).
Closes #20650.
Co-authored-by: Sylvain Henry <sylvain(a)haskus.fr>
- - - - -
f977837b by mangoiv at 2026-10-05T22:04:21-04:00
configure: fix sed script and subst tooldir script
Fixes #27672
Adds sanity checking for SUBST_TOOLDIR
Metric Decrease:
LinkableUsage01
MultiLayerModulesTH_OneShot
T10547
T12234
T12425
T13035
T13820
T18140
T18730
T18923
T9198
TcPlugin_RewritePerf
mhu-perf
- - - - -
f1cb08be by Hannes Siebenhandl at 2026-10-05T22:05:03-04:00
Prepend in-memory unit database for backpack
The packageDbFlags are stored in reverse order. Thus, prepending will
ensure that the in-memory unit database is the last item on the unit
database stack.
Further, the in-memory unit database needs to be able to shadow units
from earlier unit databases in the unit database stack.
Moreover, a `-clear-package-db` would remove the in-memory database if
it weren't the last item on the stack.
Closes #27835
- - - - -
8d49ed42 by Kazu Yamamoto at 2026-10-06T19:37:25-04:00
Do not leave standard file descriptors free at startup (#24450)
A process may be started with stdout closed -- `prog >&-` from a shell does
exactly that. Nothing then reserves descriptor 1, and open(), pipe() and
socket() hand out the lowest free descriptor, so the next descriptor the
runtime creates for itself takes it: the ticker's pipe, or a capability's IO
manager control pipe.
'GHC.Internal.IO.StdHandles.stdout' is a CAF, built the first time the program
writes to stdout, which is long after that has happened. It builds a 'Handle'
over descriptor 1, which now belongs to the runtime, and nothing reports an
error because the descriptor is perfectly good. The program then writes its
output into the runtime's own plumbing.
What that looks like from the outside is a hang. The descriptor the Handle has
taken over is the read end of a pipe, so poll() for POLLOUT on it never says
yes and epoll_ctl() accepts a registration for it; the thread waiting to write
blocks for ever. Closing the Handle at exit closes the runtime's descriptor,
which is worse: the ticker then fails on every tick.
'hs_init_ghc' now opens /dev/null onto whichever of descriptors 0, 1 and 2 are
closed, before the runtime creates any descriptor of its own. Each is opened
for the access that descriptor would normally have, read-only for 0 and
write-only for 1 and 2, so that writing to 'stdin' or reading from 'stdout'
still fails rather than quietly succeeding against /dev/null. See
Note [Standard file descriptors must be open].
Moving only the descriptors the runtime opens would not do: the first file the
program itself opened would land on the free number instead. The fix has to
leave no free number. A program run this way therefore finds stdout connected
to /dev/null rather than failing with EBADF on the first write, which is what
such a program would get from most other language runtimes.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
65bcf9e9 by Simon Jakobi at 2026-10-06T19:38:09-04:00
changelog: Repair the sentence describing #27477
The description read "programs using could crash", the object of
"using" having been lost. The synopsis already says which programs are
affected, so drop the dangling word.
Assisted-by: Claude Fable 5.1
- - - - -
15ece296 by mangoiv at 2026-10-08T15:14:56-04:00
ci: move hadrian/ghci into the lint category so it can be picked up by more runners
Fixes #27817
- - - - -
c0823135 by mangoiv at 2026-10-08T15:14:56-04:00
ci: make lint-adjacent jobs into platform independent
- move lint jobs into lint-anyarch tag
- unify lint jobs under the same platform independent container
- - - - -
f76464cf by Zubin Duggal at 2026-10-08T15:15:39-04:00
DmdAnal: Make AbsDmd neutral in maxDmd
fixes #27845
- - - - -
ffa56ae4 by sheaf at 2026-10-09T17:15:59+02:00
Preserve sign of zero when parsing -0.0#
This commit leverages the recently added GHC.Types.Literal.Floating
module in order to preserve the sign of negative zero from
source-written floating-point literals.
Fixes #27545
- - - - -
d538cac9 by Facundo Domínguez at 2026-10-09T20:26:38-04:00
Propagate annotations to simple interfaces
This allows annotations to be visible to plugins when run by
haddock. The LiquidHaskell plugin needs the annotations, in particular.
Fixes #26761
- - - - -
32c4f4ab by meooow25 at 2026-10-09T20:27:28-04:00
Bump containers submodule to 0.8.1
And fix affected tests.
* T4086a: containers depends on template-haskell-lift now instead of
template-haskell.
* T22611: Updated to be less dependent on containers internals.
- - - - -
c786065e by sheaf at 2026-10-09T20:28:20-04:00
Use an explicit pattern match in toIfaceIdDetails
The old wildcard pattern let this code bit rot: it did not properly account
for recently added 'IdDetails' such as 'RepPolyId', which resulted in
spurious 'pprTrace' messages that could even pollute HLS sessions.
Fixes #23785
- - - - -
e7cacf59 by sheaf at 2026-10-09T20:29:09-04:00
Take into account ifKind in freeNamesIfDecl
Commit 3c2f4bb4 added the 'ifKind' field to various constructors
of 'IfaceDecl', which preserves the original kind (before type synonym
expansion) for better error messages.
However, that commit forgot to update 'freeNamesIfDecl' correspondingly.
This could result in a "urk! lookup local fingerpring" crash when e.g.
a type's kind uses a type synonym defined later, as we failed to add a
dependency on the type synonym during dependency analysis.
Fixes #27916
- - - - -
41e80f41 by Simon Peyton Jones at 2026-10-11T14:38:51-04:00
Simplify the error-suppression mechanism in GHC.Tc.Errors
In `GHC.Tc.Errors.reportWanteds` we suppress some errors in favour of
others. But the mechanism had grown crufty, and #27331 exposed a bug.
This MR makes it simpler and more uniform, by doing everything via
the `ei_suppress` field of the ErrorItem.
Claude then found another closely-related bug (see the review linked
on !16564). That bug is immortalised in new test T18851d.
I'm still not happy with `ignoreConstraint` but we can worry about
that another day; I have not touched it.
Main changes
* Instead of /predicting/ when an error will be reported, we set
`cec_error_reported` when an error is /actually/ reported. (I renamed
it from `cec_suppress` to reflect this change.)
Now errors are suppressed only when a preceding error has actually been
reported. Simpler and more robust.
See `Note [cec_error_reported: suppressing less-serious errors]`
The big changes are in `reportWanteds` which looks very different.
* New `Note [ei_suppress: suppressing confusing errors]` describes the
(quite separate) `ei_suppress` mechanism for suppressing confusing
errors, mainly arising from non-empty rewriter sets
* In `tryTypeClassDefaulting`, instead of switching off type-class defaulting
if there is an insoluble /anywhere/, we just switch it off locally when
we find an insoluble sub-tree. See Note [When to do type-class defaulting]
and (W5) in Note [ApproximateWC]
* Greatly simplify `insolubleWantedCt`.
* I made type-class-defaulting be a bit more eager, only switched off when
a peer or ancestor (but not child) constraint is insoluble. See
Note [When to do type-class defaulting].
Small refactorings
* Rename `askNoErrs` to `askErrsFound` and flip its polarity
* The code for "check if ei_suppress is true of all items" code is
moved to `mkErrorItems` rather than in the large `reportWanteds`.
* Code for `has_gadt_match` moves to `mkGivenErrorReporter`, rather than
polluting the large `reportWanteds`.
* Many tests with `-fdefer-type-errors` get more warnings, especially
about ambiguous (Num a) constraints. This is by-design: see
Note [Always warn with -fdefer-type-errors]. Previously GHC was not
honouring this Note but now it is, hence the extra errors.
- - - - -
f217fc31 by Cheng Shao at 2026-10-11T14:39:33-04:00
compiler: ensure cross ghc --info output target unit ids
Previously, for cross ghcs, the base/ghc/ghc-internal unit ids in
--info output do not match the target unit ids reported by ghc-pkg,
breaking cross ghc release builds with hash-unit-ids when being used
with cabal 3.18. This patch fixes it by making --info output target
unit ids. Fixes #27919.
Co-authored-by: Codex <codex(a)openai.com>
- - - - -
d07a5176 by Simon Peyton Jones at 2026-10-13T18:10:39-04:00
Remove the Eq and Ord instances for ForAllTyFlag
In Note [Comparing visibility] in GHC.Core.TyCo.Compare we read that
"we always compare ForAllTyFlags with `eqForAllVis` or `cmpForAllVis`"
But alas there was an Eq and Ord instance for ForAllTyFlag, which made it
impossible to check this claim. So I made these changes:
* Move the definition of ForAllTyFlag and its related functions from
L.H.S.Specificity (where it did not belong, since L.H.S didn't use it)
into GHC.Types.Var.
* Remove the Eq and Ord instances for ForAllTyFlag
* Deal with the fallout, by using `eqForAllVis` or related functions.
* In interface files we use IfaceType as a key for a de-deduplication map
See Note [Deduplication during iface binary serialisation]
in GHC.Iface.Binary. For this we need /exact/ comparison, so we use a
newtype wrapper for IfaceForAllTyFlag, and give use `cmpForAllTyFlagExactly`
to implement its Ord instance. Tiresome but easy.
* Rename `toIfaceForAllBndrs` to `toIfaceForAllTyBndrs`
- - - - -
ea5c054d by Simon Peyton Jones at 2026-10-13T18:10:39-04:00
Refactor type and coercion substitution
This MR refactors type and coercion substitution so that they use
TyCoMapper, rather than hand-rolled code. Fundamentally it's a simple
idea, but I had to do quite a bit of refactoring to make it fly.
I got Claude to help me this this refactoring, but I paid careful
attention to every line of code.
Main changes:
* New module GHC.Core.TyCo.Make which defines TyCoMapper, and a bunch of other
simple "smart constructors" for types and coercions. See
GHC.Core.TyCo.Rep Note [The Type-related module hierarchy], esp (TRM1)
* The new TyCoMapper has new fields `tcm_tcapp_ty` and `tcm_tcapp_co` to handle
type-constructor applications. These replace `tcm_tycon`.
* Rewrite GHC.Core.TyCo.Subst to use TyCoMapper
* Rewrite GHC.Core.Type.expandTypeSynonyms to use TyCoMapper.
* Implement `seqType` and `seqCo` with TyCoFolder. To to this I had to add
a `tcf_lit` field to TyCoFolder.
* A new module GHC.Utils.StrictIdentity to define a strict identity monad,
which itself is used for
substTyCoMapper :: TyCoMapper Subst StrictIdentity
* I removed an apparently-unused instance for Binary Levity
Refactoring `seq` functions
* In GHC.Core.Seq, redefine `seqOneShot`, `seqRuleInfo`, and friends to return
`SeqResult`, a new type defined in GHC.Types.Baseic, rather than `()`. We
can define a Monoid instance for `SeqResult` that does the right thing.
* This has knock-on effects across the compiler.
- - - - -
34165e23 by Simon Peyton Jones at 2026-10-13T18:10:39-04:00
Refactor TyCoMapper to take a single monad; add StrictReaderT
TyCoMapper used to be parameterised over both an environment and a
monad, with fields like
tcm_tyvar :: env -> TyVar -> m Type
Now it is parameterised over just the monad:
tcm_tyvar :: TyVar -> m Type
If the mapping needs an environment, `m` is a reader monad over that
environment. Many uses (e.g. zonkTcTypeMapper, swizzleMapper) need no
environment at all, and used to pass a dummy (). The binder field
becomes
tcm_tycobinder :: forall r. TyCoVar -> ForAllTyFlag
-> (TyCoVar -> m r) -> m r
and runs the continuation in the extended environment. mapTyCoX is gone;
only mapTyCo remains.
To make this efficient, the reader monad must use the one-shot trick and
be strict in the environment. So:
* New module GHC.Utils.Monad.StrictReader defines
newtype StrictReaderT r m a
with hand-written instances. The builder of the pattern synonym
`StrictReaderT` is a smart constructor that adds both `oneShot` and a
bang on the environment, so every StrictReaderT computation is strict
in the environment. See Note [Instances for StrictReaderT].
* ZonkT becomes type ZonkT = StrictReaderT ZonkEnv
ZonkM becomes type ZonkM = StrictReaderT ZonkGblEnv IO
replacing their own hand-written instances.
* Substitution uses
type SubstM = StrictReaderT Subst StrictIdentity
substTyCoMapper :: TyCoMapper SubstM
and similarly expandTypeSynonymMapper.
* zonk_tycomapper :: TyCoMapper (ZonkT TcM) is now much simpler.
* swizzleMapper uses StrictIdentity rather than Identity.
* Module renaming, so that the strict monads are all peers in GHC.Utils.Monad:
GHC.Utils.StrictIdentity ==> GHC.Utils.Monad.StrictIdentity
GHC.Utils.Monad.State.Strict ==> GHC.Utils.Monad.StrictState
alongside the new GHC.Utils.Monad.StrictReader.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
c0299e15 by Simon Jakobi at 2026-10-13T18:11:23-04:00
testsuite: Line-buffer the driver's stdout
Python block-buffers stdout when it is a pipe. This is the case for
example in CI. As a result there is often no indication of progress at
all until the run ends.
To fix this, we configure it explicitly to use line buffering instead.
stderr is reconfigured too, for consistency: Python line-buffers it by
default since 3.9.
The type-ignores are for mypy, which types these handles as TextIO — an
interface without reconfigure.
Fixes #12934.
Assisted-by: Claude Fable 5
- - - - -
9b5beaa2 by Florian Ragwitz at 2026-10-13T18:12:05-04:00
hpc: Improve coverage semantics for instance methods and instances
Users care about which of their explicitly written methods are or aren't
covered, not whether all of the inherited methods are covered as well. Those
should be covered where they are implemented.
We therefore skip generating top-level boxes for inherited methods which will
appear as uncovered with no clear indication as to why, and no way to fix other
than exercising code the user has not written.
Previously, top-level boxes for those inherited methods would use the instance
head as their source span. Now that those boxes are gone, we can use that
source span for another purpose:
We introduce a new top-level box for each class instance with its instance head
as the source span, and use that to indicate whether or not an instance has
been covered at all.
We do this by making any method of the instance, inherited/generated or
otherwise, tick the box for the instance head. Excluded from this are
methodless classes, which could never be covered using the current mechanism.
This could be improved upon further.
These changes apply to ticking for program coverage only, and don't affect
source notes. Additionally, we update the scope of record selector ticking to
be limited to program coverage as well, as the oversight to also extend it to
source notes has previously caused bugs and because record selector ticking is
coverage-specific.
Fixes #17155, #15932.
- - - - -
836ec50a by Simon Peyton Jones at 2026-10-13T18:12:54-04:00
Refactor fundeps again
This MR fixes #27828; there was a bad scoping error in `trim_qtvs`.
The main changes are
* Refactor `trim_qtvs` completely to eliminate the bug.
* Remove a redundant `apartnessCheck` from `mkTopOpenFamEqFDs`.
* Lots of improvements to the Notes in FunDeps.hs
I also did a couple of pure refactors:
* I realised that we were carefully caching `cab_incomps` in each
`CoAxBranch`, to make it more efficient to reduce a type family application,
but we were not doing the same thing when computing relevance for functional
dependencies; see Note [Relevance] in GHC.Tc.Solver.FunDeps. So I added
`cab_overlaps`, which is now used in `noEarlierMatch`.
* Use a proper data types, `AmIUnifying` and `OuterKindsFlag`, for two
previously-Boolean arguments to `tc_unify_tys`. This is a pure refactor.
- - - - -
889ef371 by Simon Peyton Jones at 2026-10-13T18:13:36-04:00
Refactor and simplify solver's unification code
Ticket #27844 showed that GHC's constraint solver could miss an
occurs check, and thereby build an infinite type.
This patch significantly simplifes the code in
GHC.Tc.Solver.Equality.canEqCanLHSFinish_try_unification
GHC.Tc.Solver.Equality.canEqCanLHSFinish_no_unification
It is now significantly simpler, and requires much less subtle
reasoning to understand.
Main changes
* If `canEqCanLHSFinish_try_unification` fails to unify, it now /always/ calls
`canEqCanLHSFinish_no_unification` rather than trying to finish the job itself.
* `GHC.Tc.Solver.Monad.checkTypeEq` is moved from Monad into Equality, and renamed
to `GHC.Tc.Solver.Equality.checkTypeEqNoUnification`.
* `canEqCanLHSFinish_no_unification` calls `checkTypeEqNoUnification` to test
the invariants for an inert equality. Before this MR there was a special case for
`do_not_prevent_rewriting`, but that has gone; instead it's just a consequence of
the flags passed to `checkTyEqRhs`, documented in the `PuOK` case of
`canEqCanLHSFinish_no_unification`.
* There is only one bit of "swap back" code, in `finish_no_unify` in
`canEqCanLHSFinish_try_unification. Previously this code was duplicated.
* `kickOutAfterFillingCoercionHole` should account for equalities with a
TyFamLHS. See (KOC5) in Note [Kick out after filling a coercion hole]
* No need to gather coercion holes in the `PuOK` case of `canEqCanLHSFinish_no_unification`.
See documentation with that code.
- - - - -
f9193e53 by Simon Peyton Jones at 2026-10-13T18:13:37-04:00
One line fix to fallout from
...#27731, !16564, simplifying Tc.Errors machinery
There was an over-eager assert!
- - - - -
cdd56b7a by Florian Ragwitz at 2026-10-13T18:14:19-04:00
Fix several sphinx errors and warnings from rendering the release notes
The extension references which are removed here are for extension which were
already previously undocumented, so just removing them seems fine for now.
- - - - -
4f00da25 by Florian Ragwitz at 2026-10-13T18:14:19-04:00
Link to QualifiedStrings documentation
- - - - -
97adaf89 by Simon Peyton Jones at 2026-10-14T00:07:27+01:00
Line up simpleUnifyCheck and check_ty_eq_rhs
Even after #26543 was allegedly fixed, the original repo case in the
Description continued to fail. The reason was that the QuickLook
unifier, `qlUnify`, used `simpleUnifyCheck` for checking unification
invariants; and `simpleUnifyCheck` conservatively rejected any RHS
with a coercion hole in it. The upshot was that QuickLook was not
as clever as it should be, wrongly failing to do an impredicative
instantiation.
Interestingly `check_ty_eq_rhs`, which does the same job during
constraint solving, was more liberal: it just looked at the free vars
of the coercion, and allowed coercion holes.
This MR lines them up, adding some careful notes. See
Note [simpleUnifyCheck]
Note [Occurs check and coercions]
Note [Unification preconditions] esp (COERCIONS)
Things are better than before, but I am still uncomfortable about the
possibilty that a hole might be filled with a coercion that mentions
the LHS type variable; for now I have left this discomfort documented
in Note [Occurs check and coercions].
Main changes
* `qlUnify` now only unifies /instantiation variables/ not regular unification
variables. This makes QuickLook more predictable. See (UQL6) in
Note [QuickLook unification].
* `qlUnify` no longer needs to call `simpleUnifyCheck`, so we can get rid of
`UC_QuickLook` and its code in `simpleUnifyCheck`.
* I found I could get rid of `mkOccFolders` in favour of `anyFreeVarsOfType`.
Hooray.
* Improve documentation of CycleBreakerTv, and rename it to GivenCycleBreakerTv
because they are only uesd for Givens!
* I accepted a 9% worsening in compile time allocation on T5030
because the newly-consistent story triggered #27934.
Other changes
* I refactored `atvFolder` so that it pairs the "interesting-var" function
with the in-scope set, to avoid building a closure with a free variable.
Now we get nice tight loops for `anyFreeVarsOfType` and friends.
See Note [Any-free-var folder].
Metric Increase:
T5030
- - - - -
5f7b3047 by Simon Peyton Jones at 2026-10-14T00:07:27+01:00
Fix order-dependence in QuickLook
Ticket #27917 pointed out that QuickLook was order-dependent
-- very bad!
The solution is in `qlUnify`: spot when we are unifying a type with a
definite monotype, and then monomorphise any free instantiation
variables of that type.
See (UQL8) and (UQL9) in Note [QuickLook unification].
- - - - -
c391c70c by Simon Peyton Jones at 2026-10-14T00:07:28+01:00
Add some comments about RuntimeUnk
This commit just adds comments explaining why we don't need to worry about
RuntimeUnkTv in the constraint solver.
It also tightens up docmentation of earlier (overlapping) commits in
this MR.
- - - - -
7df3ba2f by Andrea Vezzosi at 2026-10-14T06:15:48-04:00
add runGhcWithSignalHandlers and remove handling from runGhc[T]
it only ever makes sense to call `withSignalHandlers` from `main`, otherwise
signals can be too easily swallowed without notification to the rest of your
process.
This commit takes withSignalHandlers out of `runGhc/runGhcT` and provides
`runGhcWithSignalHandlers` for the old behaviour.
- - - - -
3a72b8a2 by Hannes Siebenhandl at 2026-10-14T13:48:32-04:00
Fix #27836, normalise unit database path in ExternalUnitDatabases
Add a regression test, proofing that all variations:
- local-unit-db/my-test.conf
- ./local-unit-db/my-test.conf
- ./local-unit-db/my-test.conf/
are parsed only once.
- - - - -
8ddbc6f9 by Florian Ragwitz at 2026-10-14T13:49:28-04:00
Remove obsolete HPC types
Fixes #27946.
- - - - -
f34c79ee by Alan Zimmerman at 2026-10-15T04:54:47-04:00
EPA: Start using vocurly as basis for AnnListLayout
For the existing cases that populate AnnList.
This uses AnnListBraces when braces are explicitly supplied, and
AnnListLayout when vocurly is used
The change also shows up AnnList usages that can never capture layout,
these are cleared up later.
- - - - -
033ba59c by sheaf at 2026-10-15T04:55:44-04:00
Make exprFreeVars deep
exprFreeVars used to be a shallow free-variable finder (it didn't look
into kinds), but most callers wanted it to be deep. In particular,
'exprFreeVars' is often used to seed an 'InScopeSet', and that must
contain the /deep/ free variables.
This commit makes it deep, which allows us to get rid of calls to
'closeOverKinds' or other workarounds for shallowness in:
- 'GHC.Core.Opt.Simplify.Utils.abstractFloats'
- 'GHC.HsToCore.Binds.dsSpec_help'
- 'GHC.Core.Opt.Arity.etaBodyForJoinPoint'
- 'GHC.Core.FVs.freeVars'
- 'GHC.Core.Lint.lintCoreRule'
We also remove 'deepExprsFreeVarsDSet' and 'closeOverKindsDSet'.
Other places needed a little bit more care, in particular to properly
handle coercion variables free in kinds:
- 'GHC.Core.Opt.Specialise.specHeader' quantifies over the binder of
an unspecialised argument directly, instead of computing the free Ids
of the argument.
- 'GHC.HsToCore.dsWarnRuleShadowing' filters out 'CoVar's.
- 'GHC.Core.Opt.SpecConstr.callToPat' had some ad-hoc logic to compute
argument pattern types and a workaround with 'expandTypeSynonyms'.
That logic is removed in favour of a new 'argsToPats' function which
directly computes the argument pattern types by instantiating the
type of the head of the call pattern.
Fixes #27936
- - - - -
f93d523c by Luite Stegeman at 2026-10-15T04:56:34-04:00
testsuite: Use mkWeakMVar in memo001/memo002
mkWeakPtr in the memo001/memo001 tests created weak pointers
with the MVar box as the key, which is fragile in the presence
of optimization. The fix is using mkWeakMVar, keying on the
primitive MVar# instead.
Fixes #27924 and #27396
- - - - -
dc31cff5 by Wolfgang Jeltsch at 2026-10-15T14:27:19+03:00
Add test for `base` being buildable with released GHCs
- - - - -
4d0fe936 by Wolfgang Jeltsch at 2026-10-15T14:27:19+03:00
Switch to GHC 9.14.2
- - - - -
61b5e42c by Wolfgang Jeltsch at 2026-10-15T14:27:20+03:00
Make .gitlab/base-ci.sh` executable
- - - - -
e83f8003 by Wolfgang Jeltsch at 2026-10-15T14:27:20+03:00
Change the GHC version number back to 9.14.1
- - - - -
8997fc5e by Wolfgang Jeltsch at 2026-10-15T14:27:20+03:00
Enable error propagation in `.gitlab/base-ci.sh`
- - - - -
9366b2d2 by Wolfgang Jeltsch at 2026-10-15T14:27:20+03:00
Remove the accidental restriction to exactly one GHC
- - - - -
693524bb by Wolfgang Jeltsch at 2026-10-15T14:27:20+03:00
Make relative directories absolute
- - - - -
ee6ce787 by Wolfgang Jeltsch at 2026-10-15T14:27:20+03:00
Make `${project_root}` available to all code
- - - - -
829424ea by Wolfgang Jeltsch at 2026-10-15T14:27:20+03:00
Add missing newline escaping
- - - - -
c16c2d67 by Wolfgang Jeltsch at 2026-10-15T14:27:20+03:00
Fix the GHC installation path
- - - - -
55762868 by Wolfgang Jeltsch at 2026-10-15T14:27:20+03:00
Move the definition of `withEmptyCallStack` into `base`
- - - - -
258daf38 by Wolfgang Jeltsch at 2026-10-15T14:27:20+03:00
Change tag `x86_64-windows` to `new-x86_64-windows`
- - - - -
2fd2ee93 by Wolfgang Jeltsch at 2026-10-15T14:27:20+03:00
Change the actual installation procedure for Windows
- - - - -
8f84fd84 by Wolfgang Jeltsch at 2026-10-15T14:27:20+03:00
Switch to using a `Setup.hs` file
- - - - -
379d6f63 by Wolfgang Jeltsch at 2026-10-15T14:27:20+03:00
Add conditional import of `GHC.Essentials`
- - - - -
5c6aba31 by Wolfgang Jeltsch at 2026-10-15T14:27:20+03:00
Make the use of `-frebindable-known-names` conditional
- - - - -
ee67c01e by Wolfgang Jeltsch at 2026-10-15T14:27:20+03:00
Disable the inclusion of `GHC.Essentials` for older GHCs
- - - - -
0ff93adf by Wolfgang Jeltsch at 2026-10-15T14:27:20+03:00
Make only `-fdefines-known-key-names` conditional
- - - - -
29a8ae0e by Wolfgang Jeltsch at 2026-10-16T00:10:06+03:00
Make `CString`-related imports compatible with GHC 9.14.1
- - - - -
aafe84d9 by Wolfgang Jeltsch at 2026-10-16T00:56:17+03:00
Add a conditional `pfail` import for compatibility with GHC 9.14.1
- - - - -
9a224923 by Wolfgang Jeltsch at 2026-10-16T01:42:36+03:00
Reintroduce import of `Fingerprint` basics for GHC 9.14.1
- - - - -
35b27e2d by Wolfgang Jeltsch at 2026-10-16T22:11:04+03:00
Undo the changes to `GHC.Essentials`
- - - - -
e2047dd5 by Wolfgang Jeltsch at 2026-10-16T23:42:45+03:00
Remove `GHC.Essentials` for GHC 9.14.1
- - - - -
607 changed files:
- .gitlab-ci.yml
- + .gitlab/base-ci.sh
- .gitlab/ci.sh
- .gitlab/hello.hs
- + changelog.d/24450
- + changelog.d/25763-cmdline-opt
- + changelog.d/26610
- changelog.d/26616
- + changelog.d/26761
- + changelog.d/27641
- + changelog.d/27732
- + changelog.d/27845
- + changelog.d/27936
- + changelog.d/T23785
- + changelog.d/T26543
- changelog.d/T27329
- changelog.d/T27455
- + changelog.d/T27545
- + changelog.d/T27629
- + changelog.d/T27731
- + changelog.d/T27788-js-selector
- + changelog.d/T27828
- + changelog.d/T27830-rts-flag-bounds
- + changelog.d/T27844
- + changelog.d/T27916
- + changelog.d/T4162
- + changelog.d/boxing-family
- + changelog.d/clc-341-strict-mutable-data-types
- + changelog.d/clc-421
- + changelog.d/fix-compacting-gc-constr-27649
- + changelog.d/fix-control0-mask-trampoline
- + changelog.d/fix-cross-ghc-info-unit-id
- changelog.d/fix-parallel-gc-selector-race-27477
- + changelog.d/fix-threadlabel-segfault-27618
- + changelog.d/hadrian-persist-flavour
- + changelog.d/hpc-classinsts
- + changelog.d/hpc-cleanup
- + changelog.d/select-io-manager
- changelog.d/semaphore-v2
- changelog.d/tcplugin_init.md
- changelog.d/unit-index
- compiler/GHC.hs
- compiler/GHC/Builtin.hs
- compiler/GHC/Builtin/KnownKeys.hs
- compiler/GHC/Builtin/Modules.hs
- compiler/GHC/Builtin/Uniques.hs
- compiler/GHC/Builtin/WiredIn/Ids.hs
- compiler/GHC/Builtin/WiredIn/Prim.hs
- compiler/GHC/Builtin/WiredIn/TypeLits.hs
- compiler/GHC/Builtin/WiredIn/Types.hs
- + compiler/GHC/Builtin/WiredIn/Types/Box.hs
- compiler/GHC/Builtin/primops.txt.pp
- compiler/GHC/ByteCode/Asm.hs
- compiler/GHC/ByteCode/Show.hs
- compiler/GHC/Cmm/GenericOpt.hs
- compiler/GHC/Cmm/UniqueRenamer.hs
- compiler/GHC/CmmToAsm/Dwarf/Types.hs
- compiler/GHC/CmmToAsm/Monad.hs
- compiler/GHC/CmmToAsm/Reg/Graph/Spill.hs
- compiler/GHC/CmmToAsm/Reg/Graph/SpillClean.hs
- compiler/GHC/CmmToAsm/Reg/Graph/SpillCost.hs
- compiler/GHC/CmmToAsm/Reg/Graph/Stats.hs
- compiler/GHC/CmmToAsm/Reg/Linear/State.hs
- compiler/GHC/CmmToAsm/Reg/Linear/Stats.hs
- compiler/GHC/CmmToAsm/Reg/Liveness.hs
- compiler/GHC/CmmToAsm/Wasm/Asm.hs
- compiler/GHC/CmmToAsm/Wasm/Types.hs
- compiler/GHC/CmmToC.hs
- compiler/GHC/Core/Coercion.hs
- compiler/GHC/Core/Coercion.hs-boot
- compiler/GHC/Core/Coercion/Axiom.hs
- compiler/GHC/Core/Coercion/Opt.hs
- compiler/GHC/Core/DataCon.hs
- compiler/GHC/Core/FVs.hs
- compiler/GHC/Core/FamInstEnv.hs
- compiler/GHC/Core/Lint.hs
- compiler/GHC/Core/Make.hs
- + compiler/GHC/Core/Make/BigTuple.hs
- + compiler/GHC/Core/Make/Box.hs
- compiler/GHC/Core/Map/Type.hs
- compiler/GHC/Core/Opt/Arity.hs
- compiler/GHC/Core/Opt/CallerCC.hs
- compiler/GHC/Core/Opt/CallerCC/Types.hs
- compiler/GHC/Core/Opt/Exitify.hs
- compiler/GHC/Core/Opt/SetLevels.hs
- compiler/GHC/Core/Opt/Simplify/Utils.hs
- compiler/GHC/Core/Opt/SpecConstr.hs
- compiler/GHC/Core/Opt/Specialise.hs
- compiler/GHC/Core/Opt/WorkWrap/Utils.hs
- compiler/GHC/Core/Reduction.hs
- compiler/GHC/Core/Seq.hs
- compiler/GHC/Core/Subst.hs
- compiler/GHC/Core/TyCo/Compare.hs
- compiler/GHC/Core/TyCo/FVs.hs
- + compiler/GHC/Core/TyCo/Make.hs
- + compiler/GHC/Core/TyCo/Make.hs-boot
- compiler/GHC/Core/TyCo/Ppr.hs
- compiler/GHC/Core/TyCo/Rep.hs
- compiler/GHC/Core/TyCo/Rep.hs-boot
- compiler/GHC/Core/TyCo/Subst.hs
- compiler/GHC/Core/TyCon.hs
- compiler/GHC/Core/Type.hs
- compiler/GHC/Core/Type.hs-boot
- compiler/GHC/Core/Unify.hs
- compiler/GHC/CoreToIface.hs
- compiler/GHC/CoreToIface.hs-boot
- compiler/GHC/CoreToStg.hs
- compiler/GHC/CoreToStg/AddImplicitBinds.hs
- compiler/GHC/Data/FastString.hs
- compiler/GHC/Data/OsPath.hs
- + compiler/GHC/Data/StringTrie.hs
- compiler/GHC/Data/Word64Map/Internal.hs
- compiler/GHC/Data/Word64Map/Strict/Internal.hs
- compiler/GHC/Data/Word64Set/Internal.hs
- compiler/GHC/Driver/Backpack.hs
- compiler/GHC/Driver/CmdLine.hs
- compiler/GHC/Driver/Downsweep.hs
- compiler/GHC/Driver/Env.hs
- compiler/GHC/Driver/Errors/Ppr.hs
- compiler/GHC/Driver/Errors/Types.hs
- compiler/GHC/Driver/Main/Compile.hs
- compiler/GHC/Driver/Main/Passes.hs
- compiler/GHC/Driver/Pipeline.hs-boot
- compiler/GHC/Driver/Pipeline/Execute.hs
- compiler/GHC/Driver/Pipeline/Phases.hs
- compiler/GHC/Driver/Session.hs
- compiler/GHC/Hs/Doc.hs
- compiler/GHC/Hs/Dump.hs
- compiler/GHC/Hs/Expr.hs
- compiler/GHC/Hs/ImpExp.hs
- compiler/GHC/Hs/Lit.hs
- compiler/GHC/Hs/Pat.hs
- compiler/GHC/Hs/Utils.hs
- compiler/GHC/HsToCore.hs
- compiler/GHC/HsToCore/Arrows.hs
- compiler/GHC/HsToCore/Binds.hs
- compiler/GHC/HsToCore/Docs.hs
- compiler/GHC/HsToCore/Expr.hs
- compiler/GHC/HsToCore/ListComp.hs
- compiler/GHC/HsToCore/Match/Literal.hs
- compiler/GHC/HsToCore/Quote.hs
- compiler/GHC/HsToCore/Ticks.hs
- compiler/GHC/HsToCore/Utils.hs
- compiler/GHC/Iface/Decl.hs
- compiler/GHC/Iface/Errors/Types.hs
- compiler/GHC/Iface/Ext/Ast.hs
- compiler/GHC/Iface/Ext/Debug.hs
- compiler/GHC/Iface/Ext/Types.hs
- compiler/GHC/Iface/Ext/Utils.hs
- compiler/GHC/Iface/Load.hs
- compiler/GHC/Iface/Rename.hs
- compiler/GHC/Iface/Syntax.hs
- compiler/GHC/Iface/Tidy.hs
- compiler/GHC/Iface/Type.hs
- compiler/GHC/Iface/Type.hs-boot
- compiler/GHC/IfaceToCore.hs
- compiler/GHC/Parser.y
- compiler/GHC/Parser/Annotation.hs
- compiler/GHC/Parser/Errors/Types.hs
- compiler/GHC/Parser/Header.hs
- compiler/GHC/Parser/Lexer.x
- compiler/GHC/Parser/PostProcess.hs
- compiler/GHC/Parser/PostProcess/Haddock.hs
- compiler/GHC/Parser/String.hs
- compiler/GHC/Rename/Env.hs
- compiler/GHC/Rename/Module.hs
- compiler/GHC/Rename/Names.hs
- compiler/GHC/Rename/Unbound.hs
- compiler/GHC/Runtime/Heap/Inspect.hs
- compiler/GHC/Settings.hs
- compiler/GHC/Settings/IO.hs
- compiler/GHC/Stg/BcPrep.hs
- compiler/GHC/Stg/Debug.hs
- compiler/GHC/Stg/EnforceEpt/Rewrite.hs
- compiler/GHC/Stg/EnforceEpt/TagSig.hs
- compiler/GHC/Stg/Lint.hs
- compiler/GHC/Stg/Subst.hs
- compiler/GHC/StgToJS/Apply.hs
- compiler/GHC/StgToJS/CodeGen.hs
- compiler/GHC/StgToJS/ExprCtx.hs
- compiler/GHC/StgToJS/Linker/Linker.hs
- compiler/GHC/StgToJS/Symbols.hs
- compiler/GHC/Tc/Deriv.hs
- compiler/GHC/Tc/Deriv/Functor.hs
- compiler/GHC/Tc/Deriv/Generate.hs
- compiler/GHC/Tc/Deriv/Generics.hs
- compiler/GHC/Tc/Errors.hs
- compiler/GHC/Tc/Errors/Ppr.hs
- compiler/GHC/Tc/Errors/Types.hs
- compiler/GHC/Tc/Gen/App.hs
- compiler/GHC/Tc/Gen/Export.hs
- compiler/GHC/Tc/Gen/HsType.hs
- compiler/GHC/Tc/Gen/Match.hs
- compiler/GHC/Tc/Gen/Pat.hs
- compiler/GHC/Tc/Gen/Splice.hs
- compiler/GHC/Tc/Instance/Family.hs
- compiler/GHC/Tc/Instance/FunDeps.hs
- compiler/GHC/Tc/Instance/Typeable.hs
- compiler/GHC/Tc/Module.hs
- compiler/GHC/Tc/Solver/Default.hs
- compiler/GHC/Tc/Solver/Equality.hs
- compiler/GHC/Tc/Solver/FunDeps.hs
- compiler/GHC/Tc/Solver/InertSet.hs
- compiler/GHC/Tc/Solver/Monad.hs
- compiler/GHC/Tc/TyCl.hs
- compiler/GHC/Tc/TyCl/Instance.hs
- compiler/GHC/Tc/Types.hs
- compiler/GHC/Tc/Types/Constraint.hs
- compiler/GHC/Tc/Types/ErrCtxt.hs
- compiler/GHC/Tc/Utils/Backpack.hs
- compiler/GHC/Tc/Utils/Monad.hs
- compiler/GHC/Tc/Utils/TcMType.hs
- compiler/GHC/Tc/Utils/TcType.hs
- compiler/GHC/Tc/Utils/Unify.hs
- compiler/GHC/Tc/Zonk/Env.hs
- compiler/GHC/Tc/Zonk/Monad.hs
- compiler/GHC/Tc/Zonk/TcType.hs
- compiler/GHC/Tc/Zonk/Type.hs
- compiler/GHC/ThToHs.hs
- compiler/GHC/Types/Arity.hs
- compiler/GHC/Types/Basic.hs
- compiler/GHC/Types/CompleteMatch.hs
- compiler/GHC/Types/Cpr.hs
- compiler/GHC/Types/Demand.hs
- compiler/GHC/Types/Id.hs
- compiler/GHC/Types/Id/Info.hs
- compiler/GHC/Types/Id/Make.hs
- compiler/GHC/Types/Name/Env.hs
- compiler/GHC/Types/Name/Occurrence.hs
- compiler/GHC/Types/TyThing.hs
- compiler/GHC/Types/TyThing/Ppr.hs
- compiler/GHC/Types/Unique.hs
- compiler/GHC/Types/Unique/DSM.hs
- compiler/GHC/Types/Unique/FM.hs
- compiler/GHC/Types/Unique/Map.hs
- compiler/GHC/Types/Unique/Set.hs
- compiler/GHC/Types/Unique/Supply.hs
- compiler/GHC/Types/UnresolvedImport.hs
- compiler/GHC/Types/Var.hs
- compiler/GHC/Types/Var.hs-boot
- compiler/GHC/Types/Var/FV.hs
- compiler/GHC/Types/Var/Set.hs
- compiler/GHC/Unit/Env.hs
- compiler/GHC/Unit/External/Database.hs
- compiler/GHC/Unit/External/Wired.hs
- compiler/GHC/Unit/Home.hs
- compiler/GHC/Unit/Module.hs
- compiler/GHC/Unit/Module/Env.hs
- + compiler/GHC/Unit/Module/Name.hs
- compiler/GHC/Unit/Parser.hs
- compiler/GHC/Unit/State.hs
- compiler/GHC/Unit/Types.hs
- compiler/GHC/Unit/Types.hs-boot
- compiler/GHC/Utils/Binary.hs
- + compiler/GHC/Utils/Monad/StrictIdentity.hs
- + compiler/GHC/Utils/Monad/StrictReader.hs
- compiler/GHC/Utils/Monad/State/Strict.hs → compiler/GHC/Utils/Monad/StrictState.hs
- compiler/GHC/Utils/Outputable.hs
- compiler/GHC/Utils/Panic.hs
- compiler/Language/Haskell/Syntax.hs
- compiler/Language/Haskell/Syntax/Expr.hs
- compiler/Language/Haskell/Syntax/ImpExp.hs
- compiler/Language/Haskell/Syntax/Lit.hs
- compiler/Language/Haskell/Syntax/Module/Name.hs
- compiler/Language/Haskell/Syntax/Specificity.hs
- compiler/Language/Haskell/Syntax/Text.hs
- compiler/ghc.cabal.in
- distrib/configure.ac.in
- docs/users_guide/exts/literals.rst
- docs/users_guide/exts/type_data.rst
- docs/users_guide/runtime_control.rst
- ghc/GHC/Driver/Session/Mode.hs
- ghc/GHCi/UI.hs
- ghc/GHCi/UI/Info.hs
- ghc/Main.hs
- hadrian/bindist/Makefile
- hadrian/bindist/config.mk.in
- hadrian/doc/flavours.md
- hadrian/ghci-multi-cabal.in
- hadrian/src/Rules.hs
- hadrian/src/Rules/BinaryDist.hs
- hadrian/src/Rules/Generate.hs
- hadrian/src/Settings.hs
- libraries/base/base.cabal.in
- libraries/base/changelog.md
- libraries/base/src/Control/Concurrent/Chan.hs
- + libraries/base/src/Control/Concurrent/Chan/Strict.hs
- libraries/base/src/Control/Concurrent/MVar.hs
- + libraries/base/src/Control/Concurrent/MVar/Strict.hs
- libraries/base/src/Data/Fixed.hs
- libraries/base/src/Data/IORef.hs
- + libraries/base/src/Data/IORef/Strict.hs
- libraries/base/src/GHC/Base.hs
- libraries/base/src/GHC/Exts.hs
- libraries/base/src/GHC/Fingerprint.hs
- libraries/base/src/GHC/RTS/Flags.hs
- libraries/base/src/GHC/Stack.hs
- libraries/base/src/System/Info.hs
- libraries/base/tests/Memo1.lhs
- libraries/base/tests/Memo2.lhs
- libraries/base/tests/all.T
- libraries/containers
- libraries/ghc-internal/ghc-internal.cabal.in
- libraries/ghc-internal/include/RtsIfaceSymbols.h
- libraries/ghc-internal/src/GHC/Internal/Bits.hs
- + libraries/ghc-internal/src/GHC/Internal/Box.hs
- libraries/ghc-internal/src/GHC/Internal/Conc/IO.hs
- libraries/ghc-internal/src/GHC/Internal/Event/Thread.hs
- libraries/ghc-internal/src/GHC/Internal/Exts.hs
- libraries/ghc-internal/src/GHC/Internal/IO/Exception.hs
- libraries/ghc-internal/src/GHC/Internal/RTS/Flags.hsc
- libraries/ghc-internal/src/GHC/Internal/Stack.hs
- libraries/ghc-internal/src/GHC/Internal/TypeNats.hs
- libraries/ghc-internal/src/GHC/Internal/Types.hs
- linters/lint-codes/LintCodes/Static.hs
- m4/subst_tooldir.m4
- rts/Capability.c
- rts/ContinuationOps.cmm
- rts/HeapStackCheck.cmm
- rts/IOManager.c
- rts/IOManager.h
- rts/IOManagerInternals.h
- rts/Messages.c
- rts/Prelude.h
- rts/PrimOps.cmm
- rts/Printer.c
- rts/RaiseAsync.c
- rts/RtsFlags.c
- rts/RtsStartup.c
- rts/STM.c
- rts/Schedule.c
- rts/Sparks.c
- rts/StableName.c
- rts/StgMiscClosures.cmm
- rts/ThreadPaused.c
- rts/Threads.c
- rts/Trace.h
- rts/configure.ac
- rts/include/rts/Flags.h
- rts/include/rts/RtsToHsIface.h
- rts/include/rts/storage/Closures.h
- rts/include/rts/storage/GC.h
- rts/include/stg/MiscClosures.h
- rts/include/stg/Prim.h
- rts/posix/Poll.c
- rts/posix/Poll.h
- rts/posix/Select.c
- + rts/posix/SelectBis.c
- + rts/posix/SelectBis.h
- rts/posix/Timeout.c
- rts/posix/Timeout.h
- rts/prim/bitrev.c
- rts/prim/bswap.c
- rts/rts.cabal
- rts/sm/Compact.c
- rts/sm/Evac.c
- rts/sm/GC.c
- rts/sm/GCUtils.c
- rts/sm/MBlock.c
- rts/sm/NonMoving.c
- rts/sm/NonMovingMark.c
- rts/sm/Storage.c
- rts/sm/Sweep.c
- testsuite/driver/junit.py
- testsuite/driver/runtests.py
- testsuite/driver/testglobals.py
- testsuite/driver/testlib.py
- testsuite/tests/MiniQuickCheck.hs
- testsuite/tests/arrows/should_run/all.T
- + testsuite/tests/arrows/should_run/arrowrun005.hs
- + testsuite/tests/arrows/should_run/arrowrun005.stdout
- + testsuite/tests/backpack/should_compile/T27835.bkp
- + testsuite/tests/backpack/should_compile/T27835.stderr
- testsuite/tests/backpack/should_compile/all.T
- testsuite/tests/codeGen/should_run/all.T
- testsuite/tests/count-deps/CountDepsAst.stdout
- testsuite/tests/count-deps/CountDepsParser.stdout
- + testsuite/tests/deSugar/should_compile/T25065a.hs
- testsuite/tests/deSugar/should_compile/all.T
- + testsuite/tests/deSugar/should_run/T20864.hs
- + testsuite/tests/deSugar/should_run/T20864.stdout
- + testsuite/tests/deSugar/should_run/T25065b.hs
- + testsuite/tests/deSugar/should_run/T25065b.stdout
- testsuite/tests/deSugar/should_run/all.T
- testsuite/tests/default/default-fail05.stderr
- + testsuite/tests/dmdanal/should_run/T27845.hs
- + testsuite/tests/dmdanal/should_run/T27845.stdout
- + testsuite/tests/dmdanal/should_run/T27845_Lib.hs
- + testsuite/tests/dmdanal/should_run/T27845b.hs
- + testsuite/tests/dmdanal/should_run/T27845b.stdout
- + testsuite/tests/dmdanal/should_run/T27845b_Lib.hs
- testsuite/tests/dmdanal/should_run/all.T
- + testsuite/tests/driver/T27836/A.hs
- + testsuite/tests/driver/T27836/B.hs
- + testsuite/tests/driver/T27836/C.hs
- + testsuite/tests/driver/T27836/Makefile
- + testsuite/tests/driver/T27836/T27836.stdout
- + testsuite/tests/driver/T27836/all.T
- + testsuite/tests/driver/T27836/unitA
- + testsuite/tests/driver/T27836/unitB
- + testsuite/tests/driver/T27836/unitC
- testsuite/tests/driver/all.T
- testsuite/tests/driver/multipleHomeUnits/mhu-closure/Makefile
- testsuite/tests/driver/multipleHomeUnits/mhu-closure/mhu-closure.stderr
- testsuite/tests/driver/multipleHomeUnits/mhu-closure/mhu-closure.stdout
- + testsuite/tests/driver/stringtrie.hs
- + testsuite/tests/driver/stringtrie.stdout
- testsuite/tests/ghc-api/T25121_status.stdout
- + testsuite/tests/ghc-api/T4162.hs
- + testsuite/tests/ghc-api/T4162.stdout
- testsuite/tests/ghc-api/all.T
- testsuite/tests/ghc-api/downsweep/IncrementalDownsweep.hs
- testsuite/tests/ghc-api/exactprint/T22919.stderr
- testsuite/tests/ghc-api/exactprint/Test20239.stderr
- testsuite/tests/ghc-api/exactprint/ZeroWidthSemi.stderr
- testsuite/tests/ghci.debugger/scripts/T14628.stderr
- + testsuite/tests/ghci/prog-mhu008/Makefile
- + testsuite/tests/ghci/prog-mhu008/a/M.hs
- + testsuite/tests/ghci/prog-mhu008/all.T
- + testsuite/tests/ghci/prog-mhu008/b/M.hs
- + testsuite/tests/ghci/prog-mhu008/prog-mhu008.script
- + testsuite/tests/ghci/prog-mhu008/prog-mhu008.stdout
- + testsuite/tests/ghci/prog-mhu008/unitA
- + testsuite/tests/ghci/prog-mhu008/unitB
- testsuite/tests/ghci/prog020/ghci.prog020a.stderr
- testsuite/tests/ghci/prog020/ghci.prog020b.stderr
- testsuite/tests/ghci/prog021/prog021a.stderr
- testsuite/tests/ghci/prog021/prog021b.stderr
- testsuite/tests/ghci/prog022/ghci.prog022a.stderr
- testsuite/tests/ghci/prog022/ghci.prog022b.stderr
- testsuite/tests/ghci/prog022/ghci.prog022c.stderr
- testsuite/tests/ghci/prog022/ghci.prog022d.stderr
- testsuite/tests/ghci/prog022/ghci.prog022e.stderr
- testsuite/tests/ghci/prog022/ghci.prog022f.stderr
- testsuite/tests/ghci/scripts/Defer02.stderr
- + testsuite/tests/ghci/scripts/T27641.script
- + testsuite/tests/ghci/scripts/T27641.stderr
- + testsuite/tests/ghci/scripts/T27641.stdout
- + testsuite/tests/ghci/scripts/T27834.hs
- + testsuite/tests/ghci/scripts/T27834.script
- + testsuite/tests/ghci/scripts/T27834.stdout
- testsuite/tests/ghci/scripts/all.T
- testsuite/tests/haddock/should_compile_flag_haddock/T17544.stderr
- testsuite/tests/haddock/should_compile_flag_haddock/T17544_kw.stderr
- testsuite/tests/haddock/should_compile_flag_haddock/T24221.stderr
- testsuite/tests/hiefile/should_run/T24544.hs
- + testsuite/tests/hpc/instmeths/instmeths.hs
- + testsuite/tests/hpc/instmeths/instmeths.stdout
- + testsuite/tests/hpc/instmeths/test.T
- + testsuite/tests/impredicative/T27917.hs
- testsuite/tests/impredicative/all.T
- + testsuite/tests/indexed-types/should_compile/T27828.hs
- + testsuite/tests/indexed-types/should_compile/T27828a.hs
- + testsuite/tests/indexed-types/should_compile/T27828b.hs
- testsuite/tests/indexed-types/should_compile/all.T
- testsuite/tests/indexed-types/should_fail/T1897b.stderr
- testsuite/tests/indexed-types/should_fail/T9662.stderr
- + testsuite/tests/indexed-types/should_run/T27331.hs
- + testsuite/tests/indexed-types/should_run/T27331.stdout
- + testsuite/tests/indexed-types/should_run/T27331b.hs
- + testsuite/tests/indexed-types/should_run/T27331b.stdout
- + testsuite/tests/indexed-types/should_run/T27331b_Plugin.hs
- testsuite/tests/indexed-types/should_run/all.T
- testsuite/tests/interface-stability/base-exports.stdout
- testsuite/tests/interface-stability/base-exports.stdout-javascript-unknown-ghcjs
- testsuite/tests/interface-stability/base-exports.stdout-mingw32
- testsuite/tests/interface-stability/ghc-experimental-exports.stdout
- testsuite/tests/interface-stability/ghc-experimental-exports.stdout-mingw32
- testsuite/tests/interface-stability/ghc-prim-exports.stdout
- testsuite/tests/interface-stability/ghc-prim-exports.stdout-mingw32
- + testsuite/tests/javascript/T27788.hs
- + testsuite/tests/javascript/T27788.stdout
- testsuite/tests/javascript/all.T
- testsuite/tests/linters/notes.stdout
- testsuite/tests/module/mod130.stderr
- testsuite/tests/module/mod185.stderr
- + testsuite/tests/numeric/should_run/T27545.hs
- + testsuite/tests/numeric/should_run/T27545.stdout
- testsuite/tests/numeric/should_run/all.T
- testsuite/tests/overloadedstrings/should_fail/T25926.stderr
- testsuite/tests/overloadedstrings/should_fail/T27124.stderr
- testsuite/tests/package/T4806a.stderr
- testsuite/tests/package/all.T
- testsuite/tests/parser/should_compile/DumpParsedAst.stderr
- testsuite/tests/parser/should_compile/DumpParsedAstComments.stderr
- testsuite/tests/parser/should_compile/DumpRenamedAst.stderr
- testsuite/tests/parser/should_compile/DumpSemis.stderr
- testsuite/tests/parser/should_compile/KindSigs.stderr
- testsuite/tests/parser/should_compile/T14189.stderr
- testsuite/tests/parser/should_compile/T15279.stderr
- testsuite/tests/parser/should_compile/T15323.stderr
- testsuite/tests/parser/should_compile/T20452.stderr
- testsuite/tests/parser/should_compile/T20718.stderr
- testsuite/tests/parser/should_compile/T20718b.stderr
- testsuite/tests/parser/should_compile/T20846.stderr
- testsuite/tests/parser/should_compile/T23315/T23315.stderr
- testsuite/tests/patsyn/should_fail/records-nofieldselectors.stderr
- + testsuite/tests/perf/compiler/T25763.stderr
- testsuite/tests/perf/compiler/all.T
- + testsuite/tests/plugins/T26761.hs
- + testsuite/tests/plugins/T26761.stderr
- + testsuite/tests/plugins/T26761Plugin.hs
- + testsuite/tests/plugins/T26761a.hs
- testsuite/tests/plugins/all.T
- + testsuite/tests/primops/should_run/T27299.hs
- + testsuite/tests/primops/should_run/T27299.stdout
- testsuite/tests/primops/should_run/all.T
- testsuite/tests/printer/AnnotationNoListTuplePuns.stdout
- testsuite/tests/printer/T17697.stderr
- testsuite/tests/printer/T18791.stderr
- testsuite/tests/printer/Test20297.stdout
- testsuite/tests/printer/Test24533.stdout
- testsuite/tests/profiling/should_run/caller-cc/CallerCcParser.hs
- testsuite/tests/rename/should_fail/T15607.stderr
- testsuite/tests/rename/should_fail/T19843b.stderr
- + testsuite/tests/rts/T24450.hs
- + testsuite/tests/rts/T24450.stderr
- + testsuite/tests/rts/T27618.hs
- + testsuite/tests/rts/T27618.stdout
- + testsuite/tests/rts/T27649.hs
- + testsuite/tests/rts/T27649.stdout
- testsuite/tests/rts/all.T
- + testsuite/tests/rts/continuations/T27651.hs
- + testsuite/tests/rts/continuations/T27651.stdout
- testsuite/tests/rts/continuations/all.T
- testsuite/tests/rts/rtsflags001.stderr-ws-32
- testsuite/tests/rts/rtsflags001.stderr-ws-64
- testsuite/tests/safeHaskell/ghci/p4.stderr
- testsuite/tests/safeHaskell/ghci/p6.stderr
- testsuite/tests/simplCore/should_compile/Makefile
- testsuite/tests/simplCore/should_compile/T22375.stderr
- testsuite/tests/simplCore/should_compile/T22375DataFamily.stderr
- testsuite/tests/simplCore/should_compile/T22611.hs
- testsuite/tests/simplCore/should_compile/T22611.stderr
- + testsuite/tests/simplCore/should_compile/T22611a.hs
- + testsuite/tests/simplCore/should_compile/T27629.hs
- + testsuite/tests/simplCore/should_compile/T27629.stderr
- + testsuite/tests/simplCore/should_compile/T27629Plugin.hs
- + testsuite/tests/simplCore/should_compile/T27936.hs
- + testsuite/tests/simplCore/should_compile/T7803.hs
- + testsuite/tests/simplCore/should_compile/T7803.stderr
- + testsuite/tests/simplCore/should_compile/T7803a.hs
- testsuite/tests/simplCore/should_compile/all.T
- + testsuite/tests/type-data/should_fail/T27732a.hs
- + testsuite/tests/type-data/should_fail/T27732a.stderr
- + testsuite/tests/type-data/should_fail/T27732b.hs
- + testsuite/tests/type-data/should_fail/T27732b.stderr
- + testsuite/tests/type-data/should_fail/T27732c.hs
- + testsuite/tests/type-data/should_fail/T27732c.stderr
- + testsuite/tests/type-data/should_fail/T27732d.hs
- + testsuite/tests/type-data/should_fail/T27732d.stderr
- + testsuite/tests/type-data/should_fail/T27732e.hs
- + testsuite/tests/type-data/should_fail/T27732e.stderr
- + testsuite/tests/type-data/should_fail/T27732f.hs
- + testsuite/tests/type-data/should_fail/T27732f.stderr
- testsuite/tests/type-data/should_fail/TDStrictnessGADT.stderr
- testsuite/tests/type-data/should_fail/TDStrictnessH98.stderr
- testsuite/tests/type-data/should_fail/all.T
- testsuite/tests/typecheck/should_compile/LocalGivenEqs.hs
- testsuite/tests/typecheck/should_compile/T11254.stderr
- testsuite/tests/typecheck/should_compile/T15370.stderr
- + testsuite/tests/typecheck/should_compile/T26543_orig.hs
- + testsuite/tests/typecheck/should_compile/T27916.hs
- testsuite/tests/typecheck/should_compile/all.T
- testsuite/tests/typecheck/should_compile/valid_hole_fits.stderr
- testsuite/tests/typecheck/should_fail/ClassOperator.stderr
- testsuite/tests/typecheck/should_fail/DoExpansion2.stderr
- testsuite/tests/typecheck/should_fail/DoExpansion3.stderr
- testsuite/tests/typecheck/should_fail/FunDepOrigin1b.hs
- testsuite/tests/typecheck/should_fail/T12785b.stderr
- testsuite/tests/typecheck/should_fail/T18851.stderr
- + testsuite/tests/typecheck/should_fail/T18851e.hs
- + testsuite/tests/typecheck/should_fail/T18851e.stderr
- + testsuite/tests/typecheck/should_fail/T18851f.hs
- + testsuite/tests/typecheck/should_fail/T18851f.stderr
- testsuite/tests/typecheck/should_fail/T22707.stderr
- testsuite/tests/typecheck/should_fail/T22940.stderr
- + testsuite/tests/typecheck/should_fail/T26543a.hs
- + testsuite/tests/typecheck/should_fail/T26543a.stderr
- testsuite/tests/typecheck/should_fail/T26823.stderr
- + testsuite/tests/typecheck/should_fail/T27731.hs
- + testsuite/tests/typecheck/should_fail/T27731.stderr
- + testsuite/tests/typecheck/should_fail/T27844.hs
- + testsuite/tests/typecheck/should_fail/T27844.stderr
- testsuite/tests/typecheck/should_fail/T5691.stderr
- testsuite/tests/typecheck/should_fail/T7437.stderr
- testsuite/tests/typecheck/should_fail/all.T
- testsuite/tests/typecheck/should_fail/mc24.stderr
- testsuite/tests/typecheck/should_fail/tcfail019.stderr
- testsuite/tests/typecheck/should_fail/tcfail189.stderr
- + testsuite/tests/warnings/should_fail/WExpectedNoArgError.stderr
- testsuite/tests/warnings/should_fail/all.T
- utils/check-exact/ExactPrint.hs
- utils/check-exact/Main.hs
- utils/check-exact/Parsers.hs
- utils/check-exact/Transform.hs
- utils/check-exact/Utils.hs
- utils/check-ppr/Main.hs
- utils/count-deps/Main.hs
- utils/deriveConstants/Main.hs
- utils/dump-decls/Main.hs
- utils/haddock/haddock-api/src/Haddock.hs
- utils/haddock/haddock-api/src/Haddock/Backends/Hyperlinker/Renderer.hs
- utils/haddock/haddock-api/src/Haddock/Backends/Hyperlinker/Utils.hs
- utils/haddock/haddock-api/src/Haddock/Convert.hs
- utils/haddock/haddock-api/test/Haddock/Backends/Hyperlinker/ParserSpec.hs
- utils/jsffi/dyld.mjs
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/0381403a2b142eb03062a3c322d127…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/0381403a2b142eb03062a3c322d127…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc][wip/ani/hackage-test] 50 commits: Add regression test for #7803
by Apoorv Ingle (@ani) 16 Oct '26
by Apoorv Ingle (@ani) 16 Oct '26
16 Oct '26
Apoorv Ingle pushed to branch wip/ani/hackage-test at Glasgow Haskell Compiler / GHC
Commits:
234bab08 by Vladislav Zavialov at 2026-09-29T17:22:54-04:00
Add regression test for #7803
Commit 2effe18ab5, first shipped with GHC 8.2.1, fixed #7803 "Superclass
methods are left unspecialized".
This change turns the example from the ticket description into a regression
test, checking that foo1 is fully specialised at Double, with no calls to the
overloaded exp5Tail.
Closes #7803
Assisted-by: Claude Opus 5
- - - - -
c406135c by Andreas Klebinger at 2026-10-01T06:57:28-04:00
RTS: Update flag parsing/handling:
Using 0 as argument to any of these flags now resets the flags setting to default:
- ``-n0`` disables nursery chunking.
- ``-K0`` (or a bare ``-K``) removes the stack size limit.
- ``-M0`` removes the heap size limit.
- ``-H0`` resets the suggested heap size, including the nursery scaling set by ``-H``.
- ``-AL0`` makes the large object allocation limit follow ``-A`` again.
GC Generations are now limited to 64.
-n larger than -A now emits a warning and disables chunking.
Fixes #27830 #27829
- - - - -
984ee82b by Andreas Klebinger at 2026-10-01T06:58:10-04:00
Fix MultiLayerModules timeout multiplier.
We accidentally used the compile multiplier for ghci commands which
use the run timeout setting to set the timeout.
Fixes #26263 and #27796.
- - - - -
50a9cf26 by Andreas Klebinger at 2026-10-01T06:58:10-04:00
testsuite: Include runtime in JUnit report.
- - - - -
e358619f by Alan Zimmerman at 2026-10-01T06:59:01-04:00
EPA: Use EpaLocation in EpVirtualBraces
Haddock processing uses EpLayout.EpVirtualBraces to record the current
layout column, for allocating haddock comments correctly.
For exact printing, we need the line as well as the col, so we know
how many lines to skip when the indented code block starts.
This commit updates EpLayout.EpVirtualBraces so that it carries an
EpaLocation instead of just the Int column, to allow it to be used for
both purposes.
It is a simple mechanical change, with no other impact, but it allows
us to use EpLayout instead of AnnListLayout in AnnList, in the next
commit in this series.
- - - - -
1d2a26ee by Andrew Lelechenko at 2026-10-01T20:22:04-04:00
Remove bitSize from MINIMAL pragma of class Bits
Cf. https://github.com/haskell/core-libraries-committee/issues/441
The function is deprecated for 12 years and has a default implementation,
yet it was never removed from the MINIMAL pragma, putting library authors
in a very awkward position. Let's finally remove bitSize from MINIMAL.
- - - - -
3cc21e4c by Hannes Siebenhandl at 2026-10-01T20:22:59-04:00
Add regression test for #27641
- - - - -
c35096f5 by Hannes Siebenhandl at 2026-10-01T20:23:00-04:00
Don't `:add` modules the loader will reject
Only home modules can be actually added to the loader context, thus we
only accept the module if it belongs to a home unit.
- - - - -
a563cb27 by Simon Jakobi at 2026-10-02T17:37:36-04:00
ci: accept modified changelog.d entries in lint-changelog
The changelog guide says to extend an existing entry rather than add a
new one when the feature is already documented. lint_changelog only
counted added files, so such MRs failed before the validator ran.
Fixes #27779.
Assisted-by: Claude Fable 5.1
- - - - -
03082cd4 by Simon Jakobi at 2026-10-02T17:38:17-04:00
changelog.d: Fix warning flag name in the semaphore-v2 entry
The entry refers to -Wsemaphore-version-mismatch, which does not exist.
The warning GHC emits when it cannot use a -jsem semaphore, including
on a protocol version mismatch, is -Wsemaphore-open-failure.
Context: !15729, #25087
Assisted-by: Claude Fable 5.1
- - - - -
a93705ee by Simon Jakobi at 2026-10-02T17:38:17-04:00
changelog.d: Fix the CLC proposal link in the T27455 entry
The entry used the Sphinx :ref: role with a URL as its target. :ref:
resolves only internal labels, so the generated release notes would
show the proposal name without a link. Use the plain hyperlink form
like the other entries.
Context: !16274, #27455
Assisted-by: Claude Fable 5.1
- - - - -
54381079 by Hannes Siebenhandl at 2026-10-02T17:39:01-04:00
Extend the `TrustOverlay` for wired-in units
The TrustOverlay only contained the `UnitId` of all on-disk units.
However, wired-in units are referred to by their wired-in unit id, which
is not the same as the on-disk unit id.
Thus, trust checks for wired-in units failed because the lookup was
using the wired-in unit, which wasn't present in the `TrustOverlay`.
We fix #27834, by copying the trust info for wired-in unit ids.
- - - - -
f8cfb1a5 by Hécate Kleidukos at 2026-10-04T19:36:39+02:00
[CLC 341] Strict variants of mutable types
This commit is the implementation of CLC Proposal 341
https://github.com/haskell/core-libraries-committee/issues/341
- - - - -
575c4bc6 by Rodrigo Mesquita at 2026-10-05T12:32:02-04:00
ttg: HsModuleName in the AST, ModuleName in GHC
This commit makes the AST fully independent from GHC by parsing a
"module name" as an `HsModuleName (= HText)` rather than constructing an
`ModuleName (= FastString)` straight away.
In the GHC side, everything remains as a `ModuleName`. We turn AST
`HsModuleName`s into fast strings with the cheap `mkFastStringShortText`
when we process the AST for manipulation within the compiler.
There are no performance regressions introduced by this approach.
This is the final piece of #21592
Alternative plans were discussed in
gitlab.haskell.org/ghc/ghc/-/merge_requests/16546#note_694647,
but the Simon suggested one won in simplicity and performance when
compared against my attempt at implementing my original plan of having
a family `ModuleNameP`.
- - - - -
b3b89d32 by mangoiv at 2026-10-05T22:03:32-04:00
hadrian: Persist the used flavour name in the build root (#20650)
This executes the idea proposed in #20650, teaching Hadrian to persist
the flavour used to build a build root. This both makes use of multiple
build roots more ergonomic (as the user no longer needs to repeat
themselves) and avoids a tiresome foot-gun (forgetting to specify a
flavour, often wholly invalidating a build root).
Closes #20650.
Co-authored-by: Sylvain Henry <sylvain(a)haskus.fr>
- - - - -
f977837b by mangoiv at 2026-10-05T22:04:21-04:00
configure: fix sed script and subst tooldir script
Fixes #27672
Adds sanity checking for SUBST_TOOLDIR
Metric Decrease:
LinkableUsage01
MultiLayerModulesTH_OneShot
T10547
T12234
T12425
T13035
T13820
T18140
T18730
T18923
T9198
TcPlugin_RewritePerf
mhu-perf
- - - - -
f1cb08be by Hannes Siebenhandl at 2026-10-05T22:05:03-04:00
Prepend in-memory unit database for backpack
The packageDbFlags are stored in reverse order. Thus, prepending will
ensure that the in-memory unit database is the last item on the unit
database stack.
Further, the in-memory unit database needs to be able to shadow units
from earlier unit databases in the unit database stack.
Moreover, a `-clear-package-db` would remove the in-memory database if
it weren't the last item on the stack.
Closes #27835
- - - - -
8d49ed42 by Kazu Yamamoto at 2026-10-06T19:37:25-04:00
Do not leave standard file descriptors free at startup (#24450)
A process may be started with stdout closed -- `prog >&-` from a shell does
exactly that. Nothing then reserves descriptor 1, and open(), pipe() and
socket() hand out the lowest free descriptor, so the next descriptor the
runtime creates for itself takes it: the ticker's pipe, or a capability's IO
manager control pipe.
'GHC.Internal.IO.StdHandles.stdout' is a CAF, built the first time the program
writes to stdout, which is long after that has happened. It builds a 'Handle'
over descriptor 1, which now belongs to the runtime, and nothing reports an
error because the descriptor is perfectly good. The program then writes its
output into the runtime's own plumbing.
What that looks like from the outside is a hang. The descriptor the Handle has
taken over is the read end of a pipe, so poll() for POLLOUT on it never says
yes and epoll_ctl() accepts a registration for it; the thread waiting to write
blocks for ever. Closing the Handle at exit closes the runtime's descriptor,
which is worse: the ticker then fails on every tick.
'hs_init_ghc' now opens /dev/null onto whichever of descriptors 0, 1 and 2 are
closed, before the runtime creates any descriptor of its own. Each is opened
for the access that descriptor would normally have, read-only for 0 and
write-only for 1 and 2, so that writing to 'stdin' or reading from 'stdout'
still fails rather than quietly succeeding against /dev/null. See
Note [Standard file descriptors must be open].
Moving only the descriptors the runtime opens would not do: the first file the
program itself opened would land on the free number instead. The fix has to
leave no free number. A program run this way therefore finds stdout connected
to /dev/null rather than failing with EBADF on the first write, which is what
such a program would get from most other language runtimes.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
65bcf9e9 by Simon Jakobi at 2026-10-06T19:38:09-04:00
changelog: Repair the sentence describing #27477
The description read "programs using could crash", the object of
"using" having been lost. The synopsis already says which programs are
affected, so drop the dangling word.
Assisted-by: Claude Fable 5.1
- - - - -
15ece296 by mangoiv at 2026-10-08T15:14:56-04:00
ci: move hadrian/ghci into the lint category so it can be picked up by more runners
Fixes #27817
- - - - -
c0823135 by mangoiv at 2026-10-08T15:14:56-04:00
ci: make lint-adjacent jobs into platform independent
- move lint jobs into lint-anyarch tag
- unify lint jobs under the same platform independent container
- - - - -
f76464cf by Zubin Duggal at 2026-10-08T15:15:39-04:00
DmdAnal: Make AbsDmd neutral in maxDmd
fixes #27845
- - - - -
ffa56ae4 by sheaf at 2026-10-09T17:15:59+02:00
Preserve sign of zero when parsing -0.0#
This commit leverages the recently added GHC.Types.Literal.Floating
module in order to preserve the sign of negative zero from
source-written floating-point literals.
Fixes #27545
- - - - -
d538cac9 by Facundo Domínguez at 2026-10-09T20:26:38-04:00
Propagate annotations to simple interfaces
This allows annotations to be visible to plugins when run by
haddock. The LiquidHaskell plugin needs the annotations, in particular.
Fixes #26761
- - - - -
32c4f4ab by meooow25 at 2026-10-09T20:27:28-04:00
Bump containers submodule to 0.8.1
And fix affected tests.
* T4086a: containers depends on template-haskell-lift now instead of
template-haskell.
* T22611: Updated to be less dependent on containers internals.
- - - - -
c786065e by sheaf at 2026-10-09T20:28:20-04:00
Use an explicit pattern match in toIfaceIdDetails
The old wildcard pattern let this code bit rot: it did not properly account
for recently added 'IdDetails' such as 'RepPolyId', which resulted in
spurious 'pprTrace' messages that could even pollute HLS sessions.
Fixes #23785
- - - - -
e7cacf59 by sheaf at 2026-10-09T20:29:09-04:00
Take into account ifKind in freeNamesIfDecl
Commit 3c2f4bb4 added the 'ifKind' field to various constructors
of 'IfaceDecl', which preserves the original kind (before type synonym
expansion) for better error messages.
However, that commit forgot to update 'freeNamesIfDecl' correspondingly.
This could result in a "urk! lookup local fingerpring" crash when e.g.
a type's kind uses a type synonym defined later, as we failed to add a
dependency on the type synonym during dependency analysis.
Fixes #27916
- - - - -
41e80f41 by Simon Peyton Jones at 2026-10-11T14:38:51-04:00
Simplify the error-suppression mechanism in GHC.Tc.Errors
In `GHC.Tc.Errors.reportWanteds` we suppress some errors in favour of
others. But the mechanism had grown crufty, and #27331 exposed a bug.
This MR makes it simpler and more uniform, by doing everything via
the `ei_suppress` field of the ErrorItem.
Claude then found another closely-related bug (see the review linked
on !16564). That bug is immortalised in new test T18851d.
I'm still not happy with `ignoreConstraint` but we can worry about
that another day; I have not touched it.
Main changes
* Instead of /predicting/ when an error will be reported, we set
`cec_error_reported` when an error is /actually/ reported. (I renamed
it from `cec_suppress` to reflect this change.)
Now errors are suppressed only when a preceding error has actually been
reported. Simpler and more robust.
See `Note [cec_error_reported: suppressing less-serious errors]`
The big changes are in `reportWanteds` which looks very different.
* New `Note [ei_suppress: suppressing confusing errors]` describes the
(quite separate) `ei_suppress` mechanism for suppressing confusing
errors, mainly arising from non-empty rewriter sets
* In `tryTypeClassDefaulting`, instead of switching off type-class defaulting
if there is an insoluble /anywhere/, we just switch it off locally when
we find an insoluble sub-tree. See Note [When to do type-class defaulting]
and (W5) in Note [ApproximateWC]
* Greatly simplify `insolubleWantedCt`.
* I made type-class-defaulting be a bit more eager, only switched off when
a peer or ancestor (but not child) constraint is insoluble. See
Note [When to do type-class defaulting].
Small refactorings
* Rename `askNoErrs` to `askErrsFound` and flip its polarity
* The code for "check if ei_suppress is true of all items" code is
moved to `mkErrorItems` rather than in the large `reportWanteds`.
* Code for `has_gadt_match` moves to `mkGivenErrorReporter`, rather than
polluting the large `reportWanteds`.
* Many tests with `-fdefer-type-errors` get more warnings, especially
about ambiguous (Num a) constraints. This is by-design: see
Note [Always warn with -fdefer-type-errors]. Previously GHC was not
honouring this Note but now it is, hence the extra errors.
- - - - -
f217fc31 by Cheng Shao at 2026-10-11T14:39:33-04:00
compiler: ensure cross ghc --info output target unit ids
Previously, for cross ghcs, the base/ghc/ghc-internal unit ids in
--info output do not match the target unit ids reported by ghc-pkg,
breaking cross ghc release builds with hash-unit-ids when being used
with cabal 3.18. This patch fixes it by making --info output target
unit ids. Fixes #27919.
Co-authored-by: Codex <codex(a)openai.com>
- - - - -
d07a5176 by Simon Peyton Jones at 2026-10-13T18:10:39-04:00
Remove the Eq and Ord instances for ForAllTyFlag
In Note [Comparing visibility] in GHC.Core.TyCo.Compare we read that
"we always compare ForAllTyFlags with `eqForAllVis` or `cmpForAllVis`"
But alas there was an Eq and Ord instance for ForAllTyFlag, which made it
impossible to check this claim. So I made these changes:
* Move the definition of ForAllTyFlag and its related functions from
L.H.S.Specificity (where it did not belong, since L.H.S didn't use it)
into GHC.Types.Var.
* Remove the Eq and Ord instances for ForAllTyFlag
* Deal with the fallout, by using `eqForAllVis` or related functions.
* In interface files we use IfaceType as a key for a de-deduplication map
See Note [Deduplication during iface binary serialisation]
in GHC.Iface.Binary. For this we need /exact/ comparison, so we use a
newtype wrapper for IfaceForAllTyFlag, and give use `cmpForAllTyFlagExactly`
to implement its Ord instance. Tiresome but easy.
* Rename `toIfaceForAllBndrs` to `toIfaceForAllTyBndrs`
- - - - -
ea5c054d by Simon Peyton Jones at 2026-10-13T18:10:39-04:00
Refactor type and coercion substitution
This MR refactors type and coercion substitution so that they use
TyCoMapper, rather than hand-rolled code. Fundamentally it's a simple
idea, but I had to do quite a bit of refactoring to make it fly.
I got Claude to help me this this refactoring, but I paid careful
attention to every line of code.
Main changes:
* New module GHC.Core.TyCo.Make which defines TyCoMapper, and a bunch of other
simple "smart constructors" for types and coercions. See
GHC.Core.TyCo.Rep Note [The Type-related module hierarchy], esp (TRM1)
* The new TyCoMapper has new fields `tcm_tcapp_ty` and `tcm_tcapp_co` to handle
type-constructor applications. These replace `tcm_tycon`.
* Rewrite GHC.Core.TyCo.Subst to use TyCoMapper
* Rewrite GHC.Core.Type.expandTypeSynonyms to use TyCoMapper.
* Implement `seqType` and `seqCo` with TyCoFolder. To to this I had to add
a `tcf_lit` field to TyCoFolder.
* A new module GHC.Utils.StrictIdentity to define a strict identity monad,
which itself is used for
substTyCoMapper :: TyCoMapper Subst StrictIdentity
* I removed an apparently-unused instance for Binary Levity
Refactoring `seq` functions
* In GHC.Core.Seq, redefine `seqOneShot`, `seqRuleInfo`, and friends to return
`SeqResult`, a new type defined in GHC.Types.Baseic, rather than `()`. We
can define a Monoid instance for `SeqResult` that does the right thing.
* This has knock-on effects across the compiler.
- - - - -
34165e23 by Simon Peyton Jones at 2026-10-13T18:10:39-04:00
Refactor TyCoMapper to take a single monad; add StrictReaderT
TyCoMapper used to be parameterised over both an environment and a
monad, with fields like
tcm_tyvar :: env -> TyVar -> m Type
Now it is parameterised over just the monad:
tcm_tyvar :: TyVar -> m Type
If the mapping needs an environment, `m` is a reader monad over that
environment. Many uses (e.g. zonkTcTypeMapper, swizzleMapper) need no
environment at all, and used to pass a dummy (). The binder field
becomes
tcm_tycobinder :: forall r. TyCoVar -> ForAllTyFlag
-> (TyCoVar -> m r) -> m r
and runs the continuation in the extended environment. mapTyCoX is gone;
only mapTyCo remains.
To make this efficient, the reader monad must use the one-shot trick and
be strict in the environment. So:
* New module GHC.Utils.Monad.StrictReader defines
newtype StrictReaderT r m a
with hand-written instances. The builder of the pattern synonym
`StrictReaderT` is a smart constructor that adds both `oneShot` and a
bang on the environment, so every StrictReaderT computation is strict
in the environment. See Note [Instances for StrictReaderT].
* ZonkT becomes type ZonkT = StrictReaderT ZonkEnv
ZonkM becomes type ZonkM = StrictReaderT ZonkGblEnv IO
replacing their own hand-written instances.
* Substitution uses
type SubstM = StrictReaderT Subst StrictIdentity
substTyCoMapper :: TyCoMapper SubstM
and similarly expandTypeSynonymMapper.
* zonk_tycomapper :: TyCoMapper (ZonkT TcM) is now much simpler.
* swizzleMapper uses StrictIdentity rather than Identity.
* Module renaming, so that the strict monads are all peers in GHC.Utils.Monad:
GHC.Utils.StrictIdentity ==> GHC.Utils.Monad.StrictIdentity
GHC.Utils.Monad.State.Strict ==> GHC.Utils.Monad.StrictState
alongside the new GHC.Utils.Monad.StrictReader.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
c0299e15 by Simon Jakobi at 2026-10-13T18:11:23-04:00
testsuite: Line-buffer the driver's stdout
Python block-buffers stdout when it is a pipe. This is the case for
example in CI. As a result there is often no indication of progress at
all until the run ends.
To fix this, we configure it explicitly to use line buffering instead.
stderr is reconfigured too, for consistency: Python line-buffers it by
default since 3.9.
The type-ignores are for mypy, which types these handles as TextIO — an
interface without reconfigure.
Fixes #12934.
Assisted-by: Claude Fable 5
- - - - -
9b5beaa2 by Florian Ragwitz at 2026-10-13T18:12:05-04:00
hpc: Improve coverage semantics for instance methods and instances
Users care about which of their explicitly written methods are or aren't
covered, not whether all of the inherited methods are covered as well. Those
should be covered where they are implemented.
We therefore skip generating top-level boxes for inherited methods which will
appear as uncovered with no clear indication as to why, and no way to fix other
than exercising code the user has not written.
Previously, top-level boxes for those inherited methods would use the instance
head as their source span. Now that those boxes are gone, we can use that
source span for another purpose:
We introduce a new top-level box for each class instance with its instance head
as the source span, and use that to indicate whether or not an instance has
been covered at all.
We do this by making any method of the instance, inherited/generated or
otherwise, tick the box for the instance head. Excluded from this are
methodless classes, which could never be covered using the current mechanism.
This could be improved upon further.
These changes apply to ticking for program coverage only, and don't affect
source notes. Additionally, we update the scope of record selector ticking to
be limited to program coverage as well, as the oversight to also extend it to
source notes has previously caused bugs and because record selector ticking is
coverage-specific.
Fixes #17155, #15932.
- - - - -
836ec50a by Simon Peyton Jones at 2026-10-13T18:12:54-04:00
Refactor fundeps again
This MR fixes #27828; there was a bad scoping error in `trim_qtvs`.
The main changes are
* Refactor `trim_qtvs` completely to eliminate the bug.
* Remove a redundant `apartnessCheck` from `mkTopOpenFamEqFDs`.
* Lots of improvements to the Notes in FunDeps.hs
I also did a couple of pure refactors:
* I realised that we were carefully caching `cab_incomps` in each
`CoAxBranch`, to make it more efficient to reduce a type family application,
but we were not doing the same thing when computing relevance for functional
dependencies; see Note [Relevance] in GHC.Tc.Solver.FunDeps. So I added
`cab_overlaps`, which is now used in `noEarlierMatch`.
* Use a proper data types, `AmIUnifying` and `OuterKindsFlag`, for two
previously-Boolean arguments to `tc_unify_tys`. This is a pure refactor.
- - - - -
889ef371 by Simon Peyton Jones at 2026-10-13T18:13:36-04:00
Refactor and simplify solver's unification code
Ticket #27844 showed that GHC's constraint solver could miss an
occurs check, and thereby build an infinite type.
This patch significantly simplifes the code in
GHC.Tc.Solver.Equality.canEqCanLHSFinish_try_unification
GHC.Tc.Solver.Equality.canEqCanLHSFinish_no_unification
It is now significantly simpler, and requires much less subtle
reasoning to understand.
Main changes
* If `canEqCanLHSFinish_try_unification` fails to unify, it now /always/ calls
`canEqCanLHSFinish_no_unification` rather than trying to finish the job itself.
* `GHC.Tc.Solver.Monad.checkTypeEq` is moved from Monad into Equality, and renamed
to `GHC.Tc.Solver.Equality.checkTypeEqNoUnification`.
* `canEqCanLHSFinish_no_unification` calls `checkTypeEqNoUnification` to test
the invariants for an inert equality. Before this MR there was a special case for
`do_not_prevent_rewriting`, but that has gone; instead it's just a consequence of
the flags passed to `checkTyEqRhs`, documented in the `PuOK` case of
`canEqCanLHSFinish_no_unification`.
* There is only one bit of "swap back" code, in `finish_no_unify` in
`canEqCanLHSFinish_try_unification. Previously this code was duplicated.
* `kickOutAfterFillingCoercionHole` should account for equalities with a
TyFamLHS. See (KOC5) in Note [Kick out after filling a coercion hole]
* No need to gather coercion holes in the `PuOK` case of `canEqCanLHSFinish_no_unification`.
See documentation with that code.
- - - - -
f9193e53 by Simon Peyton Jones at 2026-10-13T18:13:37-04:00
One line fix to fallout from
...#27731, !16564, simplifying Tc.Errors machinery
There was an over-eager assert!
- - - - -
cdd56b7a by Florian Ragwitz at 2026-10-13T18:14:19-04:00
Fix several sphinx errors and warnings from rendering the release notes
The extension references which are removed here are for extension which were
already previously undocumented, so just removing them seems fine for now.
- - - - -
4f00da25 by Florian Ragwitz at 2026-10-13T18:14:19-04:00
Link to QualifiedStrings documentation
- - - - -
97adaf89 by Simon Peyton Jones at 2026-10-14T00:07:27+01:00
Line up simpleUnifyCheck and check_ty_eq_rhs
Even after #26543 was allegedly fixed, the original repo case in the
Description continued to fail. The reason was that the QuickLook
unifier, `qlUnify`, used `simpleUnifyCheck` for checking unification
invariants; and `simpleUnifyCheck` conservatively rejected any RHS
with a coercion hole in it. The upshot was that QuickLook was not
as clever as it should be, wrongly failing to do an impredicative
instantiation.
Interestingly `check_ty_eq_rhs`, which does the same job during
constraint solving, was more liberal: it just looked at the free vars
of the coercion, and allowed coercion holes.
This MR lines them up, adding some careful notes. See
Note [simpleUnifyCheck]
Note [Occurs check and coercions]
Note [Unification preconditions] esp (COERCIONS)
Things are better than before, but I am still uncomfortable about the
possibilty that a hole might be filled with a coercion that mentions
the LHS type variable; for now I have left this discomfort documented
in Note [Occurs check and coercions].
Main changes
* `qlUnify` now only unifies /instantiation variables/ not regular unification
variables. This makes QuickLook more predictable. See (UQL6) in
Note [QuickLook unification].
* `qlUnify` no longer needs to call `simpleUnifyCheck`, so we can get rid of
`UC_QuickLook` and its code in `simpleUnifyCheck`.
* I found I could get rid of `mkOccFolders` in favour of `anyFreeVarsOfType`.
Hooray.
* Improve documentation of CycleBreakerTv, and rename it to GivenCycleBreakerTv
because they are only uesd for Givens!
* I accepted a 9% worsening in compile time allocation on T5030
because the newly-consistent story triggered #27934.
Other changes
* I refactored `atvFolder` so that it pairs the "interesting-var" function
with the in-scope set, to avoid building a closure with a free variable.
Now we get nice tight loops for `anyFreeVarsOfType` and friends.
See Note [Any-free-var folder].
Metric Increase:
T5030
- - - - -
5f7b3047 by Simon Peyton Jones at 2026-10-14T00:07:27+01:00
Fix order-dependence in QuickLook
Ticket #27917 pointed out that QuickLook was order-dependent
-- very bad!
The solution is in `qlUnify`: spot when we are unifying a type with a
definite monotype, and then monomorphise any free instantiation
variables of that type.
See (UQL8) and (UQL9) in Note [QuickLook unification].
- - - - -
c391c70c by Simon Peyton Jones at 2026-10-14T00:07:28+01:00
Add some comments about RuntimeUnk
This commit just adds comments explaining why we don't need to worry about
RuntimeUnkTv in the constraint solver.
It also tightens up docmentation of earlier (overlapping) commits in
this MR.
- - - - -
7df3ba2f by Andrea Vezzosi at 2026-10-14T06:15:48-04:00
add runGhcWithSignalHandlers and remove handling from runGhc[T]
it only ever makes sense to call `withSignalHandlers` from `main`, otherwise
signals can be too easily swallowed without notification to the rest of your
process.
This commit takes withSignalHandlers out of `runGhc/runGhcT` and provides
`runGhcWithSignalHandlers` for the old behaviour.
- - - - -
3a72b8a2 by Hannes Siebenhandl at 2026-10-14T13:48:32-04:00
Fix #27836, normalise unit database path in ExternalUnitDatabases
Add a regression test, proofing that all variations:
- local-unit-db/my-test.conf
- ./local-unit-db/my-test.conf
- ./local-unit-db/my-test.conf/
are parsed only once.
- - - - -
8ddbc6f9 by Florian Ragwitz at 2026-10-14T13:49:28-04:00
Remove obsolete HPC types
Fixes #27946.
- - - - -
f34c79ee by Alan Zimmerman at 2026-10-15T04:54:47-04:00
EPA: Start using vocurly as basis for AnnListLayout
For the existing cases that populate AnnList.
This uses AnnListBraces when braces are explicitly supplied, and
AnnListLayout when vocurly is used
The change also shows up AnnList usages that can never capture layout,
these are cleared up later.
- - - - -
033ba59c by sheaf at 2026-10-15T04:55:44-04:00
Make exprFreeVars deep
exprFreeVars used to be a shallow free-variable finder (it didn't look
into kinds), but most callers wanted it to be deep. In particular,
'exprFreeVars' is often used to seed an 'InScopeSet', and that must
contain the /deep/ free variables.
This commit makes it deep, which allows us to get rid of calls to
'closeOverKinds' or other workarounds for shallowness in:
- 'GHC.Core.Opt.Simplify.Utils.abstractFloats'
- 'GHC.HsToCore.Binds.dsSpec_help'
- 'GHC.Core.Opt.Arity.etaBodyForJoinPoint'
- 'GHC.Core.FVs.freeVars'
- 'GHC.Core.Lint.lintCoreRule'
We also remove 'deepExprsFreeVarsDSet' and 'closeOverKindsDSet'.
Other places needed a little bit more care, in particular to properly
handle coercion variables free in kinds:
- 'GHC.Core.Opt.Specialise.specHeader' quantifies over the binder of
an unspecialised argument directly, instead of computing the free Ids
of the argument.
- 'GHC.HsToCore.dsWarnRuleShadowing' filters out 'CoVar's.
- 'GHC.Core.Opt.SpecConstr.callToPat' had some ad-hoc logic to compute
argument pattern types and a workaround with 'expandTypeSynonyms'.
That logic is removed in favour of a new 'argsToPats' function which
directly computes the argument pattern types by instantiating the
type of the head of the call pattern.
Fixes #27936
- - - - -
f93d523c by Luite Stegeman at 2026-10-15T04:56:34-04:00
testsuite: Use mkWeakMVar in memo001/memo002
mkWeakPtr in the memo001/memo001 tests created weak pointers
with the MVar box as the key, which is fragile in the presence
of optimization. The fix is using mkWeakMVar, keying on the
primitive MVar# instead.
Fixes #27924 and #27396
- - - - -
beaaf08b by Apoorv Ingle at 2026-10-16T14:17:49-06:00
Add new change.d file
- - - - -
e7018617 by Apoorv Ingle at 2026-10-16T14:17:49-06:00
Edit 27156.md
- - - - -
408 changed files:
- .gitlab-ci.yml
- .gitlab/ci.sh
- .gitlab/hello.hs
- + changelog.d/24450
- changelog.d/26616
- + changelog.d/26761
- + changelog.d/27156.md
- + changelog.d/27641
- + changelog.d/27845
- + changelog.d/27936
- + changelog.d/T23785
- + changelog.d/T26543
- changelog.d/T27329
- changelog.d/T27455
- + changelog.d/T27545
- + changelog.d/T27731
- + changelog.d/T27828
- + changelog.d/T27830-rts-flag-bounds
- + changelog.d/T27844
- + changelog.d/T27916
- + changelog.d/T4162
- changelog.d/boxing-family
- + changelog.d/clc-341-strict-mutable-data-types
- + changelog.d/fix-cross-ghc-info-unit-id
- changelog.d/fix-parallel-gc-selector-race-27477
- + changelog.d/hadrian-persist-flavour
- + changelog.d/hpc-classinsts
- + changelog.d/hpc-cleanup
- changelog.d/semaphore-v2
- changelog.d/tcplugin_init.md
- changelog.d/unit-index
- compiler/GHC.hs
- compiler/GHC/Builtin/Modules.hs
- compiler/GHC/Builtin/WiredIn/Ids.hs
- compiler/GHC/Builtin/WiredIn/Prim.hs
- compiler/GHC/Builtin/WiredIn/Types/Box.hs
- compiler/GHC/ByteCode/Asm.hs
- compiler/GHC/ByteCode/Show.hs
- compiler/GHC/Cmm/GenericOpt.hs
- compiler/GHC/Cmm/UniqueRenamer.hs
- compiler/GHC/CmmToAsm/Dwarf/Types.hs
- compiler/GHC/CmmToAsm/Monad.hs
- compiler/GHC/CmmToAsm/Reg/Graph/Spill.hs
- compiler/GHC/CmmToAsm/Reg/Graph/SpillClean.hs
- compiler/GHC/CmmToAsm/Reg/Graph/SpillCost.hs
- compiler/GHC/CmmToAsm/Reg/Graph/Stats.hs
- compiler/GHC/CmmToAsm/Reg/Linear/State.hs
- compiler/GHC/CmmToAsm/Reg/Linear/Stats.hs
- compiler/GHC/CmmToAsm/Reg/Liveness.hs
- compiler/GHC/CmmToAsm/Wasm/Asm.hs
- compiler/GHC/CmmToAsm/Wasm/Types.hs
- compiler/GHC/CmmToC.hs
- compiler/GHC/Core/Coercion.hs
- compiler/GHC/Core/Coercion.hs-boot
- compiler/GHC/Core/Coercion/Axiom.hs
- compiler/GHC/Core/Coercion/Opt.hs
- compiler/GHC/Core/DataCon.hs
- compiler/GHC/Core/FVs.hs
- compiler/GHC/Core/FamInstEnv.hs
- compiler/GHC/Core/Lint.hs
- compiler/GHC/Core/Make.hs
- compiler/GHC/Core/Map/Type.hs
- compiler/GHC/Core/Opt/Arity.hs
- compiler/GHC/Core/Opt/CallerCC.hs
- compiler/GHC/Core/Opt/CallerCC/Types.hs
- compiler/GHC/Core/Opt/Exitify.hs
- compiler/GHC/Core/Opt/Simplify/Utils.hs
- compiler/GHC/Core/Opt/SpecConstr.hs
- compiler/GHC/Core/Opt/Specialise.hs
- compiler/GHC/Core/Reduction.hs
- compiler/GHC/Core/Seq.hs
- compiler/GHC/Core/Subst.hs
- compiler/GHC/Core/TyCo/Compare.hs
- compiler/GHC/Core/TyCo/FVs.hs
- + compiler/GHC/Core/TyCo/Make.hs
- + compiler/GHC/Core/TyCo/Make.hs-boot
- compiler/GHC/Core/TyCo/Ppr.hs
- compiler/GHC/Core/TyCo/Rep.hs
- compiler/GHC/Core/TyCo/Rep.hs-boot
- compiler/GHC/Core/TyCo/Subst.hs
- compiler/GHC/Core/Type.hs
- compiler/GHC/Core/Type.hs-boot
- compiler/GHC/Core/Unify.hs
- compiler/GHC/CoreToIface.hs
- compiler/GHC/CoreToIface.hs-boot
- compiler/GHC/CoreToStg.hs
- compiler/GHC/Data/OsPath.hs
- compiler/GHC/Driver/Backpack.hs
- compiler/GHC/Driver/Downsweep.hs
- compiler/GHC/Driver/Main/Compile.hs
- compiler/GHC/Driver/Pipeline.hs-boot
- compiler/GHC/Driver/Pipeline/Execute.hs
- compiler/GHC/Driver/Pipeline/Phases.hs
- compiler/GHC/Driver/Session.hs
- compiler/GHC/Hs/Doc.hs
- compiler/GHC/Hs/Dump.hs
- compiler/GHC/Hs/Expr.hs
- compiler/GHC/Hs/ImpExp.hs
- compiler/GHC/Hs/Lit.hs
- compiler/GHC/HsToCore.hs
- compiler/GHC/HsToCore/Binds.hs
- compiler/GHC/HsToCore/Docs.hs
- compiler/GHC/HsToCore/Match/Literal.hs
- compiler/GHC/HsToCore/Quote.hs
- compiler/GHC/HsToCore/Ticks.hs
- compiler/GHC/Iface/Decl.hs
- compiler/GHC/Iface/Errors/Types.hs
- compiler/GHC/Iface/Ext/Ast.hs
- compiler/GHC/Iface/Ext/Debug.hs
- compiler/GHC/Iface/Ext/Types.hs
- compiler/GHC/Iface/Ext/Utils.hs
- compiler/GHC/Iface/Syntax.hs
- compiler/GHC/Iface/Tidy.hs
- compiler/GHC/Iface/Type.hs
- compiler/GHC/Iface/Type.hs-boot
- compiler/GHC/IfaceToCore.hs
- compiler/GHC/Parser.y
- compiler/GHC/Parser/Annotation.hs
- compiler/GHC/Parser/Errors/Types.hs
- compiler/GHC/Parser/Header.hs
- compiler/GHC/Parser/Lexer.x
- compiler/GHC/Parser/PostProcess.hs
- compiler/GHC/Parser/PostProcess/Haddock.hs
- compiler/GHC/Parser/String.hs
- compiler/GHC/Rename/Env.hs
- compiler/GHC/Rename/Module.hs
- compiler/GHC/Rename/Names.hs
- compiler/GHC/Rename/Unbound.hs
- compiler/GHC/Runtime/Heap/Inspect.hs
- compiler/GHC/Settings.hs
- compiler/GHC/Settings/IO.hs
- compiler/GHC/Stg/BcPrep.hs
- compiler/GHC/Stg/Debug.hs
- compiler/GHC/Stg/EnforceEpt/Rewrite.hs
- compiler/GHC/Stg/EnforceEpt/TagSig.hs
- compiler/GHC/Stg/Subst.hs
- compiler/GHC/StgToJS/ExprCtx.hs
- compiler/GHC/StgToJS/Linker/Linker.hs
- compiler/GHC/Tc/Deriv/Functor.hs
- compiler/GHC/Tc/Deriv/Generics.hs
- compiler/GHC/Tc/Errors.hs
- compiler/GHC/Tc/Errors/Ppr.hs
- compiler/GHC/Tc/Errors/Types.hs
- compiler/GHC/Tc/Gen/App.hs
- compiler/GHC/Tc/Gen/Export.hs
- compiler/GHC/Tc/Instance/Family.hs
- compiler/GHC/Tc/Instance/FunDeps.hs
- compiler/GHC/Tc/Module.hs
- compiler/GHC/Tc/Solver/Default.hs
- compiler/GHC/Tc/Solver/Equality.hs
- compiler/GHC/Tc/Solver/FunDeps.hs
- compiler/GHC/Tc/Solver/InertSet.hs
- compiler/GHC/Tc/Solver/Monad.hs
- compiler/GHC/Tc/TyCl.hs
- compiler/GHC/Tc/TyCl/Instance.hs
- compiler/GHC/Tc/Types.hs
- compiler/GHC/Tc/Types/Constraint.hs
- compiler/GHC/Tc/Types/ErrCtxt.hs
- compiler/GHC/Tc/Utils/Monad.hs
- compiler/GHC/Tc/Utils/TcMType.hs
- compiler/GHC/Tc/Utils/TcType.hs
- compiler/GHC/Tc/Utils/Unify.hs
- compiler/GHC/Tc/Zonk/Env.hs
- compiler/GHC/Tc/Zonk/Monad.hs
- compiler/GHC/Tc/Zonk/TcType.hs
- compiler/GHC/Tc/Zonk/Type.hs
- compiler/GHC/ThToHs.hs
- compiler/GHC/Types/Arity.hs
- compiler/GHC/Types/Basic.hs
- compiler/GHC/Types/Cpr.hs
- compiler/GHC/Types/Demand.hs
- compiler/GHC/Types/Id/Info.hs
- compiler/GHC/Types/Name/Env.hs
- compiler/GHC/Types/Name/Occurrence.hs
- compiler/GHC/Types/Unique.hs
- compiler/GHC/Types/Unique/DSM.hs
- compiler/GHC/Types/Unique/FM.hs
- compiler/GHC/Types/Unique/Map.hs
- compiler/GHC/Types/Unique/Set.hs
- compiler/GHC/Types/Unique/Supply.hs
- compiler/GHC/Types/UnresolvedImport.hs
- compiler/GHC/Types/Var.hs
- compiler/GHC/Types/Var.hs-boot
- compiler/GHC/Types/Var/FV.hs
- compiler/GHC/Types/Var/Set.hs
- compiler/GHC/Unit/External/Database.hs
- compiler/GHC/Unit/External/Wired.hs
- compiler/GHC/Unit/Home.hs
- compiler/GHC/Unit/Module.hs
- compiler/GHC/Unit/Module/Env.hs
- + compiler/GHC/Unit/Module/Name.hs
- compiler/GHC/Unit/Parser.hs
- compiler/GHC/Unit/State.hs
- compiler/GHC/Unit/Types.hs
- compiler/GHC/Unit/Types.hs-boot
- compiler/GHC/Utils/Binary.hs
- + compiler/GHC/Utils/Monad/StrictIdentity.hs
- + compiler/GHC/Utils/Monad/StrictReader.hs
- compiler/GHC/Utils/Monad/State/Strict.hs → compiler/GHC/Utils/Monad/StrictState.hs
- compiler/GHC/Utils/Outputable.hs
- compiler/GHC/Utils/Panic.hs
- compiler/Language/Haskell/Syntax.hs
- compiler/Language/Haskell/Syntax/Expr.hs
- compiler/Language/Haskell/Syntax/ImpExp.hs
- compiler/Language/Haskell/Syntax/Lit.hs
- compiler/Language/Haskell/Syntax/Module/Name.hs
- compiler/Language/Haskell/Syntax/Specificity.hs
- compiler/Language/Haskell/Syntax/Text.hs
- compiler/ghc.cabal.in
- distrib/configure.ac.in
- docs/users_guide/exts/literals.rst
- docs/users_guide/runtime_control.rst
- ghc/GHCi/UI.hs
- ghc/GHCi/UI/Info.hs
- ghc/Main.hs
- hadrian/bindist/Makefile
- hadrian/bindist/config.mk.in
- hadrian/doc/flavours.md
- hadrian/src/Rules.hs
- hadrian/src/Rules/BinaryDist.hs
- hadrian/src/Rules/Generate.hs
- hadrian/src/Settings.hs
- libraries/base/base.cabal.in
- libraries/base/changelog.md
- libraries/base/src/Control/Concurrent/Chan.hs
- + libraries/base/src/Control/Concurrent/Chan/Strict.hs
- libraries/base/src/Control/Concurrent/MVar.hs
- + libraries/base/src/Control/Concurrent/MVar/Strict.hs
- libraries/base/src/Data/IORef.hs
- + libraries/base/src/Data/IORef/Strict.hs
- libraries/base/tests/Memo1.lhs
- libraries/base/tests/Memo2.lhs
- libraries/base/tests/all.T
- libraries/containers
- libraries/ghc-internal/src/GHC/Internal/Bits.hs
- linters/lint-codes/LintCodes/Static.hs
- m4/subst_tooldir.m4
- rts/RtsFlags.c
- rts/RtsStartup.c
- rts/include/rts/Flags.h
- rts/include/rts/storage/GC.h
- rts/sm/GC.c
- rts/sm/Storage.c
- testsuite/driver/junit.py
- testsuite/driver/runtests.py
- testsuite/driver/testglobals.py
- testsuite/driver/testlib.py
- + testsuite/tests/backpack/should_compile/T27835.bkp
- + testsuite/tests/backpack/should_compile/T27835.stderr
- testsuite/tests/backpack/should_compile/all.T
- testsuite/tests/count-deps/CountDepsAst.stdout
- testsuite/tests/count-deps/CountDepsParser.stdout
- testsuite/tests/default/default-fail05.stderr
- + testsuite/tests/dmdanal/should_run/T27845.hs
- + testsuite/tests/dmdanal/should_run/T27845.stdout
- + testsuite/tests/dmdanal/should_run/T27845_Lib.hs
- + testsuite/tests/dmdanal/should_run/T27845b.hs
- + testsuite/tests/dmdanal/should_run/T27845b.stdout
- + testsuite/tests/dmdanal/should_run/T27845b_Lib.hs
- testsuite/tests/dmdanal/should_run/all.T
- + testsuite/tests/driver/T27836/A.hs
- + testsuite/tests/driver/T27836/B.hs
- + testsuite/tests/driver/T27836/C.hs
- + testsuite/tests/driver/T27836/Makefile
- + testsuite/tests/driver/T27836/T27836.stdout
- + testsuite/tests/driver/T27836/all.T
- + testsuite/tests/driver/T27836/unitA
- + testsuite/tests/driver/T27836/unitB
- + testsuite/tests/driver/T27836/unitC
- + testsuite/tests/ghc-api/T4162.hs
- + testsuite/tests/ghc-api/T4162.stdout
- testsuite/tests/ghc-api/all.T
- testsuite/tests/ghc-api/downsweep/IncrementalDownsweep.hs
- testsuite/tests/ghc-api/exactprint/T22919.stderr
- testsuite/tests/ghc-api/exactprint/Test20239.stderr
- testsuite/tests/ghc-api/exactprint/ZeroWidthSemi.stderr
- testsuite/tests/ghci.debugger/scripts/T14628.stderr
- testsuite/tests/ghci/prog020/ghci.prog020a.stderr
- testsuite/tests/ghci/prog020/ghci.prog020b.stderr
- testsuite/tests/ghci/prog021/prog021a.stderr
- testsuite/tests/ghci/prog021/prog021b.stderr
- testsuite/tests/ghci/prog022/ghci.prog022a.stderr
- testsuite/tests/ghci/prog022/ghci.prog022b.stderr
- testsuite/tests/ghci/prog022/ghci.prog022c.stderr
- testsuite/tests/ghci/prog022/ghci.prog022d.stderr
- testsuite/tests/ghci/prog022/ghci.prog022e.stderr
- testsuite/tests/ghci/prog022/ghci.prog022f.stderr
- testsuite/tests/ghci/scripts/Defer02.stderr
- + testsuite/tests/ghci/scripts/T27641.script
- + testsuite/tests/ghci/scripts/T27641.stderr
- + testsuite/tests/ghci/scripts/T27641.stdout
- + testsuite/tests/ghci/scripts/T27834.hs
- + testsuite/tests/ghci/scripts/T27834.script
- + testsuite/tests/ghci/scripts/T27834.stdout
- testsuite/tests/ghci/scripts/all.T
- testsuite/tests/haddock/should_compile_flag_haddock/T17544.stderr
- testsuite/tests/haddock/should_compile_flag_haddock/T17544_kw.stderr
- testsuite/tests/haddock/should_compile_flag_haddock/T24221.stderr
- testsuite/tests/hiefile/should_run/T24544.hs
- + testsuite/tests/hpc/instmeths/instmeths.hs
- + testsuite/tests/hpc/instmeths/instmeths.stdout
- + testsuite/tests/hpc/instmeths/test.T
- + testsuite/tests/impredicative/T27917.hs
- testsuite/tests/impredicative/all.T
- + testsuite/tests/indexed-types/should_compile/T27828.hs
- + testsuite/tests/indexed-types/should_compile/T27828a.hs
- + testsuite/tests/indexed-types/should_compile/T27828b.hs
- testsuite/tests/indexed-types/should_compile/all.T
- testsuite/tests/indexed-types/should_fail/T1897b.stderr
- testsuite/tests/indexed-types/should_fail/T9662.stderr
- testsuite/tests/interface-stability/base-exports.stdout
- testsuite/tests/interface-stability/base-exports.stdout-javascript-unknown-ghcjs
- testsuite/tests/interface-stability/base-exports.stdout-mingw32
- testsuite/tests/module/mod130.stderr
- testsuite/tests/module/mod185.stderr
- + testsuite/tests/numeric/should_run/T27545.hs
- + testsuite/tests/numeric/should_run/T27545.stdout
- testsuite/tests/numeric/should_run/all.T
- testsuite/tests/overloadedstrings/should_fail/T25926.stderr
- testsuite/tests/overloadedstrings/should_fail/T27124.stderr
- testsuite/tests/package/T4806a.stderr
- testsuite/tests/package/all.T
- testsuite/tests/parser/should_compile/DumpParsedAst.stderr
- testsuite/tests/parser/should_compile/DumpParsedAstComments.stderr
- testsuite/tests/parser/should_compile/DumpRenamedAst.stderr
- testsuite/tests/parser/should_compile/DumpSemis.stderr
- testsuite/tests/parser/should_compile/KindSigs.stderr
- testsuite/tests/parser/should_compile/T14189.stderr
- testsuite/tests/parser/should_compile/T15323.stderr
- testsuite/tests/parser/should_compile/T20452.stderr
- testsuite/tests/parser/should_compile/T20718.stderr
- testsuite/tests/parser/should_compile/T20718b.stderr
- testsuite/tests/parser/should_compile/T20846.stderr
- testsuite/tests/parser/should_compile/T23315/T23315.stderr
- testsuite/tests/patsyn/should_fail/records-nofieldselectors.stderr
- testsuite/tests/perf/compiler/all.T
- + testsuite/tests/plugins/T26761.hs
- + testsuite/tests/plugins/T26761.stderr
- + testsuite/tests/plugins/T26761Plugin.hs
- + testsuite/tests/plugins/T26761a.hs
- testsuite/tests/plugins/all.T
- testsuite/tests/printer/AnnotationNoListTuplePuns.stdout
- testsuite/tests/printer/T17697.stderr
- testsuite/tests/printer/T18791.stderr
- testsuite/tests/printer/Test20297.stdout
- testsuite/tests/printer/Test24533.stdout
- testsuite/tests/profiling/should_run/caller-cc/CallerCcParser.hs
- testsuite/tests/rename/should_fail/T15607.stderr
- testsuite/tests/rename/should_fail/T19843b.stderr
- + testsuite/tests/rts/T24450.hs
- + testsuite/tests/rts/T24450.stderr
- testsuite/tests/rts/all.T
- testsuite/tests/rts/rtsflags001.stderr-ws-32
- testsuite/tests/rts/rtsflags001.stderr-ws-64
- testsuite/tests/safeHaskell/ghci/p4.stderr
- testsuite/tests/safeHaskell/ghci/p6.stderr
- testsuite/tests/simplCore/should_compile/T22375.stderr
- testsuite/tests/simplCore/should_compile/T22375DataFamily.stderr
- testsuite/tests/simplCore/should_compile/T22611.hs
- testsuite/tests/simplCore/should_compile/T22611.stderr
- + testsuite/tests/simplCore/should_compile/T22611a.hs
- + testsuite/tests/simplCore/should_compile/T27936.hs
- + testsuite/tests/simplCore/should_compile/T7803.hs
- + testsuite/tests/simplCore/should_compile/T7803.stderr
- + testsuite/tests/simplCore/should_compile/T7803a.hs
- testsuite/tests/simplCore/should_compile/all.T
- testsuite/tests/typecheck/should_compile/LocalGivenEqs.hs
- testsuite/tests/typecheck/should_compile/T11254.stderr
- testsuite/tests/typecheck/should_compile/T15370.stderr
- + testsuite/tests/typecheck/should_compile/T26543_orig.hs
- + testsuite/tests/typecheck/should_compile/T27916.hs
- testsuite/tests/typecheck/should_compile/all.T
- testsuite/tests/typecheck/should_compile/valid_hole_fits.stderr
- testsuite/tests/typecheck/should_fail/ClassOperator.stderr
- testsuite/tests/typecheck/should_fail/DoExpansion2.stderr
- testsuite/tests/typecheck/should_fail/DoExpansion3.stderr
- testsuite/tests/typecheck/should_fail/FunDepOrigin1b.hs
- testsuite/tests/typecheck/should_fail/T12785b.stderr
- testsuite/tests/typecheck/should_fail/T18851.stderr
- + testsuite/tests/typecheck/should_fail/T18851e.hs
- + testsuite/tests/typecheck/should_fail/T18851e.stderr
- + testsuite/tests/typecheck/should_fail/T18851f.hs
- + testsuite/tests/typecheck/should_fail/T18851f.stderr
- testsuite/tests/typecheck/should_fail/T22707.stderr
- testsuite/tests/typecheck/should_fail/T22940.stderr
- + testsuite/tests/typecheck/should_fail/T26543a.hs
- + testsuite/tests/typecheck/should_fail/T26543a.stderr
- testsuite/tests/typecheck/should_fail/T26823.stderr
- + testsuite/tests/typecheck/should_fail/T27731.hs
- + testsuite/tests/typecheck/should_fail/T27731.stderr
- + testsuite/tests/typecheck/should_fail/T27844.hs
- + testsuite/tests/typecheck/should_fail/T27844.stderr
- testsuite/tests/typecheck/should_fail/T5691.stderr
- testsuite/tests/typecheck/should_fail/T7437.stderr
- testsuite/tests/typecheck/should_fail/all.T
- testsuite/tests/typecheck/should_fail/mc24.stderr
- testsuite/tests/typecheck/should_fail/tcfail019.stderr
- testsuite/tests/typecheck/should_fail/tcfail189.stderr
- utils/check-exact/ExactPrint.hs
- utils/check-exact/Parsers.hs
- utils/check-exact/Utils.hs
- utils/check-ppr/Main.hs
- utils/count-deps/Main.hs
- utils/dump-decls/Main.hs
- utils/haddock/haddock-api/src/Haddock.hs
- utils/haddock/haddock-api/src/Haddock/Backends/Hyperlinker/Renderer.hs
- utils/haddock/haddock-api/src/Haddock/Backends/Hyperlinker/Utils.hs
- utils/haddock/haddock-api/test/Haddock/Backends/Hyperlinker/ParserSpec.hs
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/98b36f4b69ab22049d4597d50c6dfe…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/98b36f4b69ab22049d4597d50c6dfe…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc][wip/andreask/cfg-fix] 6 commits: Fix #27836, normalise unit database path in ExternalUnitDatabases
by Sylvain Henry (@hsyl20) 16 Oct '26
by Sylvain Henry (@hsyl20) 16 Oct '26
16 Oct '26
Sylvain Henry pushed to branch wip/andreask/cfg-fix at Glasgow Haskell Compiler / GHC
Commits:
3a72b8a2 by Hannes Siebenhandl at 2026-10-14T13:48:32-04:00
Fix #27836, normalise unit database path in ExternalUnitDatabases
Add a regression test, proofing that all variations:
- local-unit-db/my-test.conf
- ./local-unit-db/my-test.conf
- ./local-unit-db/my-test.conf/
are parsed only once.
- - - - -
8ddbc6f9 by Florian Ragwitz at 2026-10-14T13:49:28-04:00
Remove obsolete HPC types
Fixes #27946.
- - - - -
f34c79ee by Alan Zimmerman at 2026-10-15T04:54:47-04:00
EPA: Start using vocurly as basis for AnnListLayout
For the existing cases that populate AnnList.
This uses AnnListBraces when braces are explicitly supplied, and
AnnListLayout when vocurly is used
The change also shows up AnnList usages that can never capture layout,
these are cleared up later.
- - - - -
033ba59c by sheaf at 2026-10-15T04:55:44-04:00
Make exprFreeVars deep
exprFreeVars used to be a shallow free-variable finder (it didn't look
into kinds), but most callers wanted it to be deep. In particular,
'exprFreeVars' is often used to seed an 'InScopeSet', and that must
contain the /deep/ free variables.
This commit makes it deep, which allows us to get rid of calls to
'closeOverKinds' or other workarounds for shallowness in:
- 'GHC.Core.Opt.Simplify.Utils.abstractFloats'
- 'GHC.HsToCore.Binds.dsSpec_help'
- 'GHC.Core.Opt.Arity.etaBodyForJoinPoint'
- 'GHC.Core.FVs.freeVars'
- 'GHC.Core.Lint.lintCoreRule'
We also remove 'deepExprsFreeVarsDSet' and 'closeOverKindsDSet'.
Other places needed a little bit more care, in particular to properly
handle coercion variables free in kinds:
- 'GHC.Core.Opt.Specialise.specHeader' quantifies over the binder of
an unspecialised argument directly, instead of computing the free Ids
of the argument.
- 'GHC.HsToCore.dsWarnRuleShadowing' filters out 'CoVar's.
- 'GHC.Core.Opt.SpecConstr.callToPat' had some ad-hoc logic to compute
argument pattern types and a workaround with 'expandTypeSynonyms'.
That logic is removed in favour of a new 'argsToPats' function which
directly computes the argument pattern types by instantiating the
type of the head of the call pattern.
Fixes #27936
- - - - -
f93d523c by Luite Stegeman at 2026-10-15T04:56:34-04:00
testsuite: Use mkWeakMVar in memo001/memo002
mkWeakPtr in the memo001/memo001 tests created weak pointers
with the MVar box as the key, which is fragile in the presence
of optimization. The fix is using mkWeakMVar, keying on the
primitive MVar# instead.
Fixes #27924 and #27396
- - - - -
b24112fd by Andreas Klebinger at 2026-10-16T22:15:01+02:00
x86 ncg: Track the current block in NatM to keep the CFG in sync
The x86 NCG maintains a CFG that is used for code layout. Whenever
instruction selection introduces new basic blocks (for instance for
word-to-float conversions, cmpxchg based atomic operations, ctz on
i386 or 64-bit shifts on i386) it must update this CFG, and the code
that follows must use the new block as its origin.
Before this patch the current block was threaded explicitly through
some statement-level functions only. Block-introducing primops that
were dispatched as "simple" (word2Float#, #27915) and the 64-bit shifts
in iselExpr64 did not update the CFG at all. This resulted in an
out-of-sync CFG, bad code layout and the "Can't find weight for edge
that should have one" panic once the register allocator inserted
fixup blocks (#27694, #27915).
We now keep the current block in the NatM state and provide a few
combinators (continueInNewBlock, addCondBlock, addDiamondFlow,
addColdSelfLoop, increaseEdgeWeight) that update the CFG and the
current block at the same time. See Note [Updating the CFG during
CodeGen] in GHC.CmmToAsm.Monad.
The cfg sanity check (-dasm-lint) now also checks that all branches in
the generated code have a matching edge in the CFG, which catches this
class of bug early. It immediately found another desync: when the
register allocator needs more stack than preallocated, allocMoreStack
moves the body of every entry block into a new block and retargets the
local jumps to it, but the CFG only recorded the new block as the
immediate successor of the entry block. The new addPreentryBlock also
redirects the jump edges (and keeps the call edges, since returns still
go through the entry block).
Fixes #27694, #27915
Co-authored-by: Sylvain Henry <sylvain(a)haskus.fr>
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
51 changed files:
- + changelog.d/27694
- + changelog.d/27936
- + changelog.d/hpc-cleanup
- changelog.d/unit-index
- compiler/GHC/CmmToAsm.hs
- compiler/GHC/CmmToAsm/BlockLayout.hs
- compiler/GHC/CmmToAsm/CFG.hs
- compiler/GHC/CmmToAsm/Monad.hs
- compiler/GHC/CmmToAsm/X86/CodeGen.hs
- compiler/GHC/CmmToAsm/X86/Instr.hs
- compiler/GHC/Core/FVs.hs
- compiler/GHC/Core/Lint.hs
- compiler/GHC/Core/Opt/Arity.hs
- compiler/GHC/Core/Opt/Simplify/Utils.hs
- compiler/GHC/Core/Opt/SpecConstr.hs
- compiler/GHC/Core/Opt/Specialise.hs
- compiler/GHC/Core/Subst.hs
- compiler/GHC/Core/TyCo/FVs.hs
- compiler/GHC/Core/Type.hs
- compiler/GHC/CoreToIface.hs
- compiler/GHC/CoreToStg.hs
- compiler/GHC/Data/OsPath.hs
- compiler/GHC/HsToCore.hs
- compiler/GHC/HsToCore/Binds.hs
- compiler/GHC/Parser.y
- compiler/GHC/StgToJS/ExprCtx.hs
- compiler/GHC/Tc/Utils/TcType.hs
- compiler/GHC/Types/Id/Info.hs
- compiler/GHC/Types/Var/FV.hs
- compiler/GHC/Unit/External/Database.hs
- libraries/base/tests/Memo1.lhs
- libraries/base/tests/Memo2.lhs
- libraries/base/tests/all.T
- + testsuite/tests/codeGen/should_compile/T27694.hs
- testsuite/tests/codeGen/should_compile/all.T
- + testsuite/tests/codeGen/should_run/T27915.hs
- + testsuite/tests/codeGen/should_run/T27915.stdout-ws-32
- + testsuite/tests/codeGen/should_run/T27915.stdout-ws-64
- testsuite/tests/codeGen/should_run/all.T
- + testsuite/tests/driver/T27836/A.hs
- + testsuite/tests/driver/T27836/B.hs
- + testsuite/tests/driver/T27836/C.hs
- + testsuite/tests/driver/T27836/Makefile
- + testsuite/tests/driver/T27836/T27836.stdout
- + testsuite/tests/driver/T27836/all.T
- + testsuite/tests/driver/T27836/unitA
- + testsuite/tests/driver/T27836/unitB
- + testsuite/tests/driver/T27836/unitC
- testsuite/tests/parser/should_compile/DumpSemis.stderr
- + testsuite/tests/simplCore/should_compile/T27936.hs
- testsuite/tests/simplCore/should_compile/all.T
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/c56aa4177c05d2d3b0e7f1fc22df66…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/c56aa4177c05d2d3b0e7f1fc22df66…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc][wip/marge_bot_batch_merge_job] EPA: Add TTG fields to FamilyInfo
by Marge Bot (@marge-bot) 16 Oct '26
by Marge Bot (@marge-bot) 16 Oct '26
16 Oct '26
Marge Bot pushed to branch wip/marge_bot_batch_merge_job at Glasgow Haskell Compiler / GHC
Commits:
dd86b6a7 by Alan Zimmerman at 2026-10-16T14:12:16-04:00
EPA: Add TTG fields to FamilyInfo
This commit is a simple add, with unused extension fields.
It lays the groundwork for using them for exact print annotations
- - - - -
22 changed files:
- compiler/GHC/Hs/Decls.hs
- compiler/GHC/Hs/Utils.hs
- compiler/GHC/HsToCore/Quote.hs
- compiler/GHC/Iface/Ext/Ast.hs
- compiler/GHC/Parser.y
- compiler/GHC/Parser/PostProcess.hs
- compiler/GHC/Rename/Module.hs
- compiler/GHC/Tc/TyCl.hs
- compiler/GHC/ThToHs.hs
- compiler/Language/Haskell/Syntax/Decls.hs
- compiler/Language/Haskell/Syntax/Extension.hs
- testsuite/tests/haddock/should_compile_flag_haddock/T17544.stderr
- testsuite/tests/parser/should_compile/DumpParsedAst.stderr
- testsuite/tests/parser/should_compile/DumpRenamedAst.stderr
- testsuite/tests/parser/should_compile/KindSigs.stderr
- utils/check-exact/ExactPrint.hs
- utils/haddock/haddock-api/src/Haddock/Backends/Hoogle.hs
- utils/haddock/haddock-api/src/Haddock/Backends/LaTeX.hs
- utils/haddock/haddock-api/src/Haddock/Backends/Xhtml/Decl.hs
- utils/haddock/haddock-api/src/Haddock/Convert.hs
- utils/haddock/haddock-api/src/Haddock/Interface/Rename.hs
- utils/haddock/haddock-api/src/Haddock/Types.hs
Changes:
=====================================
compiler/GHC/Hs/Decls.hs
=====================================
@@ -482,12 +482,12 @@ instance NoAnn AnnSynDecl where
------------- Pretty printing FamilyDecls -----------
-pprFlavour :: FamilyInfo pass -> SDoc
-pprFlavour DataFamily = text "data"
-pprFlavour OpenTypeFamily = text "type"
+pprFlavour :: FamilyInfo (GhcPass pass) -> SDoc
+pprFlavour DataFamily {} = text "data"
+pprFlavour OpenTypeFamily {} = text "type"
pprFlavour (ClosedTypeFamily {}) = text "type"
-instance Outputable (FamilyInfo pass) where
+instance Outputable (FamilyInfo (GhcPass pass)) where
ppr info = pprFlavour info <+> text "family"
@@ -642,8 +642,8 @@ tyClDeclFlavour (ClassDecl {}) = ClassFlavour
tyClDeclFlavour (SynDecl {}) = TypeSynonymFlavour
tyClDeclFlavour (FamDecl { tcdFam = FamilyDecl { fdInfo = info }})
= case info of
- DataFamily -> OpenFamilyFlavour (IAmData DataType) Nothing
- OpenTypeFamily -> OpenFamilyFlavour IAmType Nothing
+ DataFamily {} -> OpenFamilyFlavour (IAmData DataType) Nothing
+ OpenTypeFamily {} -> OpenFamilyFlavour IAmType Nothing
ClosedTypeFamily {} -> ClosedTypeFamilyFlavour
tyClDeclFlavour (DataDecl { tcdDataDefn = HsDataDefn { dd_cons = nd } })
= case dataDefnConsNewOrData nd of
@@ -742,6 +742,11 @@ resultVariableName _ = Nothing
type instance XCInjectivityAnn (GhcPass _) = TokRarrow
type instance XXInjectivityAnn (GhcPass _) = DataConCantHappen
+type instance XDataFamily (GhcPass _) = NoExtField
+type instance XOpenTypeFamily (GhcPass _) = NoExtField
+type instance XClosedTypeFamily (GhcPass _) = NoExtField
+type instance XXFamilyInfo (GhcPass _) = DataConCantHappen
+
instance OutputableBndrId p
=> Outputable (FamilyDecl (GhcPass p)) where
ppr (FamilyDecl { fdInfo = info, fdLName = ltycon
@@ -768,7 +773,7 @@ instance OutputableBndrId p
hsep [ vbar, ppr lhs, arrow, hsep (map ppr rhs) ]
Nothing -> empty
(pp_where, pp_eqns) = case info of
- ClosedTypeFamily mb_eqns ->
+ ClosedTypeFamily _ mb_eqns ->
( text "where"
, case mb_eqns of
Nothing -> text ".."
=====================================
compiler/GHC/Hs/Utils.hs
=====================================
@@ -1543,15 +1543,15 @@ hsLTyClDeclBinders (L loc (DataDecl { tcdLName = (L _ name)
familyInfoTyConFlavour
:: Maybe tc -- ^ Just cls <=> this is an associated family of class cls
- -> FamilyInfo pass
+ -> FamilyInfo (GhcPass pass)
-> TyConFlavour tc
familyInfoTyConFlavour mb_parent_tycon info =
case info of
- DataFamily -> OpenFamilyFlavour (IAmData DataType) mb_parent_tycon
- OpenTypeFamily -> OpenFamilyFlavour IAmType mb_parent_tycon
- ClosedTypeFamily _ -> assert (isNothing mb_parent_tycon)
- -- See Note [Closed type family mb_parent_tycon]
- ClosedTypeFamilyFlavour
+ DataFamily _ -> OpenFamilyFlavour (IAmData DataType) mb_parent_tycon
+ OpenTypeFamily _ -> OpenFamilyFlavour IAmType mb_parent_tycon
+ ClosedTypeFamily _ _ -> assert (isNothing mb_parent_tycon)
+ -- See Note [Closed type family mb_parent_tycon]
+ ClosedTypeFamilyFlavour
-------------------
hsForeignDeclsBinders :: forall p a. (UnXRec (GhcPass p), IsSrcSpanAnn p a)
=====================================
compiler/GHC/HsToCore/Quote.hs
=====================================
@@ -554,19 +554,19 @@ repFamilyDecl decl@(L loc (FamilyDecl { fdInfo = info
; dec <- addQTyVarBinds ReuseBoundNames tvs $ \bndrs ->
addSimpleTyVarBinds ReuseBoundNames (maybeToList res_tv) $
case info of
- ClosedTypeFamily Nothing ->
+ ClosedTypeFamily _ Nothing ->
notHandled (ThAbstractClosedTypeFamily decl)
- ClosedTypeFamily (Just eqns) ->
+ ClosedTypeFamily _ (Just eqns) ->
do { eqns1 <- mapM (repTyFamEqn . unLoc) eqns
; eqns2 <- coreListM tySynEqnTyConOcc eqns1
; result <- repFamilyResultSig resultSig
; inj <- repInjectivityAnn injectivity
; repClosedFamilyD tc1 bndrs result inj eqns2 }
- OpenTypeFamily ->
+ OpenTypeFamily _ ->
do { result <- repFamilyResultSig resultSig
; inj <- repInjectivityAnn injectivity
; repOpenFamilyD tc1 bndrs result inj }
- DataFamily ->
+ DataFamily _ ->
do { kind <- repFamilyResultSigToMaybeKind resultSig
; repDataFamilyD tc1 bndrs kind }
; return (locA loc, dec)
=====================================
compiler/GHC/Iface/Ext/Ast.hs
=====================================
@@ -1669,7 +1669,7 @@ instance ToHie (LocatedA (FamilyDecl GhcRn)) where
injSpan = maybe NoScope (mkScope . getLocA) inj
instance ToHie (FamilyInfo GhcRn) where
- toHie (ClosedTypeFamily (Just eqns)) = concatM $
+ toHie (ClosedTypeFamily _ (Just eqns)) = concatM $
[ concatMapM (locOnly . getLocA) eqns
, toHie $ map go eqns
]
=====================================
compiler/GHC/Parser.y
=====================================
@@ -1389,7 +1389,7 @@ ty_decl :: { LTyClDecl GhcPs }
-- data/newtype family
| 'data' 'family' type opt_datafam_kind_sig
{% do { let { tdcolon = fst $ unLoc $4 }
- ; mkFamDecl (comb4 $1 $2 $3 $4) DataFamily TopLevel $3
+ ; mkFamDecl (comb4 $1 $2 $3 $4) (DataFamily noExtField) TopLevel $3
(snd $ unLoc $4) Nothing
(AnnFamilyDecl [] [] noAnn (epTok $1) (epTok $2) tdcolon noAnn noAnn noAnn noAnn noAnn noAnn) }}
@@ -1523,10 +1523,10 @@ inj_varids :: { Located [LocatedN RdrName] }
-- Closed type families
where_type_family :: { Located ((EpToken "where", (EpToken "{", EpToken "..", EpToken "}")),FamilyInfo GhcPs) }
- : {- empty -} { noLoc (noAnn,OpenTypeFamily) }
+ : {- empty -} { noLoc (noAnn,OpenTypeFamily noExtField) }
| 'where' ty_fam_inst_eqn_list
{ sLL $1 $> ((epTok $1,(fst $ unLoc $2))
- ,ClosedTypeFamily (fmap reverse $ snd $ unLoc $2)) }
+ , ClosedTypeFamily noExtField (fmap reverse $ snd $ unLoc $2)) }
ty_fam_inst_eqn_list :: { Located ((EpToken "{", EpToken "..", EpToken "}"),Maybe [LTyFamInstEqn GhcPs]) }
: '{' ty_fam_inst_eqns '}' { sLL $1 $> ((epTok $1,noAnn, epTok $3)
@@ -1578,7 +1578,7 @@ at_decl_cls :: { LHsDecl GhcPs }
: -- data family declarations, with optional 'family' keyword
'data' opt_family type opt_datafam_kind_sig
{% do { let { tdcolon = fst $ unLoc $4 }
- ; liftM mkTyClD (mkFamDecl (comb3 $1 $3 $4) DataFamily NotTopLevel $3
+ ; liftM mkTyClD (mkFamDecl (comb3 $1 $3 $4) (DataFamily noExtField) NotTopLevel $3
(snd $ unLoc $4) Nothing
(AnnFamilyDecl [] [] noAnn (epTok $1) $2 tdcolon noAnn noAnn noAnn noAnn noAnn noAnn)) }}
@@ -1587,14 +1587,14 @@ at_decl_cls :: { LHsDecl GhcPs }
| 'type' type opt_at_kind_inj_sig
{% do { let { (tdcolon, tequal, tvbar) = fst $ unLoc $3 }
; liftM mkTyClD
- (mkFamDecl (comb3 $1 $2 $3) OpenTypeFamily NotTopLevel $2
+ (mkFamDecl (comb3 $1 $2 $3) (OpenTypeFamily noExtField) NotTopLevel $2
(fst . snd $ unLoc $3)
(snd . snd $ unLoc $3)
(AnnFamilyDecl [] [] (epTok $1) noAnn noAnn tdcolon tequal tvbar noAnn noAnn noAnn noAnn)) }}
| 'type' 'family' type opt_at_kind_inj_sig
{% do { let { (tdcolon, tequal, tvbar) = fst $ unLoc $4 }
; liftM mkTyClD
- (mkFamDecl (comb3 $1 $3 $4) OpenTypeFamily NotTopLevel $3
+ (mkFamDecl (comb3 $1 $3 $4) (OpenTypeFamily noExtField) NotTopLevel $3
(fst . snd $ unLoc $4)
(snd . snd $ unLoc $4)
(AnnFamilyDecl [] [] (epTok $1) noAnn (epTok $2) tdcolon tequal tvbar noAnn noAnn noAnn noAnn)) }}
=====================================
compiler/GHC/Parser/PostProcess.hs
=====================================
@@ -384,8 +384,8 @@ mkFamDecl loc info topLevel lhs ksig injAnn annsIn
, fdInjectivityAnn = injAnn }))) }
where
equals_or_where = case info of
- DataFamily -> empty
- OpenTypeFamily -> empty
+ DataFamily {} -> empty
+ OpenTypeFamily {} -> empty
ClosedTypeFamily {} -> whereDots
mkSpliceDecl :: LHsExpr GhcPs -> (LHsDecl GhcPs)
=====================================
compiler/GHC/Rename/Module.hs
=====================================
@@ -2437,15 +2437,15 @@ rnFamDecl mb_cls (FamilyDecl { fdLName = tycon, fdTyVars = tyvars
----------------------
rn_info :: FamilyInfo GhcPs -> RnM (FamilyInfo GhcRn, FreeNames)
- rn_info (ClosedTypeFamily (Just eqns))
+ rn_info (ClosedTypeFamily x (Just eqns))
= do { (eqns', fvs)
<- rnList (rnTyFamInstEqn (NonAssocTyFamEqn ClosedTyFam)) eqns
-- no class context
- ; return (ClosedTypeFamily (Just eqns'), fvs) }
- rn_info (ClosedTypeFamily Nothing)
- = return (ClosedTypeFamily Nothing, emptyFNs)
- rn_info OpenTypeFamily = return (OpenTypeFamily, emptyFNs)
- rn_info DataFamily = return (DataFamily, emptyFNs)
+ ; return (ClosedTypeFamily x (Just eqns'), fvs) }
+ rn_info (ClosedTypeFamily x Nothing)
+ = return (ClosedTypeFamily x Nothing, emptyFNs)
+ rn_info (OpenTypeFamily x) = return (OpenTypeFamily x, emptyFNs)
+ rn_info (DataFamily x) = return (DataFamily x, emptyFNs)
rnFamResultSig :: HsDocContext
-> FamilyResultSig GhcPs
=====================================
compiler/GHC/Tc/TyCl.hs
=====================================
@@ -2196,7 +2196,7 @@ kcTyClDecl (FamDecl _ (FamilyDecl { fdInfo = fd_info })) fam_tc
-- closed type families look at their equations, but other families don't
-- do anything here
= case fd_info of
- ClosedTypeFamily (Just eqns) -> mapM_ (kcTyFamInstEqn fam_tc) eqns
+ ClosedTypeFamily _ (Just eqns) -> mapM_ (kcTyFamInstEqn fam_tc) eqns
_ -> return ()
-------------------
@@ -3387,7 +3387,7 @@ tcFamDecl1 parent (FamilyDecl { fdInfo = fam_info
, fdLName = tc_lname@(L _ tc_name)
, fdResultSig = L _ sig
, fdInjectivityAnn = inj })
- | DataFamily <- fam_info
+ | DataFamily _ <- fam_info
= bindTyClTyVarsAndZonk tc_name $ \ kind tc_bndrs nb_eta res_kind -> do
{ traceTc "tcFamDecl1 data family:" (ppr tc_name)
; checkFamFlag tc_name
@@ -3413,7 +3413,7 @@ tcFamDecl1 parent (FamilyDecl { fdInfo = fam_info
parent inj
; return (tycon, []) }
- | OpenTypeFamily <- fam_info
+ | OpenTypeFamily _ <- fam_info
= bindTyClTyVarsAndZonk tc_name $ \ kind tc_bndrs _nb_eta res_kind -> do
{ traceTc "tcFamDecl1 open type family:" (ppr tc_name)
; checkFamFlag tc_name
@@ -3424,7 +3424,7 @@ tcFamDecl1 parent (FamilyDecl { fdInfo = fam_info
parent inj'
; return (tycon, []) }
- | ClosedTypeFamily mb_eqns <- fam_info
+ | ClosedTypeFamily _ mb_eqns <- fam_info
= -- Closed type families are a little tricky, because they contain the definition
-- of both the type family and the equations for a CoAxiom.
do { traceTc "tcFamDecl1 Closed type family:" (ppr tc_name)
=====================================
compiler/GHC/ThToHs.hs
=====================================
@@ -373,7 +373,7 @@ cvtDec (DataFamilyD tc tvs kind)
= do { (_, tc', tvs') <- cvt_tycl_hdr [] tc tvs
; result <- cvtMaybeKindToFamilyResultSig kind
; returnJustLA $ TyClD noExtField $ FamDecl noExtField $
- FamilyDecl noAnn DataFamily TopLevel tc' tvs' Prefix result Nothing }
+ FamilyDecl noAnn (DataFamily noExtField) TopLevel tc' tvs' Prefix result Nothing }
cvtDec (DataInstD ctxt bndrs tys ksig constrs derivs)
= do { (ctxt', tc', bndrs', typats') <- cvt_datainst_hdr ctxt bndrs tys
@@ -427,14 +427,14 @@ cvtDec (TySynInstD eqn)
cvtDec (OpenTypeFamilyD head)
= do { (tc', tyvars', result', injectivity') <- cvt_tyfam_head head
; returnJustLA $ TyClD noExtField $ FamDecl noExtField $
- FamilyDecl noAnn OpenTypeFamily TopLevel tc' tyvars' Prefix result' injectivity'
+ FamilyDecl noAnn (OpenTypeFamily noExtField) TopLevel tc' tyvars' Prefix result' injectivity'
}
cvtDec (ClosedTypeFamilyD head eqns)
= do { (tc', tyvars', result', injectivity') <- cvt_tyfam_head head
; eqns' <- mapM cvtTySynEqn eqns
; returnJustLA $ TyClD noExtField $ FamDecl noExtField $
- FamilyDecl noAnn (ClosedTypeFamily (Just eqns')) TopLevel tc' tyvars' Prefix
+ FamilyDecl noAnn (ClosedTypeFamily noExtField (Just eqns')) TopLevel tc' tyvars' Prefix
result' injectivity' }
cvtDec (TH.RoleAnnotD tc roles)
=====================================
compiler/Language/Haskell/Syntax/Decls.hs
=====================================
@@ -503,15 +503,15 @@ isFamilyDecl _other = False
-- | type family declaration
isTypeFamilyDecl :: TyClDecl pass -> Bool
isTypeFamilyDecl (FamDecl _ (FamilyDecl { fdInfo = info })) = case info of
- OpenTypeFamily -> True
+ OpenTypeFamily {} -> True
ClosedTypeFamily {} -> True
_ -> False
isTypeFamilyDecl _ = False
-- | open type family info
isOpenTypeFamilyInfo :: FamilyInfo pass -> Bool
-isOpenTypeFamilyInfo OpenTypeFamily = True
-isOpenTypeFamilyInfo _ = False
+isOpenTypeFamilyInfo OpenTypeFamily {} = True
+isOpenTypeFamilyInfo _ = False
-- | closed type family info
isClosedTypeFamilyInfo :: FamilyInfo pass -> Bool
@@ -520,7 +520,7 @@ isClosedTypeFamilyInfo _ = False
-- | data family declaration
isDataFamilyDecl :: TyClDecl pass -> Bool
-isDataFamilyDecl (FamDecl _ (FamilyDecl { fdInfo = DataFamily })) = True
+isDataFamilyDecl (FamDecl _ (FamilyDecl { fdInfo = DataFamily _ })) = True
isDataFamilyDecl _other = False
-- Dealing with names
@@ -771,11 +771,12 @@ data InjectivityAnn pass
| XInjectivityAnn !(XXInjectivityAnn pass)
data FamilyInfo pass
- = DataFamily
- | OpenTypeFamily
+ = DataFamily (XDataFamily pass)
+ | OpenTypeFamily (XOpenTypeFamily pass)
-- | 'Nothing' if we're in an hs-boot file and the user
-- said "type family Foo x where .."
- | ClosedTypeFamily (Maybe [LTyFamInstEqn pass])
+ | ClosedTypeFamily (XClosedTypeFamily pass) (Maybe [LTyFamInstEqn pass])
+ | XFamilyInfo !(XXFamilyInfo pass)
{- Note [Closed type family mb_parent_tycon]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
=====================================
compiler/Language/Haskell/Syntax/Extension.hs
=====================================
@@ -473,6 +473,13 @@ type family XXRoleAnnotDecl x
type family XCInjectivityAnn x
type family XXInjectivityAnn x
+-- -------------------------------------
+-- FamilyInfo type families
+type family XDataFamily x
+type family XOpenTypeFamily x
+type family XClosedTypeFamily x
+type family XXFamilyInfo x
+
-- =====================================================================
-- Type families for the HsModule extension points
=====================================
testsuite/tests/haddock/should_compile_flag_haddock/T17544.stderr
=====================================
@@ -930,7 +930,8 @@
(EpTok
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
- (DataFamily)
+ (DataFamily
+ (NoExtField))
(NotTopLevel)
(L
(EpAnn
@@ -1325,7 +1326,8 @@
(EpTok
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
- (DataFamily)
+ (DataFamily
+ (NoExtField))
(NotTopLevel)
(L
(EpAnn
@@ -1720,7 +1722,8 @@
(EpTok
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
- (DataFamily)
+ (DataFamily
+ (NoExtField))
(NotTopLevel)
(L
(EpAnn
@@ -2115,7 +2118,8 @@
(EpTok
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
- (DataFamily)
+ (DataFamily
+ (NoExtField))
(NotTopLevel)
(L
(EpAnn
@@ -2510,7 +2514,8 @@
(EpTok
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
- (DataFamily)
+ (DataFamily
+ (NoExtField))
(NotTopLevel)
(L
(EpAnn
@@ -2905,7 +2910,8 @@
(EpTok
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
- (DataFamily)
+ (DataFamily
+ (NoExtField))
(NotTopLevel)
(L
(EpAnn
=====================================
testsuite/tests/parser/should_compile/DumpParsedAst.stderr
=====================================
@@ -364,6 +364,7 @@
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
(ClosedTypeFamily
+ (NoExtField)
(Just
[(L
(EpAnn
@@ -1148,6 +1149,7 @@
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
(ClosedTypeFamily
+ (NoExtField)
(Just
[(L
(EpAnn
@@ -1545,7 +1547,8 @@
(EpTok
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
- (DataFamily)
+ (DataFamily
+ (NoExtField))
(TopLevel)
(L
(EpAnn
=====================================
testsuite/tests/parser/should_compile/DumpRenamedAst.stderr
=====================================
@@ -311,6 +311,7 @@
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
(ClosedTypeFamily
+ (NoExtField)
(Just
[(L
(EpAnn
@@ -798,7 +799,8 @@
(EpTok
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
- (DataFamily)
+ (DataFamily
+ (NoExtField))
(TopLevel)
(L
(EpAnn
@@ -1183,6 +1185,7 @@
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
(ClosedTypeFamily
+ (NoExtField)
(Just
[(L
(EpAnn
@@ -1766,7 +1769,8 @@
(EpTok
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
- (OpenTypeFamily)
+ (OpenTypeFamily
+ (NoExtField))
(NotTopLevel)
(L
(EpAnn
=====================================
testsuite/tests/parser/should_compile/KindSigs.stderr
=====================================
@@ -113,6 +113,7 @@
(EpaSpan { <no location info> }))
(EpTok (EpaSpan { <no location info> })))
(ClosedTypeFamily
+ (NoExtField)
(Just
[(L
(EpAnn
=====================================
utils/check-exact/ExactPrint.hs
=====================================
@@ -3844,7 +3844,7 @@ instance ExactPrint (FamilyDecl GhcPs) where
return (vb', Just inj')
(w', oc', dd', cc', info') <-
case info of
- ClosedTypeFamily mb_eqns -> do
+ ClosedTypeFamily x mb_eqns -> do
w' <- markEpToken w
oc' <- markEpToken oc
(dd', mb_eqns') <-
@@ -3856,7 +3856,7 @@ instance ExactPrint (FamilyDecl GhcPs) where
eqns' <- mapM markAnnotated eqns
return (dd, Just eqns')
cc' <- markEpToken cc
- return (w',oc',dd',cc', ClosedTypeFamily mb_eqns')
+ return (w',oc',dd',cc', ClosedTypeFamily x mb_eqns')
_ -> return (w,oc,dd,cc, info)
return (FamilyDecl { fdExt = AnnFamilyDecl [] [] t' d' f' dc' eq' vb' w' oc' dd' cc'
, fdInfo = info'
@@ -3890,8 +3890,8 @@ instance ExactPrint (FamilyDecl GhcPs) where
exactFlavour :: (Monad m, Monoid w) => (EpToken "data", EpToken "type") -> FamilyInfo GhcPs -> EP w m (EpToken "data", EpToken "type")
-exactFlavour (td,tt) DataFamily = (\td' -> (td',tt)) <$> markEpToken td
-exactFlavour (td,tt) OpenTypeFamily = (td,) <$> markEpToken tt
+exactFlavour (td,tt) DataFamily {} = (\td' -> (td',tt)) <$> markEpToken td
+exactFlavour (td,tt) OpenTypeFamily {} = (td,) <$> markEpToken tt
exactFlavour (td,tt) (ClosedTypeFamily {}) = (td,) <$> markEpToken tt
-- ---------------------------------------------------------------------
=====================================
utils/haddock/haddock-api/src/Haddock/Backends/Hoogle.hs
=====================================
@@ -254,7 +254,7 @@ ppFam sDocContext decl@(FamilyDecl{fdInfo = info}) =
decl' = case info of
-- We don't need to print out a closed type family's equations
-- for Hoogle, so pretend it doesn't have any.
- ClosedTypeFamily{} -> decl{fdInfo = OpenTypeFamily}
+ ClosedTypeFamily{} -> decl{fdInfo = OpenTypeFamily noExtField}
_ -> decl
ppInstance :: DynFlags -> UnitState -> ClsInst -> [String]
=====================================
utils/haddock/haddock-api/src/Haddock/Backends/LaTeX.hs
=====================================
@@ -373,11 +373,11 @@ ppFamDecl associated doc instances decl@(FamDecl{}) unicode =
body = Maybe.catMaybes [familyEqns, documentationToLaTeX doc]
whereBit = case fdInfo (tcdFam decl) of
- ClosedTypeFamily _ -> keyword "where"
+ ClosedTypeFamily _ _ -> keyword "where"
_ -> empty
familyEqns
- | FamilyDecl{fdInfo = ClosedTypeFamily (Just eqns)} <- tcdFam decl
+ | FamilyDecl{fdInfo = ClosedTypeFamily _ (Just eqns)} <- tcdFam decl
, not (null eqns) =
Just
( text "\\haddockbeginargs"
@@ -429,9 +429,9 @@ ppFamHeader
famly leader <+> famName <+> famSig <+> injAnn
where
leader = case info of
- OpenTypeFamily -> keyword "type"
- ClosedTypeFamily _ -> keyword "type"
- DataFamily -> keyword "data"
+ OpenTypeFamily _ -> keyword "type"
+ ClosedTypeFamily _ _ -> keyword "type"
+ DataFamily _ -> keyword "data"
famly
| associated = id
=====================================
utils/haddock/haddock-api/src/Haddock/Backends/Xhtml/Decl.hs
=====================================
@@ -548,7 +548,7 @@ ppFamDecl summary associated links instances fixities loc doc decl splice unicod
ppFamHeader summary associated decl unicode qual <+> ppFixities fixities qual
instancesBit
- | FamilyDecl{fdInfo = ClosedTypeFamily mb_eqns} <- decl
+ | FamilyDecl{fdInfo = ClosedTypeFamily _ mb_eqns} <- decl
, not summary =
subEquations pkg qual $ map (ppFamDeclEqn . unLoc) $ Maybe.fromMaybe [] mb_eqns
| otherwise =
@@ -603,7 +603,7 @@ ppFamHeader
]
where
whereBit = case info of
- ClosedTypeFamily _ -> keyword "where ..."
+ ClosedTypeFamily _ _ -> keyword "where ..."
_ -> noHtml
injAnn = case injectivity of
@@ -622,9 +622,9 @@ ppFamilyLeader :: Bool -> FamilyInfo DocNameI -> Html
ppFamilyLeader assoc info = keyword (typ ++ if assoc then "" else " family")
where
typ = case info of
- OpenTypeFamily -> "type"
- ClosedTypeFamily _ -> "type"
- DataFamily -> "data"
+ OpenTypeFamily _ -> "type"
+ ClosedTypeFamily _ _ -> "type"
+ DataFamily _ -> "data"
-- | Print the signature attached to a family
ppResultSig :: FamilyResultSig DocNameI -> Unicode -> Qualification -> Html
=====================================
utils/haddock/haddock-api/src/Haddock/Convert.hs
=====================================
@@ -306,20 +306,20 @@ synifyTyCon _prr _coax tc
| Just flav <- famTyConFlav_maybe tc =
case flav of
DataFamilyTyCon{} ->
- mkFamDecl DataFamily
- OpenTypeFamilyTyCon -> mkFamDecl OpenTypeFamily
+ mkFamDecl (DataFamily noExtField)
+ OpenTypeFamilyTyCon -> mkFamDecl (OpenTypeFamily noExtField)
ClosedTypeFamilyTyCon ctf ->
case ctf of
CTF mb
| Just (CoAxiom{co_ax_branches = branches}) <- mb
-> mkFamDecl $
- ClosedTypeFamily $
+ ClosedTypeFamily noExtField $
Just $
map (noLocA . synifyAxBranch tc) (fromBranches branches)
| otherwise
- -> mkFamDecl $ ClosedTypeFamily $ Just []
- CTF_BuiltIn {} -> mkFamDecl $ ClosedTypeFamily $ Just []
- CTF_Abstract -> mkFamDecl $ ClosedTypeFamily Nothing
+ -> mkFamDecl $ ClosedTypeFamily noExtField $ Just []
+ CTF_BuiltIn {} -> mkFamDecl $ ClosedTypeFamily noExtField $ Just []
+ CTF_Abstract -> mkFamDecl $ ClosedTypeFamily noExtField Nothing
where
resultVar = tyConFamilyResVar_maybe tc
mkFamDecl i =
=====================================
utils/haddock/haddock-api/src/Haddock/Interface/Rename.hs
=====================================
@@ -686,12 +686,12 @@ renameFamilyDecl
)
renameFamilyInfo :: FamilyInfo GhcRn -> RnM (FamilyInfo DocNameI)
-renameFamilyInfo DataFamily = return DataFamily
-renameFamilyInfo OpenTypeFamily = return OpenTypeFamily
-renameFamilyInfo (ClosedTypeFamily eqns) =
+renameFamilyInfo (DataFamily x) = return (DataFamily x)
+renameFamilyInfo (OpenTypeFamily x) = return (OpenTypeFamily x)
+renameFamilyInfo (ClosedTypeFamily x eqns) =
do
eqns' <- mapM (mapM (mapM renameTyFamInstEqn)) eqns
- return $ ClosedTypeFamily eqns'
+ return $ ClosedTypeFamily x eqns'
renameDataDefn :: HsDataDefn GhcRn -> RnM (HsDataDefn DocNameI)
renameDataDefn
=====================================
utils/haddock/haddock-api/src/Haddock/Types.hs
=====================================
@@ -1036,6 +1036,11 @@ type instance XSplicePat DocNameI = DataConCantHappen
type instance XCInjectivityAnn DocNameI = NoExtField
+type instance XDataFamily DocNameI = NoExtField
+type instance XOpenTypeFamily DocNameI = NoExtField
+type instance XClosedTypeFamily DocNameI = NoExtField
+type instance XXFamilyInfo DocNameI = DataConCantHappen
+
type instance XCFunDep DocNameI = NoExtField
type instance XCTyFamInstDecl DocNameI = NoExtField
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/dd86b6a761f471da6c5c1df1e1dfc11…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/dd86b6a761f471da6c5c1df1e1dfc11…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc][wip/romes/async-rpc] 2 commits: Revert "generalized handleRemoteCall to allow forking."
by Rodrigo Mesquita (@alt-romes) 16 Oct '26
by Rodrigo Mesquita (@alt-romes) 16 Oct '26
16 Oct '26
Rodrigo Mesquita pushed to branch wip/romes/async-rpc at Glasgow Haskell Compiler / GHC
Commits:
de57cda3 by Rodrigo Mesquita at 2026-10-16T16:07:19+01:00
Revert "generalized handleRemoteCall to allow forking."
This reverts commit 753abb8145b3591596e35f1e83307d1dcfae81e0.
- - - - -
05b34675 by Rodrigo Mesquita at 2026-10-16T17:21:46+01:00
better forkIO linear api and direct use in loop
- - - - -
5 changed files:
- libraries/ghci/GHCi/Message.hs
- libraries/ghci/GHCi/Message/Async.hs
- libraries/ghci/GHCi/Server.hs
- + libraries/ghci/GHCi/Server/Threads.hs
- libraries/ghci/ghci.cabal.in
Changes:
=====================================
libraries/ghci/GHCi/Message.hs
=====================================
@@ -26,7 +26,7 @@ module GHCi.Message
, Pipe(..), mkPipeFromHandles, mkPipeFromContinuations, closePipe
, remoteCall, remoteTHCall
- , handleRemoteCall, handleRemoteTHCall
+ , handleRemoteCall, handleRemoteTHCall, writeReply
, RemoteProcessException(..), PipeReadClosedException(..)
, InboxId(..)
@@ -55,6 +55,7 @@ import qualified GHC.Exts.Heap as Heap
import GHC.ForeignSrcLang
import GHC.Fingerprint
import GHC.Conc (pseq, par)
+import GHC.IO (IO(..))
import Control.Concurrent
import Control.DeepSeq
import Control.Exception
@@ -664,11 +665,13 @@ remoteCall pipe msg = either throwIO (pure . runGet get)
-- | Handle a single 'Message' request on the interpreter and reply to the host
handleRemoteCall :: Pipe
- -> (CorrelationId -> Msg -> (Msg -> IO ()) %1 -> IO ()) {-^ called with action that handles req and writes reply -}
- -> (forall a. (Show a, Binary a) => Message a -> IO a)
- -> IO ()
-handleRemoteCall pipe forkHandler k =
- handleAsyncReq pipe getMessage Nothing (\(Msg msg) -> fmap put . k $ msg) forkHandler
+ -> (Msg -> IO Msg) {-^ Msg hook -}
+ -> (forall a. (Show a, Binary a) => WriteReply a %1 -> Message a -> IO r)
+ -> IO r
+handleRemoteCall pipe hook k =
+ handleAsyncReq pipe getMessage Nothing \(WriteReply writer) msg0 -> IO \s0 ->
+ case hook msg0 |#> s0 of -- unIO for linearity checking
+ (# s1, Msg msg #) -> k (WriteReply \x -> writer (fmap put x)) msg |#> s1
-- | Send a 'THMessage' request to the host and wait for a reply from the host
-- to the interpreter.
@@ -686,5 +689,7 @@ remoteTHCall pipe ii msg = either throwIO (pure . runGet get)
handleRemoteTHCall
:: Pipe -> InboxId -> (forall a. (Show a, Binary a) => THMessage a -> IO a) -> IO ()
handleRemoteTHCall pipe ii k =
- handleAsyncReq pipe getTHMessage (Just ii) (\(THMsg msg) -> fmap put . k $ msg) $ \ _ msg hndlr -> hndlr msg
+ handleAsyncReq pipe getTHMessage (Just ii) \writer (THMsg msg) -> IO \s0 ->
+ case k msg |#> s0 of -- unIO for linearity checking
+ (# s1, a #) -> writeReply writer (put a) |#> s1
=====================================
libraries/ghci/GHCi/Message/Async.hs
=====================================
@@ -23,8 +23,8 @@ module GHCi.Message.Async
, IddMsg(..), newAsyncManager
-- ** Consume `reply` exactly once
- , WriteReply(..)
- , writeReply, (|#>), bindIO
+ , WriteReply(..), writeReply
+ , runWriteReply, (|#>), (%>>=)
-- * Serializable exceptions
, SerializableException(..)
@@ -226,9 +226,10 @@ remoteAsyncReq pipe msg ii = do
-- It must be used exactly once (all requests expect a reply, and you can't
-- reply more than once). Linear types enforce the handler replies in every
-- branch, and if the handler otherwise throws, it is handled by 'handleAsyncReq'.
-handleAsyncReq :: Pipe -> Get a -> (Maybe InboxId) -> (a -> IO Put) -> (CorrelationId -> a -> (a -> IO ()) %1 -> IO ()) -> IO ()
-handleAsyncReq pipe getit mii hndlr k = mask $ \restore -> do
+handleAsyncReq :: Pipe -> Get a -> (Maybe InboxId) -> (WriteReply Put %1 -> a -> IO r) -> IO r
+handleAsyncReq pipe getit mii k = mask $ \restore -> do
let am = pipeAsyncMngr pipe
+ ack <- newEmptyMVar
-- Block waiting for request
mbreq <- atomically $ do
@@ -246,6 +247,7 @@ handleAsyncReq pipe getit mii hndlr k = mask $ \restore -> do
Just (uq, bs) -> do
let reply p = do
writePipe pipe (Reply uq (bimap toSerializableException runPut p))
+ putMVar ack ()
-- Run the continuation which must reply exactly once with 'writeReply'
case runGetOrFail getit bs of
@@ -253,11 +255,20 @@ handleAsyncReq pipe getit mii hndlr k = mask $ \restore -> do
let exc = DecodeAsyncReqException err
reply (Left (toException exc))
throwIO exc
- Right (_, _, it) -> k uq it (\ msg -> do
- try @SomeException (restore (hndlr msg)) >>= \x -> do
- reply x
- either throwIO (const $ pure ()) x
- )
+ Right (_, _, it) ->
+ restore (k (WriteReply reply) it)
+
+ -- If there's an exception before the reply is sent, reply with an error instead.
+ `catch` \(e :: SomeException) -> do
+
+ tryTakeMVar ack >>= \case
+ Just () ->
+ -- Already replied
+ throwIO e
+ Nothing -> do
+ -- Reply with an error
+ reply (Left e)
+ throwIO e
-- | 'handleSyncReq' failed to decode an incoming request payload using the given @'Get' a@
newtype DecodeAsyncReqException = DecodeAsyncReqException String deriving Show
@@ -440,14 +451,19 @@ data WriteReply a where
writeReply :: WriteReply a %1 -> a -> IO ()
writeReply (WriteReply r) = \x -> r (Right x)
+-- | Write the reply with a value or an exception
+runWriteReply :: WriteReply a %1 -> Either SomeException a -> IO ()
+runWriteReply (WriteReply r) = r
+
-- | Infix, linear, 'unIO'
(|#>) :: IO a %1 -> State# RealWorld -> (# State# RealWorld, a #)
(|#>) (IO fs) s = fs s
-bindIO :: (IO a) -> (a -> IO b) %1 -> IO b
-bindIO = \ m f -> IO (\s0 ->
+(%>>=) :: (IO a) -> (a -> IO b) %1 -> IO b
+(%>>=) = \ m f -> IO (\s0 ->
case m |#> s0 of -- unIO for linearity checking
(# s1, x #) -> f x |#> s1)
+infixl 1 %>>=
--------------------------------------------------------------------------------
-- * Serializable Exceptions
=====================================
libraries/ghci/GHCi/Server.hs
=====================================
@@ -39,13 +39,8 @@ import System.Exit
import System.IO
import Control.Concurrent
-import Control.Concurrent.STM
-import Data.IntMap (IntMap)
-import qualified Data.IntMap as IM
-import GHCi.Message.Async (bindIO)
-import qualified Unsafe.Coerce as Unsafe
-
-type CorrelationId = Int
+import GHCi.Message.Async (runWriteReply, (%>>=))
+import GHCi.Server.Threads
type MessageHook = Msg -> IO Msg
@@ -62,49 +57,6 @@ serv :: Bool -> MessageHook -> Pipe -> (forall a .IO a -> IO a) -> IO ()
serv verbose hook pipe restore =
servWithCustom verbose hook pipe restore noCustomHandler
-
-data ThreadManager = ThreadManager
- { managedThreads :: !(TVar (IntMap ThreadId))
- , managerClosed :: !(TVar Bool)
- }
-
--- | Cancels and Waits for all threads spawned by ThreadManager to terminate before returning.
-withThreadManager :: (ThreadManager -> IO a) -> IO a
-withThreadManager k = do
- managedThreads <- newTVarIO IM.empty
- managerClosed <- newTVarIO False
- let tm = ThreadManager{..}
- k tm `finally` shutdown tm
- where
- shutdown ThreadManager{..} = do
- ts <- atomically $ do
- writeTVar managerClosed True
- IM.elems <$> readTVar managedThreads
- mapM_ killThread ts
-
-spawn :: ThreadManager -> CorrelationId -> IO () %1 -> IO ()
-spawn mng i = Unsafe.unsafeCoerce (spawn' mng i)
-
-spawn' :: ThreadManager -> CorrelationId -> IO () -> IO ()
-spawn' ThreadManager{..} i action = void $ mask_ $ forkIOWithUnmask $ \unmask -> do
- tid <- myThreadId
- registered <- atomically $ do
- s <- readTVar managerClosed
- unless s $ modifyTVar' managedThreads (IM.insert i tid)
- pure (not s)
- when registered $
- (unmask action)
- `finally` atomically (modifyTVar' managedThreads (IM.delete i))
-
--- could be used to cancel a specific handler.
--- cancel :: ThreadManager -> CorrelationId -> IO ()
--- cancel ThreadManager{..} i = do
--- ts <- atomically $ do
--- readTVar managedThreads
--- case IM.lookup i ts of
--- Just tid -> killThread tid
--- Nothing -> pure ()
-
servWithCustom
:: Bool
-> MessageHook
@@ -117,23 +69,23 @@ servWithCustom verbose hook pipe restore customHandler = do
withThreadManager $ \mngr ->
loop ref mngr `finally` closePipe pipe
where
- forkHandler mngr uq hndlr msg0@(Msg msg) = do
- (do discardCtrlC
- when verbose $ trace ("msg: " ++ (show msg))) `bindIO` \ _ -> do
- case msg of
- RunTH{} -> spawn mngr uq (hndlr msg0)
- RunModFinalizers{} -> spawn mngr uq (hndlr msg0)
- _ -> hndlr msg0
loop doneRef mngr = do
when verbose $ trace "reading pipe..."
- handleRemoteCall pipe (\uq msg act -> hook msg `bindIO` forkHandler mngr uq act) $ \(msg :: Message a) -> do
+
+ handleRemoteCall pipe hook $ \wr (msg :: Message a) ->
+
+ discardCtrlC %>>= \_ ->
+ when verbose (trace ("msg: " ++ (show msg))) %>>= \_ ->
+
case msg of
- CustomMessage tag payload -> handleCustom tag payload
- Shutdown -> writeIORef doneRef True >> reply ()
- -- TODO: These two should probably be done off the main thread
- RunTH ii st q ty loc -> wrapRunTH ii $ runTH pipe ii st q ty loc
- RunModFinalizers ii st qrefs -> wrapRunTH ii $ runModFinalizerRefs pipe ii st qrefs
- _other -> run msg >>= reply
+ CustomMessage tag payload -> handleCustom tag payload %>>= writeReply wr
+ Shutdown -> writeIORef doneRef True >>
+ reply () %>>= writeReply wr
+ RunTH ii st q ty loc -> spawnFinally mngr (runWriteReply wr)
+ (wrapRunTH ii (runTH pipe ii st q ty loc))
+ RunModFinalizers ii st qs -> spawnFinally mngr (runWriteReply wr)
+ (wrapRunTH ii (runModFinalizerRefs pipe ii st qs))
+ _other -> run msg >>= reply %>>= writeReply wr
isDone <- readIORef doneRef
if isDone then pure ()
@@ -149,7 +101,7 @@ servWithCustom verbose hook pipe restore customHandler = do
reply :: forall a. Show a => a -> IO a
reply r = do
when verbose $ trace ("writing pipe: " ++ show r)
- return r -- the result of the handler gets sent
+ return r -- the result of the handler is passed to writeReply
-- Run some TH code, which may interact with GHC by sending
-- THMessage requests, and then finally send RunTHDone followed by a
=====================================
libraries/ghci/GHCi/Server/Threads.hs
=====================================
@@ -0,0 +1,72 @@
+{-# LANGUAGE LambdaCase, CPP, RankNTypes, RecordWildCards, GADTs, ScopedTypeVariables, LinearTypes, BlockArguments #-}
+module GHCi.Server.Threads
+ ( ThreadManager -- abstract for linearity
+ , withThreadManager -- scoped, so that we're guaranteed to wait for threads
+ , spawnFinally
+ ) where
+
+import Prelude
+import Control.Exception
+import Control.Monad
+
+import Control.Concurrent
+import Control.Concurrent.STM
+import qualified Data.Set as Set
+import qualified Unsafe.Coerce as Unsafe
+
+data ThreadManager = ThreadManager
+ { managedThreads :: !(TVar (Set.Set ThreadId))
+ , managerClosed :: !(TVar Bool)
+ }
+
+-- | Cancels and Waits for all threads spawned by 'ThreadManager' to terminate
+-- before returning.
+--
+-- This thread manager which cancels then waits for all pending threads allows
+-- us to provide a resource-safe linearly typed 'spawnFinally', because
+-- 'withThreadManager' guarantees neither the threads nor their exceptions
+-- leak.
+withThreadManager :: (ThreadManager -> IO a) -> IO a
+withThreadManager k = do
+ managedThreads <- newTVarIO Set.empty
+ managerClosed <- newTVarIO False
+ let tm = ThreadManager{..}
+ k tm `finally` shutdown tm
+ where
+ shutdown ThreadManager{..} = do
+ ts <- atomically $ do
+ writeTVar managerClosed True
+ Set.elems <$> readTVar managedThreads
+ mapM_ killThread ts
+
+-- | Linear and resource-safe because 'ThreadManager' is guaranteed to wait or
+-- cancel all threads.
+spawnFinally :: ThreadManager -> (Either SomeException a -> IO ()) %1 -> IO a -> IO ()
+spawnFinally ThreadManager{..} = unsafeLinear \fin -> \action -> void $
+ forkFinally
+ ( mask $ \unmask -> do
+ tid <- myThreadId
+ registered <- atomically $ do
+ s <- readTVar managerClosed
+ unless s $ modifyTVar' managedThreads (Set.insert tid)
+ pure (not s)
+ if registered
+ then (unmask action)
+ `finally`
+ atomically (modifyTVar' managedThreads (Set.delete tid))
+ else throwIO ThreadKilled
+ )
+ ( \ea -> fin ea )
+
+unsafeLinear :: (a -> b) %1 -> (a %1 -> b)
+unsafeLinear = Unsafe.unsafeCoerce (Unsafe.unsafeCoerce :: (a -> b) -> (a %1 -> b))
+
+-- TODO:
+-- could be used to cancel a specific handler.
+-- cancel :: ThreadManager -> CorrelationId -> IO ()
+-- cancel ThreadManager{..} i = do
+-- ts <- atomically $ do
+-- readTVar managedThreads
+-- case IM.lookup i ts of
+-- Just tid -> killThread tid
+-- Nothing -> pure ()
=====================================
libraries/ghci/ghci.cabal.in
=====================================
@@ -68,6 +68,7 @@ library
GHCi.StaticPtrTable
GHCi.TH
GHCi.Server
+ GHCi.Server.Threads
if !arch(javascript)
exposed-modules:
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/ee5d2db04cf26509ae9bf565c73213…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/ee5d2db04cf26509ae9bf565c73213…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc][wip/T27737] 17 commits: Improve exprOkForSpeculation
by Simon Peyton Jones (@simonpj) 16 Oct '26
by Simon Peyton Jones (@simonpj) 16 Oct '26
16 Oct '26
Simon Peyton Jones pushed to branch wip/T27737 at Glasgow Haskell Compiler / GHC
Commits:
8c947573 by Simon Peyton Jones at 2026-10-16T13:11:53+01:00
Improve exprOkForSpeculation
Fixes #27910, which exposed an infelicity in exprOkForSpeculation
The new story is carefully described in new Note [exprOkForSpeculation],
esp (a-c) and (EOKS1).
- - - - -
b1623ed2 by Simon Peyton Jones at 2026-10-16T17:11:24+01:00
Don't push `case` inside `let` in Gentle simplification
Triggered by #27737 this MR arranges for the Simplifier NOT to do
K[ let binds in e ] --> let binds in K[ e ]
in when `sm_case_case` is on; that is, in the first "gentle"
simplication.
Needs better documentation, but see discussion on #27737.
- - - - -
cf59db84 by Simon Peyton Jones at 2026-10-16T17:11:24+01:00
Wibble
- - - - -
9d8ef33f by Simon Peyton Jones at 2026-10-16T17:11:24+01:00
Wibbles and documentation
- - - - -
2fe5734e by Simon Peyton Jones at 2026-10-16T17:11:24+01:00
Try another way
let's see what CI says
- - - - -
3aab8640 by Simon Peyton Jones at 2026-10-16T17:11:24+01:00
Fix join points
Split contininuations *first*
- - - - -
574b3e56 by Simon Peyton Jones at 2026-10-16T17:11:24+01:00
Deal with runRW# too
ToDo: document this
- - - - -
883a949d by Simon Peyton Jones at 2026-10-16T17:11:24+01:00
Wibbles
- - - - -
025075dd by Simon Peyton Jones at 2026-10-16T17:11:24+01:00
Eliminate accidental pprTrace
- - - - -
343fc71a by Simon Peyton Jones at 2026-10-16T17:11:24+01:00
Fix perf hole in exprIsConApp_maybe
in subst_bndr. ToDo: document
- - - - -
e7972340 by Simon Peyton Jones at 2026-10-16T17:11:24+01:00
Fix in-scope set violation
- - - - -
e0aef7c6 by Simon Peyton Jones at 2026-10-16T17:11:24+01:00
Attempt to deal with the perf issue in T18223 [skip ci]
see `rebuildWithFloats`
- - - - -
44d0fa5d by Simon Peyton Jones at 2026-10-16T17:11:24+01:00
Work in progress on modifying the Simplifier's FloatBinds
...in collaboration with Claude
- - - - -
76031f6e by Simon Peyton Jones at 2026-10-16T17:11:24+01:00
More work in progress
...with Claude
Very nice refactor.
The hack does about what we hoped. Changes are relative to the original branch (casts always in inner), and only tests that moved by more than 0.5% are listed:
┌──────────────────┬───────────────────────┬───────────────────────────────────────────────────────────────────┐
│ Test │ Casts always in outer │ Hack (cast only into a single-alternative case or a non-join let) │
├──────────────────┼───────────────────────┼───────────────────────────────────────────────────────────────────┤
│ CoOpt_Read │ +6.9% │ +5.6% (still a regression) │
├──────────────────┼───────────────────────┼───────────────────────────────────────────────────────────────────┤
│ CoOpt_Singletons │ +6.1% │ 0.0% (fully recovered) │
├──────────────────┼───────────────────────┼───────────────────────────────────────────────────────────────────┤
│ T13253 │ +3.7% │ +0.1% (recovered) │
├──────────────────┼───────────────────────┼───────────────────────────────────────────────────────────────────┤
│ T13056 │ +1.1% │ +1.1% │
├──────────────────┼───────────────────────┼───────────────────────────────────────────────────────────────────┤
│ T5642 │ −1.9% │ −1.9% (fix kept) │
├──────────────────┼───────────────────────┼───────────────────────────────────────────────────────────────────┤
│ T16577 │ −1.5% │ −1.5% │
├──────────────────┼───────────────────────┼───────────────────────────────────────────────────────────────────┤
│ T21839c │ −1.0% │ −1.0% │
├──────────────────┼───────────────────────┼───────────────────────────────────────────────────────────────────┤
│ T19695 │ +0.8% │ −0.1% │
└──────────────────┴───────────────────────┴───────────────────────────────────────────────────────────────────┘
The other 56 tests are within 0.5%.
Relative to master, CoOpt_Read is still about 3% better (it was 9% better with casts always pushed inside). CoOpt_Read is the only real loss left. It presumably gains from pushing a cast into a multi-alternative case, or into a join point, which the hack now forbids.
The Core Lint bug. My reading is that it's caused by the hack, not latent: a cast pushed into a join point's RHS but not into a multi-alternative case in its body leaves a jump under a cast. The mightBeJoinBind test (no casts into a join-point let) fixes it, and the current tree builds cleanly with it. /tmp/tjoin/JoinCast.hs is a candidate reproducer of that shape: MkN (let j z = ... in case x of {0 -> j 1; 1 -> j 2; _ -> 3}). It passes Lint on master and on the current branch. I haven't yet seen it fail, because that needs the buggy state rebuilt, which means editing Iteration.hs. I'll do that only after your push, if you want it.
State you're committing:
- FloatBinds work, with addFloatBinds.
- Your getFF and Note [LetFloats] changes, plus my comment fixes and the let-can-float and soft-scope assertions.
- Soft-scoped ticks floated as FloatTicks.
- The push_casts flag, with mightBeJoinBind.
- Accepted outputs for T20510 and show-bytecode-hpc.
- Tests:
- The full testsuite was run before the push_casts change; the only unexpected failures were environmental ones and those two outputs, now accepted.
- The push_casts version has only been built, and measured with the perf harness. simplCore and the full testsuite haven't been rerun on it.
- - - - -
d10a0fc8 by Simon Peyton Jones at 2026-10-16T17:11:24+01:00
Undo the push_casts experiment in splitContArgs
Go back to always putting casts in the `inner` continuation when
case-of-case is off. The push_casts flag (and mightBeJoinBind) fixed
the coercion duplication in T5642, but cost CoOpt_Read, and needed a
delicate side condition for join points.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
dbf34eb1 by Simon Peyton Jones at 2026-10-16T17:11:44+01:00
Add a small regression test
- - - - -
e8ec242c by Simon Peyton Jones at 2026-10-16T17:11:44+01:00
Simplifier: tidy up case-floats, casts and float handling (#27737)
Casts
* splitContArgs: push a cast into `inner` only when it is followed by an
application (isAppCont). A cast suffix stays outside, so it is not
duplicated into every alternative of a multi-way case, and cast
worker/wrapper can still fire. Fixes the quadratic coercion blow-up
in T5642, T16577 (derived Generic `from`).
Note [Do not push a cast inwards unnecessarily]; invariant on CastIt.
Case-floats and single-alternative cases
* Restructure reallyRebuildCase: do prepareCase first, then split into
rebuildSingleAltCase (no mkDupableCont; returns a case-float) and
rebuildMultiAltCase. simplAlt now returns (AltCon, [OutVar], floats, rhs).
* rebuildSingleAltCase no longer calls mkCase (removing the buggy (FSC1)
fast path). Instead new simplWrapFloats wraps floats using mkCase for
each case-float, so case-merging, identity-case elimination etc still
happen. It replaces Env.wrapFloats at all Simplifier call sites.
Note [Wrapping case-floats with mkCase].
* Invariant (FFC1): a DEFAULT case-float never has a scrutinee for which
doCaseToLet holds (it should be a let-float). doCaseToLet moves to
Simplify.Env; asserted by okCaseFloat. rebuildSingleAltCase makes a
let-float when prepareAlts has pruned a case to a single DEFAULT.
Note [Case-floats], Note [Tick-floats].
* contIsDupable: treat a Select with "unpacking alternatives"
(case x of K a b -> b, possibly nested) as dupable, so CPR
unboxing cancels with the boxing instead of making a join point.
Fixes the extra Simplifier iteration in T15304.
Note [Duplicating unpacking continuations].
Float representation
* Flatten LetFloats into SimplFloats: sfLetFloats :: FloatBinds; no
per-group FloatFlag field. New `type LetFloats = OrdList OutBind`
(let-bindings only, satisfying let-can-float). New addLetFloat,
addCaseFloat, addLetFloats, mkLetSimplFloats; getFF_Case/getFF_Tick gone.
Note [LetFloats].
* prepareBinding floats only lazy or ok-for-spec let-bindings
(onlyLazyLetFloats, one pass); returns (LetFloats, InScopeSet, rhs).
No more strict_bind argument. abstractFloats takes LetFloats, so a
case-float can never reach it (was a panic: T27737a).
Note [prepareBinding], including the lost addIntC# opportunity (PB4).
* prepareRhs/makeTrivial return LetFloats; makeTrivial declines to bind
an unlifted, not-ok-for-spec expression (bindingOk).
Note [Cannot trivialise] (CT1).
Performance details
* mkSingleAltCase: skip occCheckExpand when no binder is a TyCoVar.
* Force a Case's type only when emitting it: mkCase3 renamed returnCase,
which does the seqType; callers don't. Update
Note [Avoiding space leaks in OutType].
* Record the (rejected) idea of floating a prefix of the floats:
Note [Floating a prefix of the floats].
Notes
* Note [LetFloats]: why we have FloatCase (LF1, LF2).
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
15 changed files:
- compiler/GHC/Core.hs
- compiler/GHC/Core/Opt/Simplify/Env.hs
- compiler/GHC/Core/Opt/Simplify/Iteration.hs
- compiler/GHC/Core/Opt/Simplify/Utils.hs
- compiler/GHC/Core/SimpleOpt.hs
- compiler/GHC/Core/Type.hs
- compiler/GHC/Core/Utils.hs
- compiler/GHC/Driver/Config/Core/Opt/Simplify.hs
- testsuite/tests/dmdanal/should_compile/T20510.stderr
- testsuite/tests/show-bytecode/show-bytecode-hpc.stdout
- testsuite/tests/simplCore/should_compile/T26903.stderr
- + testsuite/tests/simplCore/should_compile/T27737a.hs
- + testsuite/tests/simplCore/should_compile/T27910.hs
- + testsuite/tests/simplCore/should_compile/T27910.stderr
- testsuite/tests/simplCore/should_compile/all.T
Changes:
=====================================
compiler/GHC/Core.hs
=====================================
@@ -490,7 +490,7 @@ This is a well-kinded type, in an environment-based scheme. But `typeKind`
will panic, because the kind of the body of a forall must not mention
the forall'd variable (and the inner forall's body appears to do so).
-It might be possible to make `exprType` and `typeKind`` more complicated, so that
+It might be possible to make `exprType` and `typeKind` more complicated, so that
they do renaming on the fly. But instead we impose
INVARIANT (NoTypeShadowing):
@@ -1720,10 +1720,19 @@ isEmptyFloatBinds = isNilOL
data FloatBind
= FloatLet CoreBind
+ -- let(rec) x = e
+ -- Invariant: satisfies the let-can-float invariant
+
| FloatCase CoreExpr CoreBndr AltCon [CoreBndr]
-- case e of y { C ys -> ... }
-- See Note [Floating single-alternative cases] in GHC.Core.Opt.SetLevels
+
| FloatTick CoreTickish
+ -- tick<t> ...
+ -- Invariant: the tick is always soft-scoped (tickishHasSoftScope holds)
+ -- Why? We are floating these FloatBinds outwards, bringing more code under
+ -- the bindigns; that is only OK for soft-scoped ticks.
+ -- See Note [Scoping ticks and counting ticks] in GHC.Types.Tickish
floatsBinders :: FloatBinds -> [Var]
floatsBinders fs = foldr ((++) . floatBinders) [] fs
=====================================
compiler/GHC/Core/Opt/Simplify/Env.hs
=====================================
@@ -38,14 +38,13 @@ module GHC.Core.Opt.Simplify.Env (
-- * Floats
SimplFloats(..), emptyFloats, isEmptyFloats, mkRecFloats,
- mkFloatBind, addLetFloats, addJoinFloats, addFloats,
- extendFloats, wrapFloats,
- isEmptyJoinFloats, isEmptyLetFloats,
- doFloatFromRhs, getTopFloatBinds,
+ mkFloatBind, addLetFloat, addLetFloats, addCaseFloat, mkLetSimplFloats,
+ addJoinFloats, addFloats, addFloatBindsF,
+ extendFloats, isEmptyJoinFloats,
+ doFloatFromRhs, getTopFloatBinds, onlyLazyLetFloats, doCaseToLet,
-- * LetFloats
- LetFloats, FloatEnable(..), letFloatBinds, emptyLetFloats, unitLetFloat,
- addLetFlts, mapLetFloats,
+ LetFloats, FloatEnable(..), emptyLetFloats, mapLetFloats,
-- * JoinFloats
JoinFloat, JoinFloats, emptyJoinFloats,
@@ -65,7 +64,7 @@ import GHC.Core.Subst( substExprSC )
import GHC.Core.Unfold
import GHC.Core.TyCo.Subst (emptyIdSubstEnv, mkSubst)
import GHC.Core.Multiplicity( Scaled(..), mkMultMul )
-import GHC.Core.Make ( mkWildValBinder, mkCoreLet )
+import GHC.Core.Make ( mkWildValBinder )
import GHC.Core.Type hiding ( substTy, substTyVar, substTyVarBndr, substCo
, extendTvSubst, extendCvSubst )
import qualified GHC.Core.Coercion as Coercion
@@ -78,6 +77,7 @@ import GHC.Types.Var.Set
import GHC.Types.Id as Id
import GHC.Types.InlinePragma ( ActivationGhc, CompilerPhase, isActiveInPhase )
import GHC.Types.Basic
+import GHC.Types.Tickish ( tickishHasSoftScope )
import GHC.Types.Unique.FM ( pprUniqFM )
import GHC.Data.OrdList
@@ -418,9 +418,10 @@ see GHC.Core.Opt.FloatOut.
data SimplFloats
= SimplFloats
- { -- Ordinary let bindings
- sfLetFloats :: LetFloats
+ { -- Ordinary let bindings, case-floats and tick-floats
+ sfLetFloats :: FloatBinds
-- See Note [LetFloats]
+ -- Invariant: every FloatLet satisfies the let-can-float invariant
-- Join points
, sfJoinFloats :: JoinFloats
@@ -438,19 +439,19 @@ data SimplFloats
instance Outputable SimplFloats where
ppr (SimplFloats { sfLetFloats = lf, sfJoinFloats = jf, sfInScope = is })
= text "SimplFloats"
- <+> braces (vcat [ text "lets: " <+> ppr lf
+ <+> braces (vcat [ text "lets: " <+> ppr (fromOL lf)
, text "joins:" <+> ppr jf
, text "in_scope:" <+> ppr is ])
emptyFloats :: SimplEnvIS -> SimplFloats
emptyFloats env
- = SimplFloats { sfLetFloats = emptyLetFloats
+ = SimplFloats { sfLetFloats = nilOL
, sfJoinFloats = emptyJoinFloats
, sfInScope = seInScope env }
isEmptyFloats :: SimplFloats -> Bool
-- Precondition: used only when sfJoinFloats is empty
-isEmptyFloats (SimplFloats { sfLetFloats = LetFloats fs _
+isEmptyFloats (SimplFloats { sfLetFloats = fs
, sfJoinFloats = js })
= assertPpr (isNilOL js) (ppr js ) $
isNilOL fs
@@ -744,26 +745,159 @@ setSubstEnv env tvs cvs ids = env { seTvSubst = tvs, seCvSubst = cvs, seIdSubst
Note [LetFloats]
~~~~~~~~~~~~~~~~
-The LetFloats is a bunch of bindings, classified by a FloatFlag.
-
-The `FloatFlag` contains summary information about the bindings, see the data
-type declaration of `FloatFlag`
-
+The `sfLetFloats` field of SimplFloats is a bunch of FloatBinds. A FloatBind
+can take one of three forms: FloatLet, FloatCase, and FloatTick; see
+Note [Case-floats] and Note [Tick-floats].
+
+In contrast, the type `LetFloats` (= OrdList OutBind) has let-bindings only.
+It is what prepareBinding, prepareRhs and makeTrivial return: they never
+produce case-floats or tick-floats. See Note [prepareBinding] in
+GHC.Core.Opt.Simplify.Iteration.
+
+When prepareBinding decides whether to float some let-bindings out of a RHS,
+doFloatFromRhs classifies them with a FloatFlag; see the data type declaration
+of `FloatFlag`, and Note [FloatFlag for FloatLet]. Case-floats and tick-floats
+have no FloatFlag, because prepareBinding never floats them out of a RHS.
+
+Why do we have FloatCase at all, rather than just let-bindings?
+
+(LF1) exprIsConApp_maybe looks through single-alternative cases (and lets
+ and ticks) and returns what it looked through as a [FloatBind]. The
+ case-of-known-constructor code wants to add these straight to the
+ Simplifier's floats, so the floats must be able to hold a case.
+
+(LF2) A single-alternative case is returned as a FloatCase by
+ rebuildSingleAltCase rather than as an expression, so that the lets in
+ its alternative are not trapped inside it. Example, with case-of-case
+ switched off (e.g. in the Gentle phase):
+ case (case f x s of (# s1, a #) ->
+ let b = g a in
+ let c = h b in
+ (# s1, c #))
+ of (# s2, r #) -> body
+ We simplify the inner case with an empty continuation (see
+ splitContForNoCaseCase), and get back
+ floats: [case f x s of (# s1, a #), b = g a, c = h b]
+ result: (# s1, c #)
+ Now rebuildWithFloats can do case-of-known-constructor on the result
+ directly, giving
+ case f x s of (# s1, a #) ->
+ let b = g a in
+ let c = h b in
+ body[s1/s2, c/r]
+ If instead the inner case came back as a single expression, then
+ exprIsConApp_maybe would have to walk down through the case and all the
+ lets to find the (# s1, c #). With a long chain of such nested binds
+ (e.g. state-passing code, as in T18223) the scrutinee at each level
+ contains all the lets from the levels inside it, so the repeated walks
+ are quadratic (#27737).
+ See Note [Floating single-alternative cases] in GHC.Core.Opt.Simplify.Iteration.
+
+Note [FloatFlag for FloatLet] -- see `getFF_Let`
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Examples
- NonRec x (y:ys) FltLifted
- Rec [(x,rhs)] FltLifted
-
- NonRec x* (p:q) FltOKSpec -- RHS is WHNF. Question: why not FltLifted?
- NonRec x# (y +# 3) FltOkSpec -- Unboxed, but ok-for-spec'n
-
- NonRec x* (f y) FltCareful -- Strict binding; might fail or diverge
- NonRec x# (a /# b) FltCareful -- Might fail; does not satisfy let-can-float invariant
- NonRec x# (f y) FltCareful -- Might diverge; does not satisfy let-can-float invariant
+ NonRec x (y:ys) FltLifted
+ Rec [(x,rhs)] FltLifted
+
+ NonRec x* (p:q) FltOKSpec -- RHS is WHNF. Question: why not FltLifted?
+ NonRec x# (y +# 3) FltOkSpec -- Unboxed, but ok-for-spec'n
+
+ NonRec x* (f y) FltCareful -- Strict binding; might fail or diverge
+ NonRec x# (a /# b) FltCareful -- Might fail; does not satisfy let-can-float invariant
+ NonRec x# (f y) FltCareful -- Might diverge; does not satisfy let-can-float invariant
+
+ NonRec s "foo"# FltLifted -- Literal string can go to top level
+
+* (FFL1) Note that a FloatLet can still be FltCareful: the first FltCareful example
+ above, NonRec x* (f y), where x* is lifted but has a strict demand
+ (isStrUsedDmd). That is a perfectly valid (lazy) let-binding, but its demand
+ info is valid only where it is. If we floated it out of the RHS of a lazy
+ binding
+ let v = let x* = f y in x*+1 in body
+ ==> let x* = f y; v = x*+1 in body
+ then x's demand info would be a lie, and CorePrep, which case-binds a let
+ whose binder has a strict demand, would evaluate (f y) eagerly. Hence
+ FltCareful. prepareBinding never floats a FltCareful binding out of a RHS,
+ even the RHS of a strict binding; see onlyLazyLetFloats.
+
+* (FFL2) A literal-string binding is marked FltLifted (a bit of a mis-nomer
+ because it's not a lifted type) because it can go to top level.
+ See Note [Core top-level string literals] in GHC.Core.
+
+* A binding that does not satisfy the let-can-float invariant (the last two
+ examples above) is represented by a FloatCase, not a FloatLet:
+ FloatCase (a /# b) x# DEFAULT []
+ That is done once and for all by `addLetFloat`, so a FloatLet in sfLetFloats
+ is always a valid let-binding, and `simplWrapFloats` does not need to check.
+ Such bindings used to arise from `makeTrivial`, because an argument need not
+ satisfy the let-can-float invariant; but now makeTrivial declines to bind such
+ an argument (see Note [Cannot trivialise] in GHC.Core.Opt.Simplify.Iteration).
+ They can also arise because
+ exprOkForSpeculation is conservative: e.g. it says False for (# s, x #)
+ where x is lifted, because it checks the arguments against the
+ (representation-polymorphic) type of the unboxed-tuple worker.
+
+Note [Case-floats]
+~~~~~~~~~~~~~~~~~~
+As well as let-bindings, sfLetFloats can contain single-alternative case
+floats (FloatCase), for example
+ case e of b { (# a, c #) -> <hole> }
+A case-float never floats out of the RHS of a let-binding: prepareBinding
+floats only let-bindings. See Note [prepareBinding] in
+GHC.Core.Opt.Simplify.Iteration, which also describes an opportunity that
+we lose as a result.
+
+(FFC1) Invariant: a DEFAULT FloatCase never has a scrutinee for which doCaseToLet
+ holds. Such a case-float
+ FloatCase e b DEFAULT [] -- where doCaseToLet e b
+ should instead be the let-float (b = e), which satisfies the let-can-float
+ invariant. It would not actually be /wrong/ to use the FloatCase, just less
+ good: a let-float can be inlined, and can float out of the RHS of a let-binding
+ (see Note [prepareBinding]).
+
+ doCaseToLet is the same test that rebuildCase uses to turn a case into a let:
+ roughly, the scrutinee is ok-for-speculation (if unlifted) or a HNF (if lifted).
+ But it says No if `b` is a coercion variable, because a coercion variable can
+ be let-bound only to a Coercion (Note [Core type and coercion invariant] in
+ GHC.Core); so FloatCase (eq_sel @k @t1 @t2 d) co DEFAULT [] is fine.
+
+ We maintain the invariant thus:
+ * addLetFloat makes a FloatCase only for a binding that needsCaseBinding,
+ i.e. an unlifted one whose RHS is not ok-for-speculation.
+ * rebuildCase turns case e of b { DEFAULT -> body } into a let when
+ doCaseToLet holds.
+ * But rebuildCase looks at the alternatives before prepareAlts prunes away
+ impossible ones; e.g. case x# of b { 1# -> e1; DEFAULT -> e2 } may be
+ pruned to a single DEFAULT alternative. So rebuildSingleAltCase makes a
+ let-float, rather than a case-float, for a DEFAULT alternative when
+ doCaseToLet holds.
+ * exprIsConApp_maybe makes DEFAULT case-floats (in GHC.Core.SimpleOpt) only
+ for an unlifted argument that needsCaseBinding, or for a strict field
+ whose argument is not a HNF (mkFieldSeqFloats).
+ We check the invariant, with `okCaseFloat`, in addCaseFloat and addFloatBindsF.
+
+ This invariant is only about DEFAULT case-floats. A case-float with pattern
+ binders, such as case addIntC# x y of (# r, c #) -> <hole>, cannot be a
+ let-float even when its scrutinee is ok-for-speculation.
+
+Note [Tick-floats]
+~~~~~~~~~~~~~~~~~~
+sfLetFloats can contain a FloatTick for soft-scoped ticks (only -- see the
+invariant on FloatTick in GHC.Core); see simplTick.
+
+Like a case-float, a tick-float never floats out of the RHS of a let-binding,
+because prepareBinding floats only let-bindings. For a /counting/ tick (e.g.
+an HPC tick) that is essential: floating it out of a lazy RHS would change when
+(and how often) it is counted, namely when the let is executed rather than when
+the binder is evaluated. For a /non-counting/ tick (e.g. a source note) it
+would be fine, but we don't bother.
-}
-data LetFloats = LetFloats (OrdList OutBind) FloatFlag
- -- See Note [LetFloats]
+type LetFloats = OrdList OutBind
+ -- Let-bindings only: no case-floats or tick-floats
+ -- Invariant: every binding satisfies the let-can-float invariant
+ -- See Note [LetFloats]
type JoinFloat = OutBind
type JoinFloats = OrdList JoinFloat
@@ -780,17 +914,14 @@ data FloatFlag
-- *and* ok-for-speculation
-- Hence ok to float out of the RHS
-- of a lazy non-recursive let binding
- -- (but not to top level, or into a rec group)
+ -- (but /not/ to top level, or into a rec group)
-- NB: consequence: all bindings satisfy let-can-float invariant
| FltCareful -- At least one binding is strict (or unlifted)
-- and not guaranteed cheap
- -- Do not float these bindings out of a lazy let!
+ -- Never float these bindings out of a RHS
-- NB: some bindings may not satisfy let-can-float
-instance Outputable LetFloats where
- ppr (LetFloats binds ff) = ppr ff $$ ppr (fromOL binds)
-
instance Outputable FloatFlag where
ppr FltLifted = text "FltLifted"
ppr FltOkSpec = text "FltOkSpec"
@@ -803,9 +934,13 @@ andFF FltOkSpec _ = FltOkSpec
andFF FltLifted flt = flt
-doFloatFromRhs :: FloatEnable -> TopLevelFlag -> RecFlag -> Bool -> SimplFloats -> OutExpr -> Bool
+doFloatFromRhs :: FloatEnable -> TopLevelFlag -> RecFlag
+ -> LetFloats -> FloatFlag -- The let-bindings and their FloatFlag,
+ -- from onlyLazyLetFloats
+ -> OutExpr -> Bool
-- If you change this function look also at FloatIn.noFloatIntoRhs
-doFloatFromRhs fe lvl rec strict_bind (SimplFloats { sfLetFloats = LetFloats fs ff }) rhs
+-- See Note [Floating a prefix of the floats] for a possible improvement
+doFloatFromRhs fe lvl rec fs ff rhs
= floatEnabled lvl fe
&& not (isNilOL fs)
&& want_to_float
@@ -817,7 +952,7 @@ doFloatFromRhs fe lvl rec strict_bind (SimplFloats { sfLetFloats = LetFloats fs
can_float = case ff of
FltLifted -> True
FltOkSpec -> isNotTopLevel lvl && isNonRec rec
- FltCareful -> isNotTopLevel lvl && isNonRec rec && strict_bind
+ FltCareful -> False -- onlyLazyLetFloats never returns FltCareful
-- Whether any floating is allowed by flags.
floatEnabled :: TopLevelFlag -> FloatEnable -> Bool
@@ -825,6 +960,38 @@ doFloatFromRhs fe lvl rec strict_bind (SimplFloats { sfLetFloats = LetFloats fs
floatEnabled lvl FloatNestedOnly = not (isTopLevel lvl)
floatEnabled _ FloatEnabled = True
+{- Note [Floating a prefix of the floats]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+prepareBinding floats all of the floats from a RHS, or none of them. It floats
+none if any of them is a case-float or tick-float (see Note [prepareBinding] in
+GHC.Core.Opt.Simplify.Iteration), or if doFloatFromRhs says no; and doFloatFromRhs
+gives a single FloatFlag to the whole group. Consider (T5321FD)
+ x = let v1 = \ds -> ... in
+ ...
+ let v200 = \ds -> ... in
+ case sampleData of (a :* b) -> ...
+where the single-alternative case has become a FloatCase; see
+Note [Floating single-alternative cases] in GHC.Core.Opt.Simplify.Iteration.
+Because of the FloatCase, none of these floats go to top level, even though the
+lets in front of the case are all FltLifted.
+
+Opportunity: when the group cannot float as a whole, float the longest prefix
+of let-bindings that can, and wrap the rest back around the RHS. Taking a
+prefix is always fine, because later floats may mention the binders of earlier
+ones, but not vice versa. To keep the common path cheap, do the linear
+traversal only when the group cannot float as a whole.
+
+We tried this (#27737). It did restore the top-level floating in T5321FD, but
+made little difference to compile time, so we did not keep it. If you try it
+again, beware: the sfInScope of the floats describes the scope /inside/ all of
+them, which is wrong for the prefix alone. In T5321FD, inside the trapped
+ case sampleData of (x :* xs) -> ...
+binder-swap gives sampleData the unfolding (x :* xs); keeping that sfInScope
+let the refined sampleData escape to top level, taking x and xs with it. The
+fix is to rebuild sfInScope from the in-scope set outside the RHS, extended
+with the binders of the prefix.
+-}
+
{- Note [Float when expandable]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We float when that would leave us with a RHS that is /expandable/ (#26854).
@@ -851,10 +1018,7 @@ End of historial aside
-}
emptyLetFloats :: LetFloats
-emptyLetFloats = LetFloats nilOL FltLifted
-
-isEmptyLetFloats :: LetFloats -> Bool
-isEmptyLetFloats (LetFloats fs _) = isNilOL fs
+emptyLetFloats = nilOL
emptyJoinFloats :: JoinFloats
emptyJoinFloats = nilOL
@@ -862,19 +1026,83 @@ emptyJoinFloats = nilOL
isEmptyJoinFloats :: JoinFloats -> Bool
isEmptyJoinFloats = isNilOL
-unitLetFloat :: OutBind -> LetFloats
--- This key function constructs a singleton float with the right form
-unitLetFloat bind = assert (all (not . isJoinId) (bindersOf bind)) $
- LetFloats (unitOL bind) (flag bind)
+getFF_Let :: CoreBind -> FloatFlag
+-- See Note [FloatFlag for FloatLet]
+getFF_Let (Rec {}) = FltLifted
+getFF_Let (NonRec bndr rhs)
+ | not (isStrictId bndr) = FltLifted -- Lazy lifted let
+ | exprIsTickedString rhs = FltLifted -- See (FFL2)
+ | exprOkForSpeculation rhs = FltOkSpec -- Unlifted, or strict lifted, and ok-for-spec (e.g. HNF)
+ | otherwise = FltCareful -- See (FFL1) Strict, e.g. let x* = factorial y
+
+addLetFloat :: SimplFloats -> OutBind -> SimplFloats
+-- Add a non-join binding to the let-floats, and extend the in-scope set.
+-- If the binding does not satisfy the let-can-float invariant, it
+-- makes a FloatCase. See Note [LetFloats]
+addLetFloat floats bind
+ | NonRec bndr rhs <- bind
+ , needsCaseBinding (idType bndr) rhs
+ = -- This should never happen, but currently does because of #27910
+ add_float floats (FloatCase rhs bndr DEFAULT [])
+
+ | otherwise
+ = assert (all (not . isJoinId) (bindersOf bind)) $
+ add_float floats (FloatLet bind)
+
+addCaseFloat :: SimplFloats -> OutExpr -> OutId -> AltCon -> [OutVar] -> SimplFloats
+-- Add a single-alternative case float
+-- case scrut of bndr { con bndrs -> <hole> }
+-- and extend the in-scope set. See Note [LetFloats]
+addCaseFloat floats scrut bndr con bndrs
+ = assertPpr (okCaseFloat flt) (ppr flt) $
+ add_float floats flt
where
- flag (Rec {}) = FltLifted
- flag (NonRec bndr rhs)
- | not (isStrictId bndr) = FltLifted
- | exprIsTickedString rhs = FltLifted
- -- String literals can be floated freely.
- -- See Note [Core top-level string literals] in GHC.Core.
- | exprOkForSpeculation rhs = FltOkSpec -- Unlifted, and lifted but ok-for-spec (eg HNF)
- | otherwise = FltCareful
+ flt = FloatCase scrut bndr con bndrs
+
+add_float :: SimplFloats -> FloatBind -> SimplFloats
+-- Add the float /inside/ the existing let-floats
+add_float floats@(SimplFloats { sfLetFloats = fs, sfInScope = in_scope }) flt
+ = floats { sfLetFloats = fs `snocOL` flt
+ , sfInScope = in_scope `extendInScopeFromFB` unitOL flt }
+
+okLetFloat :: OutBind -> Bool
+-- Checks the let-can-float invariant; used only in assertions
+okLetFloat (NonRec b r)
+ | isId b, not (isCoVar b) = not (needsCaseBinding (idType b) r)
+okLetFloat _ = True
+
+okCaseFloat :: FloatBind -> Bool
+-- Checks invariant (FFC1) in Note [Case-floats]
+-- Used only in assertions
+okCaseFloat (FloatCase scrut b DEFAULT _) = not (doCaseToLet scrut b)
+okCaseFloat _ = True
+
+doCaseToLet :: OutExpr -- Scrutinee
+ -> Id -- Case binder; can be InId or OutId
+ -> Bool
+-- The situation is case scrut of b { DEFAULT -> body }
+-- Can we transform thus? let { b = scrut } in body
+-- See also (FFC1) in Note [Case-floats]
+doCaseToLet scrut case_bndr
+ | isTyCoVar case_bndr -- Respect GHC.Core
+ = isTyCoArg scrut -- Note [Core type and coercion invariant]
+
+ | isUnliftedType (exprType scrut)
+ -- We can call isUnliftedType here: scrutinees always have a fixed RuntimeRep (see FRRCase).
+ -- Note however that we must check 'scrut' (which is an 'OutExpr') and not 'case_bndr'
+ -- (which may be an 'InId'): see Note [Dark corner with representation polymorphism]
+ -- in GHC.Core.Opt.Simplify.Iteration.
+ -- Using `exprType` is typically cheap because `scrut` is typically a variable.
+ -- We could instead use mightBeUnliftedType (idType case_bndr), but that hurts
+ -- the brain more. Consider that if this test ever turns out to be a perf
+ -- problem (which seems unlikely).
+ = exprOkForSpeculation scrut
+
+ | otherwise -- Scrut has a lifted type
+ = exprIsHNF scrut
+ -- || isStrUsedDmd (idDemandInfo case_bndr)
+ -- We no longer look at the demand on the case binder
+ -- See Note [Case-to-let for strictly-used binders] in GHC.Core.Opt.Simplify.Iteration
unitJoinFloat :: OutBind -> JoinFloats
unitJoinFloat bind = assert (all isJoinId (bindersOf bind)) $
@@ -886,50 +1114,65 @@ mkFloatBind :: SimplEnv -> OutBind -> (SimplFloats, SimplEnv)
-- These binders may already be in the in-scope set,
-- but may have by now been augmented with more IdInfo
mkFloatBind env bind
- = (floats, env { seInScope = in_scope' })
+ = (floats, env { seInScope = sfInScope floats })
where
- floats
- | isJoinBind bind
- = SimplFloats { sfLetFloats = emptyLetFloats
- , sfJoinFloats = unitJoinFloat bind
- , sfInScope = in_scope' }
- | otherwise
- = SimplFloats { sfLetFloats = unitLetFloat bind
- , sfJoinFloats = emptyJoinFloats
- , sfInScope = in_scope' }
-- See Note [Bangs in the Simplifier]
- !in_scope' = seInScope env `extendInScopeSetBind` bind
+ !floats = emptyFloats env `extendFloats` bind
extendFloats :: SimplFloats -> OutBind -> SimplFloats
--- Add this binding to the floats, and extend the in-scope env too
-extendFloats (SimplFloats { sfLetFloats = floats
- , sfJoinFloats = jfloats
- , sfInScope = in_scope })
- bind
+-- Add this binding (join point or not) to the floats,
+-- and extend the in-scope env too
+extendFloats floats@(SimplFloats { sfJoinFloats = jfloats, sfInScope = in_scope }) bind
| isJoinBind bind
- = SimplFloats { sfInScope = in_scope'
- , sfLetFloats = floats
- , sfJoinFloats = jfloats' }
+ = floats { sfJoinFloats = jfloats `addJoinFlts` unitJoinFloat bind
+ , sfInScope = in_scope `extendInScopeSetBind` bind }
| otherwise
- = SimplFloats { sfInScope = in_scope'
- , sfLetFloats = floats'
- , sfJoinFloats = jfloats }
- where
- in_scope' = in_scope `extendInScopeSetBind` bind
- floats' = floats `addLetFlts` unitLetFloat bind
- jfloats' = jfloats `addJoinFlts` unitJoinFloat bind
+ = floats `addLetFloat` bind
-addLetFloats :: SimplFloats -> LetFloats -> SimplFloats
--- Add the let-floats for env2 to env1;
--- *plus* the in-scope set for env2, which is bigger
--- than that for env1
-addLetFloats floats let_floats
- = floats { sfLetFloats = sfLetFloats floats `addLetFlts` let_floats
- , sfInScope = sfInScope floats `extendInScopeFromLF` let_floats }
+mkLetSimplFloats :: InScopeSet -> LetFloats -> SimplFloats
+-- Make SimplFloats from some let-bindings.
+-- Precondition: the InScopeSet already includes the binders of the let-bindings
+mkLetSimplFloats in_scope binds
+ = SimplFloats { sfLetFloats = fmap FloatLet binds
+ , sfJoinFloats = emptyJoinFloats
+ , sfInScope = in_scope }
-extendInScopeFromLF :: InScopeSet -> LetFloats -> InScopeSet
-extendInScopeFromLF in_scope (LetFloats binds _)
- = foldlOL extendInScopeSetBind in_scope binds
+addLetFloats :: SimplFloats -> LetFloats -> SimplFloats
+-- Add the let-bindings /inside/ the existing floats,
+-- and extend the in-scope set
+-- No need for addLetFloat's needsCaseBinding test: LetFloats satisfy the
+-- let-can-float invariant (see the declaration of LetFloats)
+addLetFloats floats binds = foldlOL add floats binds
+ where
+ add fs bind = assertPpr (okLetFloat bind) (ppr bind) $
+ add_float fs (FloatLet bind)
+
+addFloatBindsF :: FloatBinds -> SimplFloats -> SimplFloats
+-- (addFloatBindsF new_fbs floats) adds `new_fbs` /outside/ `floats`;
+-- i.e. `new_fbs` scope over `floats`
+-- Precondition: every FloatLet in `new_fbs` satisfies the let-can-float
+-- invariant (see the FloatBind declaration in GHC.Core), so we can add
+-- them directly; see Note [LetFloats]
+addFloatBindsF new_fbs floats@(SimplFloats { sfLetFloats = lf_fbs, sfInScope = in_scope })
+ | isNilOL new_fbs
+ = floats
+ | otherwise
+ = assertPpr (all ok_float new_fbs) (ppr new_fbs) $
+ floats { sfLetFloats = new_fbs `appOL` lf_fbs
+ , sfInScope = in_scope `extendInScopeFromFB` new_fbs }
+ where
+ -- Check the invariants on FloatBind; see its declaration in GHC.Core
+ ok_float (FloatLet bind) = okLetFloat bind
+ ok_float (FloatTick t) = tickishHasSoftScope t
+ ok_float flt@(FloatCase {}) = okCaseFloat flt
+
+extendInScopeFromFB :: InScopeSet -> FloatBinds -> InScopeSet
+extendInScopeFromFB in_scope binds
+ = foldlOL extend in_scope binds
+ where
+ extend in_scope (FloatLet bind) = in_scope `extendInScopeSetBind` bind
+ extend in_scope (FloatCase _ b _ bs) = in_scope `extendInScopeSetList` (b:bs)
+ extend in_scope (FloatTick {}) = in_scope
addJoinFloats :: SimplFloats -> JoinFloats -> SimplFloats
addJoinFloats floats join_floats
@@ -943,16 +1186,46 @@ addFloats :: SimplFloats -> SimplFloats -> SimplFloats
-- than that for env1
addFloats (SimplFloats { sfLetFloats = lf1, sfJoinFloats = jf1 })
(SimplFloats { sfLetFloats = lf2, sfJoinFloats = jf2, sfInScope = in_scope })
- = SimplFloats { sfLetFloats = lf1 `addLetFlts` lf2
+ = SimplFloats { sfLetFloats = lf1 `appOL` lf2
, sfJoinFloats = jf1 `addJoinFlts` jf2
, sfInScope = in_scope }
-addLetFlts :: LetFloats -> LetFloats -> LetFloats
-addLetFlts (LetFloats bs1 l1) (LetFloats bs2 l2)
- = LetFloats (bs1 `appOL` bs2) (l1 `andFF` l2)
+onlyLazyLetFloats :: SimplFloats -> LetFloats -> Maybe (LetFloats, FloatFlag)
+-- (onlyLazyLetFloats floats extra_binds) returns (Just (binds, ff)) if all the
+-- let-floats in `floats`, followed by `extra_binds`, are let-bindings that we are
+-- prepared to float out of a RHS: no case-floats or tick-floats, and no
+-- FltCareful bindings. The FloatFlag `ff` combines the flags of the `binds`,
+-- so it is FltLifted or FltOkSpec.
+-- Precondition: there are no join floats
+-- See Note [prepareBinding] in GHC.Core.Opt.Simplify.Iteration
+onlyLazyLetFloats (SimplFloats { sfLetFloats = fs, sfJoinFloats = jfs }) extra_binds
+ = assertPpr (isNilOL jfs) (ppr jfs) $
+ go FltLifted nilOL (fromOL fs)
+ where
+ go ff binds [] = foldlOL add_extra (Just (binds, ff)) extra_binds
+ go ff binds (FloatLet bind : rest)
+ | FltCareful <- bind_ff = Nothing
+ | otherwise = go (ff `andFF` bind_ff) (binds `snocOL` bind) rest
+ where
+ bind_ff = getFF_Let bind -- See Note [FloatFlag for FloatLet]
+ go _ _ _ = Nothing -- Case-float or tick-float
-letFloatBinds :: LetFloats -> [CoreBind]
-letFloatBinds (LetFloats bs _) = fromOL bs
+ add_extra Nothing _ = Nothing
+ add_extra (Just (binds, ff)) bind
+ | FltCareful <- bind_ff = Nothing
+ | otherwise = Just (binds `snocOL` bind, ff `andFF` bind_ff)
+ where
+ bind_ff = getFF_Let bind
+
+letFloatBinds :: SimplFloats -> [OutBind]
+-- The let-floats, as bindings
+-- Precondition: there are no case-floats or tick-floats; true, for example,
+-- for floats that have come out of a recursive or top-level RHS
+-- (see Note [prepareBinding] in GHC.Core.Opt.Simplify.Iteration)
+letFloatBinds (SimplFloats { sfLetFloats = fs }) = map get_bind (fromOL fs)
+ where
+ get_bind (FloatLet bind) = bind
+ get_bind flt = pprPanic "letFloatBinds" (ppr flt)
addJoinFlts :: JoinFloats -> JoinFloats -> JoinFloats
addJoinFlts = appOL
@@ -960,7 +1233,7 @@ addJoinFlts = appOL
mkRecFloats :: SimplFloats -> SimplFloats
-- Flattens the floats into a single Rec group,
-- They must either all be lifted LetFloats or all JoinFloats
-mkRecFloats floats@(SimplFloats { sfLetFloats = LetFloats bs _ff
+mkRecFloats floats@(SimplFloats { sfLetFloats = bs
, sfJoinFloats = jbs
, sfInScope = in_scope })
= assertPpr (isNilOL bs || isNilOL jbs) (ppr floats) $
@@ -969,22 +1242,11 @@ mkRecFloats floats@(SimplFloats { sfLetFloats = LetFloats bs _ff
, sfInScope = in_scope }
where
-- See Note [Bangs in the Simplifier]
- !floats' | isNilOL bs = emptyLetFloats
- | otherwise = unitLetFloat (Rec (flattenBinds (fromOL bs)))
+ !floats' | isNilOL bs = nilOL
+ | otherwise = unitOL (FloatLet (Rec (flattenBinds (letFloatBinds floats))))
!jfloats' | isNilOL jbs = emptyJoinFloats
| otherwise = unitJoinFloat (Rec (flattenBinds (fromOL jbs)))
-wrapFloats :: SimplFloats -> OutExpr -> OutExpr
--- Wrap the floats around the expression
-wrapFloats (SimplFloats { sfLetFloats = LetFloats bs flag
- , sfJoinFloats = jbs }) body
- = foldrOL mk_let (wrapJoinFloats jbs body) bs
- -- Note: Always safe to put the joins on the inside
- -- since the values can't refer to them
- where
- mk_let | FltCareful <- flag = mkCoreLet -- need to enforce let-can-float-invariant
- | otherwise = Let -- let-can-float invariant hold
-
wrapJoinFloatsX :: SimplFloats -> OutExpr -> (SimplFloats, OutExpr)
-- Wrap the sfJoinFloats of the env around the expression,
-- and take them out of the SimplEnv
@@ -999,19 +1261,18 @@ wrapJoinFloats join_floats body
= foldrOL Let body join_floats
getTopFloatBinds :: SimplFloats -> [CoreBind]
-getTopFloatBinds (SimplFloats { sfLetFloats = lbs
- , sfJoinFloats = jbs})
+getTopFloatBinds floats@(SimplFloats { sfJoinFloats = jbs })
= assert (isNilOL jbs) $ -- Can't be any top-level join bindings
- letFloatBinds lbs
+ letFloatBinds floats
{-# INLINE mapLetFloats #-}
mapLetFloats :: LetFloats -> ((Id,CoreExpr) -> (Id,CoreExpr)) -> LetFloats
-mapLetFloats (LetFloats fs ff) fun
- = LetFloats fs1 ff
+mapLetFloats binds fun
+ = binds1
where
app (NonRec b e) = case fun (b,e) of (b',e') -> NonRec b' e'
app (Rec bs) = Rec (strictMap fun bs)
- !fs1 = (mapOL' app fs) -- See Note [Bangs in the Simplifier]
+ !binds1 = mapOL' app binds -- See Note [Bangs in the Simplifier]
{-
************************************************************************
=====================================
compiler/GHC/Core/Opt/Simplify/Iteration.hs
=====================================
@@ -22,8 +22,7 @@ import GHC.Core.Opt.Simplify.Env
import GHC.Core.Opt.Simplify.Inline
import GHC.Core.Opt.Simplify.Utils
import GHC.Core.Opt.OccurAnal ( occurAnalyseExpr, zapLambdaBndrs )
-import GHC.Core.Make hiding( wrapFloats )
-import qualified GHC.Core.Make
+import GHC.Core.Make
import GHC.Core.Coercion hiding ( substCo, substCoVar )
import qualified GHC.Core.Coercion as Coercion
import GHC.Core.Reduction
@@ -40,7 +39,7 @@ import GHC.Core.Utils
import GHC.Core.Opt.Arity ( ArityType, exprArity, arityTypeBotSigs_maybe
, pushCoTyArg, pushCoValArg, exprIsDeadEnd
, typeArity, arityTypeArity, etaExpandAT )
-import GHC.Core.SimpleOpt ( exprIsConApp_maybe, joinPointBinding_maybe, joinPointBindings_maybe )
+import GHC.Core.SimpleOpt ( exprIsConApp_maybe, joinPointBind_maybe )
import GHC.Core.FVs ( mkRuleInfo {- exprsFreeIds -} )
import GHC.Core.Rules ( lookupRule, getRules )
import GHC.Core.Multiplicity
@@ -57,7 +56,6 @@ import GHC.Types.Demand
import GHC.Types.Unique ( hasKey )
import GHC.Types.Basic
import GHC.Types.Tickish
-import GHC.Types.Var ( isTyCoVar )
import GHC.Builtin.WiredIn.Prim( realWorldStatePrimTy )
import GHC.Builtin.KnownKeys( runRWKey, seqHashKey )
@@ -66,6 +64,8 @@ import GHC.Builtin.WiredIn.Ids( seqId )
import qualified GHC.Data.List.Infinite as Inf
import GHC.Data.Maybe ( isNothing, orElse, mapMaybe )
import GHC.Data.FastString
+import GHC.Data.OrdList ( unitOL, isNilOL, appOL, snocOL, foldlOL )
+import GHC.Types.Var.Env ( InScopeSet )
import GHC.Unit.Module ( moduleName )
import GHC.Utils.Outputable
import GHC.Utils.Panic
@@ -255,6 +255,8 @@ simplRecBind env0 bind_cxt pairs0
; let new_bndrs = map sndOf3 triples
; (rec_floats, env2) <- enterRecGroupRHSs env1 new_bndrs $ \env ->
go env triples
+
+ -- In rec_floats, all the `sfLetFloats` bindings are `FltLifted`
; return (mkRecFloats rec_floats, env2) }
where
add_rules :: SimplEnv -> (InBndr,InExpr) -> SimplM (SimplEnv, (InBndr, OutBndr, InExpr))
@@ -283,7 +285,8 @@ simplRecOrTopPair :: SimplEnv
-> BindContext
-> InId -> OutBndr -> InExpr -- Binder and rhs
-> SimplM (SimplFloats, SimplEnv)
-
+-- Invariant: in the returned SimplFloats,
+-- all the `sfLetFloats` bindings are `FltLifted`
simplRecOrTopPair env bind_cxt old_bndr new_bndr rhs
| Just env' <- preInlineUnconditionally env (bindContextLevel bind_cxt)
old_bndr (UnSimplified env) rhs MRefl
@@ -348,25 +351,27 @@ simplLazyBind top_lvl is_rec (bndr,unf_se) (bndr1,env) (rhs,rhs_se)
; (body_floats0, body0) <- {-#SCC "simplExprF" #-} simplExprF body_env body rhs_cont
-- ANF-ise a constructor or PAP rhs
- ; (body_floats2, body2) <- {-#SCC "prepareBinding" #-}
- prepareBinding env top_lvl is_rec
- False -- Not strict; this is simplLazyBind
- bndr1 body_floats0 body0
+ ; (body_lets, lets_in_scope, body2)
+ <- {-#SCC "prepareBinding" #-}
+ prepareBinding env top_lvl is_rec
+ bndr1 (contResultType rhs_cont)
+ body_floats0 body0
-- Subtle point: we do not need or want tvs' in the InScope set
-- of body_floats2, so we pass in 'env' not 'body_env'.
-- Don't want: if tvs' are in-scope in the scope of this let-binding, we may do
-- more renaming than necessary => extra work (see !7777 and test T16577).
-- Don't need: we wrap tvs' around the RHS anyway.
+ ; let body_floats2 = mkLetSimplFloats lets_in_scope body_lets
; (rhs_floats, body3)
- <- if isEmptyFloats body_floats2 || null tvs then -- Simple floating
+ <- if isNilOL body_lets || null tvs then -- Simple floating
{-#SCC "simplLazyBind-simple-floating" #-}
return (body_floats2, body2)
else -- Non-empty floats, and non-empty tyvars: do type-abstraction first
{-#SCC "simplLazyBind-type-abstraction-first" #-}
- do { (poly_binds, body3) <- abstractFloats (seUnfoldingOpts env) top_lvl
- tvs' body_floats2 body2
+ do { (poly_binds, body3) <- abstractFloats (seUnfoldingOpts env) top_lvl tvs'
+ lets_in_scope body_lets body2
; let poly_floats = foldl' extendFloats (emptyFloats env) poly_binds
; return (poly_floats, body3) }
@@ -426,7 +431,7 @@ simplAuxBind (saf,env) bndr new_rhs
= do { -- ANF-ise the RHS
let !occ_fs = getOccFS bndr
; (anf_floats, rhs1) <- prepareRhs env NotTopLevel occ_fs new_rhs
- ; unless (isEmptyLetFloats anf_floats) (tick LetFloatFromLet)
+ ; unless (isNilOL anf_floats) (tick LetFloatFromLet)
; let rhs_floats = emptyFloats env `addLetFloats` anf_floats
-- Simplify the binder and complete the binding
@@ -628,15 +633,14 @@ tryCastWorkerWrapper env bind_cxt old_bndr bndr (Cast rhs co)
= do { uniq <- getUniqueM
; let work_name = mkSystemVarName uniq occ_fs
work_id = mkLocalIdWithInfo work_name ManyTy work_ty work_info
- is_strict = isStrictId bndr
- ; (rhs_floats, work_rhs) <- prepareBinding env top_lvl is_rec is_strict
- work_id (emptyFloats env) rhs
+ ; (rhs_lets, lets_in_scope, work_rhs)
+ <- prepareBinding env top_lvl is_rec work_id work_ty (emptyFloats env) rhs
; work_unf <- mk_worker_unfolding top_lvl work_id work_rhs
; let work_id_w_unf = work_id `setIdUnfolding` work_unf
- floats = rhs_floats `addLetFloats`
- unitLetFloat (NonRec work_id_w_unf work_rhs)
+ floats = mkLetSimplFloats lets_in_scope rhs_lets `addLetFloat`
+ NonRec work_id_w_unf work_rhs
triv_rhs = Cast (Var work_id_w_unf) co
@@ -714,10 +718,12 @@ mkCastWrapperInlinePrag prag = prag
* *
********************************************************************* -}
-prepareBinding :: SimplEnv -> TopLevelFlag -> RecFlag -> Bool
- -> Id -- Used only for its OccName; can be InId or OutId
+prepareBinding :: SimplEnv -> TopLevelFlag -> RecFlag
+ -> Id -- Used only for its OccName; can be InId or OutId
+ -> OutType -- The type of the RHS
-> SimplFloats -> OutExpr
- -> SimplM (SimplFloats, OutExpr)
+ -> SimplM (LetFloats, InScopeSet, OutExpr)
+ -- The InScopeSet includes the binders of the LetFloats
-- In (prepareBinding ... bndr floats rhs), the binding is really just
-- bndr = let floats in rhs
-- Maybe we can ANF-ise this binding and float out; e.g.
@@ -728,8 +734,8 @@ prepareBinding :: SimplEnv -> TopLevelFlag -> RecFlag -> Bool
-- bndr = K a a tmp
-- That's what prepareBinding does
-- Precondition: binder is not a JoinId
--- Postcondition: the returned SimplFloats contains only let-floats
-prepareBinding env top_lvl is_rec strict_bind bndr rhs_floats rhs
+-- Postcondition: returns only let-bindings; see Note [prepareBinding]
+prepareBinding env top_lvl is_rec bndr rhs_ty rhs_floats rhs
= do { -- Never float join-floats out of a non-join let-binding (which this is)
-- So wrap the body in the join-floats right now
-- Hence: rhs_floats1 consists only of let-floats
@@ -745,16 +751,73 @@ prepareBinding env top_lvl is_rec strict_bind bndr rhs_floats rhs
; (anf_floats, rhs2) <- prepareRhs rhs_env top_lvl occ_fs rhs1
-- Finally, decide whether or not to float
- ; let all_floats = rhs_floats1 `addLetFloats` anf_floats
- ; if doFloatFromRhs (seFloatEnable env) top_lvl is_rec strict_bind all_floats rhs2
- then -- Float!
- do { tick LetFloatFromLet
- ; return (all_floats, rhs2) }
-
- else -- Abandon floating altogether; revert to original rhs
- -- Since we have already built rhs1, we just need to add
- -- rhs_floats1 to it
- return (emptyFloats env, wrapFloats rhs_floats1 rhs1) }
+ -- The anf_floats are already let-bindings, so we need not add them
+ -- to rhs_floats1 (and its in-scope set) just to check them
+ ; case onlyLazyLetFloats rhs_floats1 anf_floats of
+ Just (all_lets, ff) -- Float only lazy or ok-for-spec let-bindings
+ -- See Note [prepareBinding]
+ | doFloatFromRhs (seFloatEnable env) top_lvl is_rec all_lets ff rhs2
+ -> do { tick LetFloatFromLet
+ ; let !in_scope = foldlOL extendInScopeSetBind
+ (sfInScope rhs_floats1) anf_floats
+ -- rhs_floats1 already has the binders of its own floats
+ ; return (all_lets, in_scope, rhs2) }
+
+ _ -> -- Abandon floating altogether; revert to original rhs
+ -- Since we have already built rhs1, we just need to add
+ -- rhs_floats1 to it
+ do { rhs' <- simplWrapFloats (seMode env) rhs_floats1 rhs1 rhs_ty
+ ; return (emptyLetFloats, seInScope env, rhs') } }
+
+{- Note [prepareBinding]
+~~~~~~~~~~~~~~~~~~~~~~~~~
+In (prepareBinding ... bndr floats rhs), the binding is really
+ bndr = let floats in rhs
+and prepareBinding decides whether to float the floats out, so that we get
+ floats; bndr = rhs
+using doFloatFromRhs to make the decision. First it ANF-ises the RHS with
+prepareRhs, which may add more floats.
+
+prepareBinding floats only let-bindings, and only lazy or ok-for-speculation
+ones (FltLifted or FltOkSpec): if any of the floats is a case-float, a tick-float,
+or a FltCareful let-binding, it floats nothing. So it returns just let-bindings
+(LetFloats), and doFloatFromRhs is concerned only with let-bindings. All this is
+done by onlyLazyLetFloats, in a single pass over the floats.
+
+We never float a FltCareful let-binding (a strict one whose RHS is not
+ok-for-speculation), even out of the RHS of a strict binding: we just don't
+think it is worth it. See (FFL1) in Note [FloatFlag for FloatLet] in
+GHC.Core.Opt.Simplify.Env.
+
+Why not float case-floats and tick-floats too?
+
+(PB1) If the RHS of a lazy binding is /\tvs. body (with no value lambda),
+ simplLazyBind strips off the type lambdas, simplifies the body, and calls
+ prepareBinding on the body. If prepareBinding floats anything, simplLazyBind
+ must then abstract those floats over the `tvs`, with abstractFloats; see
+ Note [Floating and type abstraction] in GHC.Core.Opt.Simplify.Utils. But
+ abstractFloats can only deal with let-bindings: a case-float binds pattern
+ variables strictly, and cannot be abstracted over the `tvs`. T27737a was a
+ panic arising from a case-float reaching abstractFloats.
+
+(PB2) For a tick-float, see Note [Tick-floats] in GHC.Core.Opt.Simplify.Env.
+
+(PB3) It is simple, and before case-floats existed, a case simply stayed in the
+ RHS, so we lose nothing compared to that.
+
+(PB4) Lost opportunity. Consider
+ x = case addIntC# a b of (# r, c #) -> K r c
+ The scrutinee is ok-for-speculation, so we /could/ float the case-float out,
+ to get
+ case addIntC# a b of (# r, c #) -> let x = K r c in ...
+ Now x is bound to a value, so case-of-known-constructor can see through it.
+ That is just what we do for a strict let with an ok-for-speculation RHS (which
+ is FltOkSpec). But we would need to classify case-floats with a FloatFlag
+ (FltOkSpec if the scrutinee is ok-for-speculation, otherwise FltCareful), and
+ to avoid floating them when they must be abstracted over type variables (PB1).
+ We do not currently do this; the simplicity of returning only let-bindings
+ seems to be worth more.
+-}
{- Note [prepareRhs]
~~~~~~~~~~~~~~~~~~~~
@@ -813,7 +876,7 @@ prepareRhs env top_lvl occ rhs0
anfise (App fun arg)
= do { (floats1, fun') <- anfise fun
; (floats2, arg') <- makeTrivial env top_lvl topDmd occ arg
- ; return (floats1 `addLetFlts` floats2, App fun' arg') }
+ ; return (floats1 `appOL` floats2, App fun' arg') }
anfise (Var fun)
= return (emptyLetFloats, Var fun)
@@ -879,43 +942,69 @@ makeTrivial env top_lvl dmd occ_fs expr
bind = NonRec final_id expr2
; traceSmpl "makeTrivial" (vcat [text "final_id" <+> ppr final_id, text "rhs" <+> ppr expr2 ])
- ; return ( floats `addLetFlts` unitLetFloat bind, Var final_id ) }
+ ; return ( assertPpr (not (needsCaseBinding expr_ty expr2)) (ppr bind) $
+ -- See bindingOk and Note [Cannot trivialise]
+ floats `snocOL` bind, Var final_id ) }
where
id_info = vanillaIdInfo `setDemandInfo` dmd
expr_ty = exprType expr
bindingOk :: TopLevelFlag -> CoreExpr -> Type -> Bool
--- True iff we can have a binding of this expression at this level
+-- True iff we can have a let-binding of this expression at this level
-- Precondition: the type is the type of the expression
+-- See Note [Cannot trivialise]
bindingOk top_lvl expr expr_ty
| isTopLevel top_lvl = exprIsTopLevelBindable expr expr_ty
- | otherwise = True
+ | otherwise = not (needsCaseBinding expr_ty expr)
{- Note [Cannot trivialise]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Consider:
- f :: Int -> Addr#
+The goal of makeTrivial (when called from prepareRhs) is to transform
+ x = Just (f y)
+into
+ x = let z = f y in Just z
+and thence, by floating, into
+ z = f y
+ x = Just z
+so that x is bound to a value. It returns only let-bindings (LetFloats), so
+sometimes it cannot trivialise its argument, and must return it unchanged.
+
+(CT1) Nested bindings. Suppose that (f y) had type Int#, with a different data
+ constructor Just' :: Int# -> T. Then we cannot let-bind (f y), because that
+ would violate the let-can-float invariant (unless (f y) is ok-for-speculation).
+ We could case-bind it instead, to get
+ x = case f y of r -> Just' r
+ but there is no point: x is no more of a value than it was before. So we
+ lose nothing by not trivialising (f y); CorePrep will case-bind it anyway.
+ Hence the needsCaseBinding test in bindingOk. (See also #27910.)
+
+ makeTrivialArg, called from mkDupableCont, may therefore return a non-trivial
+ argument, which may then be duplicated into several branches. That duplicates
+ code but not work, since only one branch is executed.
- foo :: Bar
- foo = Bar (f 3)
+(CT2) Top-level bindings. Consider:
+ f :: Int -> Addr#
-Then we can't ANF-ise foo, even though we'd like to, because
-we can't make a top-level binding for the Addr# (f 3). And if
-so we don't want to turn it into
- foo = let x = f 3 in Bar x
-because we'll just end up inlining x back, and that makes the
-simplifier loop. Better not to ANF-ise it at all.
+ foo :: Bar
+ foo = Bar (f 3)
-Literal strings are an exception.
+ Then we can't ANF-ise foo, even though we'd like to, because
+ we can't make a top-level binding for the Addr# (f 3). And if
+ so we don't want to turn it into
+ foo = let x = f 3 in Bar x
+ because we'll just end up inlining x back, and that makes the
+ simplifier loop. Better not to ANF-ise it at all.
- foo = Ptr "blob"#
+ Literal strings are an exception.
-We want to turn this into:
+ foo = Ptr "blob"#
- foo1 = "blob"#
- foo = Ptr foo1
+ We want to turn this into:
-See Note [Core top-level string literals] in GHC.Core.
+ foo1 = "blob"#
+ foo = Ptr foo1
+
+ See Note [Core top-level string literals] in GHC.Core.
************************************************************************
* *
@@ -1191,7 +1280,7 @@ simplExprC env expr cont
; -- pprTrace "simplExprC ret" (ppr expr $$ ppr expr') $
-- pprTrace "simplExprC ret3" (ppr (seInScope env')) $
-- pprTrace "simplExprC ret4" (ppr (seLetFloats env')) $
- return (wrapFloats floats expr') }
+ simplWrapFloats (seMode env) floats expr' (contResultType cont) }
--------------------------------------------------
simplExprF :: SimplEnv
@@ -1282,18 +1371,20 @@ simplExprF1 env expr@(Lam {}) cont
-- NB: countArgs counts all the args (incl type args)
-- and likewise drop counts all binders (incl type lambdas)
-simplExprF1 env (Case scrut bndr _ alts) cont
+simplExprF1 env expr@(Case scrut bndr _ alts) cont
+ | Just (inner, outer) <- splitContForNoCaseCase env cont
+ -- See (COC-INV) in Note [sm_case_case: switching off case continuations]
+ = do { (floats, expr') <- simplExprF env expr inner
+ ; rebuildWithFloats env floats expr' outer }
+
+ | otherwise
= {-#SCC "simplExprF1-Case" #-}
simplExprF env scrut (Select { sc_bndr = bndr, sc_alts = alts
, sc_env = UnSimplified env, sc_cont = cont })
-simplExprF1 env (Let (Rec pairs) body) cont
- | Just pairs' <- joinPointBindings_maybe pairs
- = {-#SCC "simplRecJoinPoin" #-} simplRecJoinPoint env pairs' body cont
-
- | otherwise
- = {-#SCC "simplRecE" #-} simplRecE env pairs body cont
+-- Let-expressions
+-- Try to eiminate the let altogether
simplExprF1 env (Let (NonRec bndr rhs) body) cont
| Type ty <- rhs -- First deal with type lets (let a = Type ty in e)
= {-#SCC "simplExprF1-NonRecLet-Type" #-}
@@ -1308,18 +1399,42 @@ simplExprF1 env (Let (NonRec bndr rhs) body) cont
tick (PreInlineUnconditionally bndr)
; simplExprF env' body cont }
- -- Now check for a join point. It's better to do the preInlineUnconditionally
- -- test first, because joinPointBinding_maybe has to eta-expand, so a trivial
- -- binding like { j = j2 |> co } would first be eta-expanded and then inlined
- -- Better to test preInlineUnconditionally first.
- | Just (bndr', rhs') <- joinPointBinding_maybe bndr rhs
- = {-#SCC "simplNonRecJoinPoint" #-}
- simplNonRecJoinPoint env bndr' rhs' body cont
+simplExprF1 env expr@(Let {}) cont
+ | Just (inner, outer) <- splitContForNoCaseCase env cont
+ -- See (COC-INV) in Note [sm_case_case: switching off case continuations]
+ = do { (floats, expr') <- simplExprF env expr inner
+ ; rebuildWithFloats env floats expr' outer }
- | otherwise
+-- Now check for a join point. It's better to do the preInlineUnconditionally
+-- test first, because joinPointBinding_maybe has to eta-expand, so a trivial
+-- binding like { j = j2 |> co } would first be eta-expanded and then inlined
+-- Better to test preInlineUnconditionally first.
+--
+-- Must be after the seCaseCase stuff: todo: explain why
+-- Example GHC.Internal.Debug
+simplExprF1 env (Let bind body) cont
+ | Just bind' <- joinPointBind_maybe bind
+ = simplJoinPointBind env bind' body cont
+
+-- Non-recursive let
+simplExprF1 env (Let (NonRec bndr rhs) body) cont
= {-#SCC "simplNonRecE" #-}
simplNonRecE env FromLet bndr (rhs, env) body cont
+-- Recursive let
+simplExprF1 env (Let (Rec pairs) body) cont
+ = {-#SCC "simplRecE" #-}
+ simplRecE env pairs body cont
+
+
+splitContForNoCaseCase :: SimplEnv -> SimplCont
+ -> Maybe (SimplCont, SimplCont)
+-- When seCaseCase is off, this function splits `cont` into (inner, outer),
+-- where `inner` has only applications, and `outer` is non-trivial
+splitContForNoCaseCase env cont
+ | seCaseCase env = Nothing
+ | otherwise = splitContArgs cont
+
{- Note [Avoiding space leaks in OutType]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Since the simplifier is run for multiple iterations, we need to ensure
@@ -1362,6 +1477,13 @@ work. T5631 is a good example of this.
emit it into the output program, after obtaining it from
contResultType. (The hole type in ApplyToTy is only directly used
to form the result type in a new Stop continuation.)
+
+- In particular, the type annotation on a Case is forced by returnCase in
+ GHC.Core.Opt.Simplify.Utils, where the Case is finally built (via mkCase, or
+ directly). Its callers
+ should not force it themselves: e.g. simplWrapFloats is given the type of the
+ body, but needs it only if there is a case-float, and forcing it in other
+ cases can do a lot of unnecessary work.
-}
---------------------------------
@@ -1473,10 +1595,16 @@ simplTick env tickish expr cont
-- push the continuation inside the tick. This has the effect of moving the
-- tick to the outside of a case or application context, allowing the normal
-- 'case' and 'application' optimisations to fire.
+ --
+ -- We return the tick as a FloatTick, /outside/ the floats from `expr`.
+ -- So all the code that was covered by the tick (including the floats,
+ -- notably single-alternative case floats) remains covered, as soft scope
+ -- requires; and yet `expr'` is exposed to the caller, e.g. for
+ -- case-of-known-constructor in rebuildWithFloats.
+ -- See Note [Tick-floats] in GHC.Core.Opt.Simplify.Env
| tickishHasSoftScope tickish
= do { (floats, expr') <- simplExprF env expr cont
- ; return (floats, mkTick tickish expr')
- }
+ ; return (unitOL (FloatTick tickish) `addFloatBindsF` floats, expr') }
-- Push tick inside if the context looks like this will allow us to
-- do a case-of-case - see Note [case-of-scc-of-case]
@@ -1513,9 +1641,8 @@ simplTick env tickish expr cont
no_floating_past_tick =
do { let (inc,outc) = splitCont cont
- ; (floats, expr1) <- simplExprF env expr inc
- ; let expr2 = wrapFloats floats expr1
- tickish' = simplTickish env tickish
+ ; expr2 <- simplExprC env expr inc
+ ; let tickish' = simplTickish env tickish
; rebuild env (mkTick tickish' expr2) outc
}
@@ -1601,6 +1728,23 @@ simplTick env tickish expr cont
rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM (SimplFloats, OutExpr)
rebuild env expr cont = rebuild_go (zapSubstEnv env) expr cont
+rebuildWithFloats :: SimplEnv -> SimplFloats -> OutExpr -> SimplCont
+ -> SimplM (SimplFloats, OutExpr)
+-- (rebuildWithFloats env floats expr cont) rebuilds (let floats in expr)
+-- with continuation `cont`. Used only when seCaseCase is off.
+-- See (COC3) in Note [sm_case_case: switching off case continuations]
+rebuildWithFloats env floats expr cont
+ | Select { sc_bndr = bndr, sc_alts = alts, sc_env = se, sc_cont = cont' } <- cont
+ , isEmptyJoinFloats (sfJoinFloats floats)
+ , let env1 = zapSubstEnv env `setInScopeFromF` floats
+ , Just do_it <- knownConCase_maybe (mkAltEnv env1 se) expr bndr alts cont'
+ = do { (floats2, res) <- do_it
+ ; return (floats `addFloats` floats2, res) }
+
+ | otherwise
+ = do { expr' <- simplWrapFloats (seMode env) floats expr (contHoleType cont)
+ ; rebuild env expr' cont }
+
rebuild_go :: HasDebugCallStack
=> SimplEnvIS -> OutExpr -> SimplCont -> SimplM (SimplFloats, OutExpr)
-- SimplEnvIS: at this point the substitution in the SimplEnv is irrelevant;
@@ -1655,24 +1799,22 @@ completeBindX env from_what bndr rhs body cont
= do { (env1, bndr1) <- simplNonRecBndr env bndr -- Lambda binders don't have rules
; (floats, expr') <- simplNonRecBody env1 from_what body cont
-- Do not float floats past the Case binder below
- ; let expr'' = wrapFloats floats expr'
- case_expr = Case rhs bndr1 (contResultType cont) [Alt DEFAULT [] expr'']
+ ; let res_ty = contResultType cont
+ ; expr'' <- simplWrapFloats (seMode env) floats expr' res_ty
+ ; case_expr <- returnCase rhs bndr1 res_ty [Alt DEFAULT [] expr'']
; return (emptyFloats env, case_expr) }
| otherwise -- Make a let-binding
= do { (env1, bndr1) <- simplNonRecBndr env bndr
; (env2, bndr2) <- addBndrRules env1 bndr bndr1 (BC_Let NotTopLevel NonRecursive)
- ; let is_strict = isStrictId bndr2
- -- isStrictId: use simplified binder because the InId bndr might not have
- -- a fixed runtime representation, which isStrictId doesn't expect
- -- c.f. Note [Dark corner with representation polymorphism]
-
- ; (rhs_floats, rhs1) <- prepareBinding env NotTopLevel NonRecursive is_strict
- bndr2 (emptyFloats env) rhs
+ ; (rhs_lets, lets_in_scope, rhs1)
+ <- prepareBinding env NotTopLevel NonRecursive
+ bndr2 (idType bndr2) (emptyFloats env) rhs
-- NB: it makes a surprisingly big difference (5% in compiler allocation
-- in T9630) to pass 'env' rather than 'env1'. It's fine to pass 'env',
-- because this is completeBindX, so bndr is not in scope in the RHS.
+ ; let rhs_floats = mkLetSimplFloats lets_in_scope rhs_lets
; let env3 = env2 `setInScopeFromF` rhs_floats
; (bind_float, env4) <- completeBind (BC_Let NotTopLevel NonRecursive)
@@ -2015,9 +2157,10 @@ simplNonRecE env from_what bndr (rhs, rhs_se) body cont
-- If not, the invariant holds already, and it's optional.
-- (FromBeta Lifted) or FromLet: look at the demand info
+ -- seCaseCase: see (COC-INV)
+ -- in Note [sm_case_case: switching off case continuations]
_ -> seCaseCase env && isStrUsedDmd (idDemandInfo bndr)
-
------------------
simplRecE :: SimplEnv
-> [(InId, InExpr)]
@@ -2085,10 +2228,10 @@ is a join point, and what 'cont' is, in a value of type MaybeJoinCont
of a SpecConstr-generated RULE for a join point.
-}
-simplNonRecJoinPoint :: SimplEnv -> InId -> InExpr
+simplJoinPointBind :: SimplEnv -> InBind
-> InExpr -> SimplCont
-> SimplM (SimplFloats, OutExpr)
-simplNonRecJoinPoint env bndr rhs body cont
+simplJoinPointBind env (NonRec bndr rhs) body cont
= assert (isJoinId bndr ) $
wrapJoinCont env cont $ \ env cont ->
do { -- We push join_cont into the join RHS and the body;
@@ -2101,12 +2244,7 @@ simplNonRecJoinPoint env bndr rhs body cont
; (floats2, body') <- simplExprF env3 body cont
; return (floats1 `addFloats` floats2, body') }
-
-------------------
-simplRecJoinPoint :: SimplEnv -> [(InId, InExpr)]
- -> InExpr -> SimplCont
- -> SimplM (SimplFloats, OutExpr)
-simplRecJoinPoint env pairs body cont
+simplJoinPointBind env (Rec pairs) body cont
= wrapJoinCont env cont $ \ env cont ->
do { let bndrs = map fst pairs
mult = contHoleScaling cont
@@ -2125,18 +2263,13 @@ wrapJoinCont :: SimplEnv -> SimplCont
-- Deal with making the continuation duplicable if necessary,
-- and with the no-case-of-case situation.
wrapJoinCont env cont thing_inside
- | contIsStop cont -- Common case; no need for fancy footwork
+ | contIsStop cont -- Fast path: no need for fancy footwork
= thing_inside env cont
- | not (seCaseCase env)
- -- See Note [Join points with -fno-case-of-case]
- = do { (floats1, expr1) <- thing_inside env (mkBoringStop (contHoleType cont))
- ; let (floats2, expr2) = wrapJoinFloatsX floats1 expr1
- ; (floats3, expr3) <- rebuild (env `setInScopeFromF` floats2) expr2 cont
- ; return (floats2 `addFloats` floats3, expr3) }
-
| otherwise
-- Normal case; see Note [Join points and case-of-case]
+ -- Case-of-case should be /on/ here, else we should not
+ -- be in wrapJoinCont in the first place
= do { (floats1, cont') <- mkDupableCont env cont
; (floats2, result) <- thing_inside (env `setInScopeFromF` floats1) cont'
; return (floats1 `addFloats` floats2, result) }
@@ -2166,8 +2299,84 @@ trimJoinCont var (JoinPoint arity) cont
= pprPanic "completeCall" $ ppr var $$ ppr cont
-{- Note [Join points and case-of-case]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+{- Note [sm_case_case: switching off case continuations]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Normally when we come across a `case` expression, we just push a `Select`
+continuation onto the continuation, roughly like this.
+ simplExprF (Case scrut alts) cont
+ = simplExprF scrut (Select alts cont)
+
+There are two reasons that we might NOT want to do this
+
+1. Loss of full laziness. The case-of-case transformation can hide
+ opportunities for let-floating (aka full laziness). For example
+ rec { f = \y. case (expensive x) of (a,b) -> blah }
+ We might hope to float the (expensive x) out of the \y-loop.
+ But if we inline `expensive` we might get
+ \y. case (case x of I# x' -> body) of (a,b) -> blah
+ Now if we do case-of-case we get
+ \y. case x if I# x2 ->
+ case body of (a,b) -> blah
+
+ Sadly, at this point `body` mentions `x2`, so we can't float it out of the \y-loop.
+
+2. Pushing a `case` inside a `let` can prevent a join point from being
+ discovered (#27737). For example
+ case (letrec j x y = ... in id (j p q)) of blah
+ Here `j` is not /yet/ a join point, because it is not tail called, but it
+ well become one after we inline `id`. But if we push that `case` inwards
+ at the same time as inlinine `id` we'll get
+ letrec j x y = ... in case (j p q) of blah
+ and now `j` /still/ isn't a join point, and will never become one. This
+ matters in practice: #27737
+
+Solution in both cases: in the "gentle" simplification phase that precedes the
+first float-out transformation, never push a `Select` continuation. So we
+do not push the `case` inwards. This behaiour is controlled by the `sm_case_case`
+field of `SimplMode`, interrogated via `seCaseCase`.
+
+Some specifics, for when `sm_case_case` is False:
+
+(COC-INV) When `sm_case_case` is False we obey the following invariant:
+ The SimplCont never contains
+ - Select
+ - StrictBind
+ - StrictArg
+ This is achieved by testing `seCaseCase` just before pushing any of
+ those three constructors. Why StrictBind and StrictArg? Because
+ they mess with evaluation order in the same way that Select does.
+
+(COC1) The (COC-INV) also solves #25055, where we pushed a `case` inside `runRW`:
+ case (runRW# (\s. body)) of (a,b) -> blah
+ --->
+ runRW# (\s. case body of (a,b) -> blah)
+ Again, we don't want to this when `sm_case_case` is False, but that falls
+ out as a simple consequence of (COC-INV)
+
+(COC2) Supose `sm_case_case` is False, and we are simplifying
+
+ case (join j x = <j-rhs> in
+ case y of
+ A -> j 1
+ B -> j 2
+ C -> e) of <outer-alts>
+
+ Usually, we'd push the outer continuation (case . of <outer-alts>) into
+ both the RHS and the body of the join point j. But since we aren't doing
+ case-of-case we could end up with this totally bogus result
+
+ join x = case <j-rhs> of <outer-alts> in
+ case (case y of
+ A -> j 1
+ B -> j 2
+ C -> e) of <outer-alts>
+
+ Again, (COC-INV) neatly avoid this bogosity: we never push a Select
+ onto the continuation. This is much nicer than switching off case-of-case
+ specifically (which we used to do).
+
+Note [Join points and case-of-case]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we perform the case-of-case transform (or otherwise push continuations
inward), we want to treat join points specially. Since they're always
tail-called and we want to maintain this invariant, we can do this (for any
@@ -2198,44 +2407,6 @@ optional!
We need to make the continuation E duplicable (since we are duplicating it)
with mkDupableCont.
-Note [Join points with -fno-case-of-case]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Supose case-of-case is switched off, and we are simplifying
-
- case (join j x = <j-rhs> in
- case y of
- A -> j 1
- B -> j 2
- C -> e) of <outer-alts>
-
-Usually, we'd push the outer continuation (case . of <outer-alts>) into
-both the RHS and the body of the join point j. But since we aren't doing
-case-of-case we may then end up with this totally bogus result
-
- join x = case <j-rhs> of <outer-alts> in
- case (case y of
- A -> j 1
- B -> j 2
- C -> e) of <outer-alts>
-
-This would be OK in the language of the paper, but not in GHC: j is no longer
-a join point. We can only do the "push continuation into the RHS of the
-join point j" if we also push the continuation right down to the /jumps/ to
-j, so that it can evaporate there (trimJoinCont). Then, if we are doing
-case-of-case, we'll get to:
-
- join x = case <j-rhs> of <outer-alts> in
- case y of
- A -> j 1
- B -> j 2
- C -> case e of <outer-alts>
-
-which is great.
-
-Bottom line: if case-of-case is off, we must stop pushing the continuation
-inwards altogether at any join point. Instead simplify the (join ... in ...)
-with a Stop continuation, and wrap the original continuation around the
-outside. Surprisingly tricky!
************************************************************************
@@ -2353,49 +2524,14 @@ simplOutId :: SimplEnvIS -> OutId -> SimplCont -> SimplM (SimplFloats, OutExpr)
simplOutId env fun cont
| fun `hasKey` runRWKey
, ApplyToTy { sc_cont = cont1 } <- cont
- , ApplyToTy { sc_cont = cont2, sc_arg_ty = hole_ty } <- cont1
- , ApplyToVal { sc_cont = cont3, sc_arg = arg, sc_cast = arg_mco
- , sc_env = arg_se, sc_hole_ty = fun_ty } <- cont2
- -- Do this even if (contIsStop cont), or if seCaseCase is off.
- -- See Note [No eta-expansion in runRW#]
- = do { let (_saf,arg_env) = mkAltEnv env arg_se
-
- overall_res_ty = contResultType cont3
- -- hole_ty is the type of the current runRW# application
- (outer_cont, new_runrw_res_ty, inner_cont)
- | seCaseCase env = (mkBoringStop overall_res_ty, overall_res_ty, cont3)
- | otherwise = (cont3, hole_ty, mkBoringStop hole_ty)
- -- Only when case-of-case is on. See GHC.Driver.Config.Core.Opt.Simplify
- -- Note [Case-of-case and full laziness]
-
- -- If the argument is a literal lambda already, take a short cut
- -- This isn't just efficiency:
- -- * If we don't do this we get a beta-redex every time, so the
- -- simplifier keeps doing more iterations.
- -- * Even more important: see Note [No eta-expansion in runRW#]
- ; arg' <- case arg of
- Lam s body -> do { (env', s') <- simplBinder arg_env s
- ; body' <- simplExprC env' body inner_cont
- ; return (Lam s' body') }
- -- Important: do not try to eta-expand this lambda
- -- See Note [No eta-expansion in runRW#]
-
- _ -> do { s' <- newId (fsLit "s") ManyTy realWorldStatePrimTy
- ; let (m,_,_) = splitFunTy fun_ty
- env' = arg_env `addNewInScopeIds` [s']
- hole_ty = mkVisFunTy m realWorldStatePrimTy new_runrw_res_ty
- ; cont' <- pushCastMCo env' arg_mco $
- ApplyToVal { sc_arg = Var s', sc_cast = MRefl
- , sc_env = Simplified OkDup
- , sc_cont = inner_cont
- , sc_hole_ty = hole_ty }
- -- cont' applies to s', then K
- ; body' <- simplExprC env' arg cont'
- ; return (Lam s' body') }
-
- ; let rr' = getRuntimeRep new_runrw_res_ty
- call' = mkApps (Var fun) [mkTyArg rr', mkTyArg new_runrw_res_ty, arg']
- ; rebuild_go env call' outer_cont }
+ , ApplyToTy { sc_cont = cont2 } <- cont1
+ , ApplyToVal { sc_cont = cont3, sc_arg = arg, sc_env = arg_se
+ , sc_cast = arg_mco, sc_hole_ty = fun_ty } <- cont2
+ = case splitContForNoCaseCase env cont3 of
+ Nothing -> do { e' <- simplRunRW env fun arg arg_se arg_mco fun_ty cont3
+ ; return (emptyFloats env, e') }
+ Just (ink,outk) -> do { e' <- simplRunRW env fun arg arg_se arg_mco fun_ty ink
+ ; rebuild env e' outk }
-- Normal case for (f e1 .. en)
simplOutId env fun cont
@@ -2430,6 +2566,51 @@ simplOutId env fun cont
; rebuildCall env arg_info cont
} } } } }
+simplRunRW :: SimplEnv
+ -> OutId -- runRW#
+ -> CoreExpr -- Main value argument `e` of runRW#
+ -> StaticEnv -- ...and its static envt
+ -> MOutCoercion -- ...and its MCoercion
+ -> OutType -- Type of (runRW# @k @ty), always t1->t2
+ -> SimplCont -- Continuation to push into body of `e`
+ -> SimplM OutExpr
+simplRunRW env fun arg arg_se arg_mco fun_ty cont
+ -- Do this even if (contIsStop cont), or if seCaseCase is off.
+ -- See Note [No eta-expansion in runRW#]
+ = do { let (_saf,arg_env) = mkAltEnv env arg_se
+
+ overall_res_ty = contResultType cont
+ -- hole_ty is the type of the current runRW# application
+
+ -- If the argument is a literal lambda already, take a short cut
+ -- This isn't just efficiency:
+ -- * If we don't do this we get a beta-redex every time, so the
+ -- simplifier keeps doing more iterations.
+ -- * Even more important: see Note [No eta-expansion in runRW#]
+ ; arg' <- case arg of
+ Lam s body -> do { (env', s') <- simplBinder arg_env s
+ ; body' <- simplExprC env' body cont
+ ; return (Lam s' body') }
+ -- Important: do not try to eta-expand this lambda
+ -- See Note [No eta-expansion in runRW#]
+
+ _ -> do { s' <- newId (fsLit "s") ManyTy realWorldStatePrimTy
+ ; let (m,_,_) = splitFunTy fun_ty
+ env' = arg_env `addNewInScopeIds` [s']
+ hole_ty = mkVisFunTy m realWorldStatePrimTy overall_res_ty
+ ; cont' <- pushCastMCo env' arg_mco $
+ ApplyToVal { sc_arg = Var s', sc_cast = MRefl
+ , sc_env = Simplified OkDup
+ , sc_cont = cont
+ , sc_hole_ty = hole_ty }
+ -- cont' applies to s', then K
+ ; body' <- simplExprC env' arg cont'
+ ; return (Lam s' body') }
+
+ ; let rr' = getRuntimeRep overall_res_ty
+ call' = mkApps (Var fun) [mkTyArg rr', mkTyArg overall_res_ty, arg']
+ ; return call' }
+
---------------------------------------------------------
-- Dealing with a call site
@@ -2460,8 +2641,8 @@ rebuildCall env fun_info
, sc_hole_ty = fun_ty, sc_cont = cont })
| UnSimplified arg_env <- arg_se
, isStrictArgInfo fun_info -- Strict arguments
- , seCaseCase env -- But only when case-of-case is on.
- -- See Note [Case-of-case and full laziness]
+ , seCaseCase env -- But only when case-of-case is on; see (COC-INV)
+ -- in Note [sm_case_case: switching off case continuations]
= simplExprF (arg_env `setInScopeFromE` env) arg $
addCastMCo arg_mco $
StrictArg { sc_fun = fun_info, sc_fun_ty = fun_ty
@@ -2469,7 +2650,7 @@ rebuildCall env fun_info
, sc_cont = cont }
-- Note [Shadowing in the Simplifier]
- | otherwise -- Lazy, or already simplified arguments
+ | otherwise -- Lazy, or already simplified arguments, or -fno-case-of-case
-- DO NOT float anything outside, hence simplExprC
-- There is no benefit (unlike in a let-binding), and we'd
-- have to be very careful about bogus strictness through
@@ -2753,14 +2934,10 @@ fireRuleAFTER env rule_match arg_specs cont
| RM { rm_rule = rule, rm_rhs = rhs, rm_args = rhs_args
, rm_floats = float_bs } <- rule_match
= do { let env' = env `addNewInScopeIds` floatsBinders float_bs
- ; (floats, e') <- simplExprF env' rhs $
- pushOutArgs (exprType rhs) rhs_args $
- pushArgSpecs (drop (ruleArity rule) arg_specs) cont
- ; return $
- if isEmptyFloatBinds float_bs -- Not very pretty
- then (floats, e')
- else (emptyFloats env', GHC.Core.Make.wrapFloats float_bs $
- wrapFloats floats e') }
+ ; addFloatBinds (contHoleScaling cont) float_bs $
+ simplExprF env' rhs $
+ pushOutArgs (exprType rhs) rhs_args $
+ pushArgSpecs (drop (ruleArity rule) arg_specs) cont }
tryRules :: SimplEnv -> [CoreRule]
@@ -3223,41 +3400,9 @@ rebuildCase, reallyRebuildCase
-- 1. Eliminate the case if there's a known constructor
--------------------------------------------------
-rebuildCase (saf,env) scrut case_bndr alts cont
- | Lit lit <- scrut -- No need for same treatment as constructors
- -- because literals are inlined more vigorously
- , not (litIsLifted lit)
- = do { tick (KnownBranch case_bndr)
- ; case findAlt (LitAlt lit) alts of
- Nothing -> missingAlt env case_bndr alts cont
- Just (Alt _ bs rhs) -> simpl_rhs env scrut bs rhs }
-
- | Just (in_scope', wfloats, con, ty_args, other_args)
- <- exprIsConApp_maybe (getUnfoldingInRuleMatch env) scrut
- -- Works when the scrutinee is a variable with a known unfolding
- -- as well as when it's an explicit constructor application
- , let env0 = setInScopeSet env in_scope'
- = do { tick (KnownBranch case_bndr)
- ; let -- case_bndr_unf: see Note [Do not duplicate constructor applications]
- case_bndr_rhs | exprIsTrivial scrut = scrut
- | otherwise = con_app
- con_app = Var (dataConWorkId con) `mkTyApps` ty_args
- `mkApps` other_args
- ; wrapDataConFloats env wfloats case_bndr cont $
- case findAlt (DataAlt con) alts of
- Nothing -> missingAlt env0 case_bndr alts cont
- Just (Alt DEFAULT bs rhs) -> simpl_rhs env0 case_bndr_rhs bs rhs
- Just (Alt _ bs rhs) -> knownCon env0 scrut con other_args
- case_bndr bs rhs cont
- }
- where
- simpl_rhs env case_bndr_rhs bs rhs
- = assert (null bs) $
- do { (floats1, env') <- simplAuxBind (saf,env) case_bndr case_bndr_rhs
- -- scrut is a constructor application,
- -- hence satisfies let-can-float invariant
- ; (floats2, expr') <- simplExprF env' rhs cont
- ; return (floats1 `addFloats` floats2, expr') }
+rebuildCase saf_env scrut case_bndr alts cont
+ | Just do_it <- knownConCase_maybe saf_env scrut case_bndr alts cont
+ = do_it
--------------------------------------------------
-- 2. Eliminate the case if scrutinee is evaluated
@@ -3318,54 +3463,74 @@ rebuildCase (saf,env) scrut case_bndr alts cont
| otherwise
= reallyRebuildCase (saf,env) scrut case_bndr alts cont
-doCaseToLet :: OutExpr -- Scrutinee
- -> InId -- Case binder
- -> Bool
--- The situation is case scrut of b { DEFAULT -> body }
--- Can we transform thus? let { b = scrut } in body
-doCaseToLet scrut case_bndr
- | isTyCoVar case_bndr -- Respect GHC.Core
- = isTyCoArg scrut -- Note [Core type and coercion invariant]
-
- | isUnliftedType (exprType scrut)
- -- We can call isUnliftedType here: scrutinees always have a fixed RuntimeRep (see FRRCase).
- -- Note however that we must check 'scrut' (which is an 'OutExpr') and not 'case_bndr'
- -- (which is an 'InId'): see Note [Dark corner with representation polymorphism].
- -- Using `exprType` is typically cheap because `scrut` is typically a variable.
- -- We could instead use mightBeUnliftedType (idType case_bndr), but that hurts
- -- the brain more. Consider that if this test ever turns out to be a perf
- -- problem (which seems unlikely).
- = exprOkForSpeculation scrut
-
- | otherwise -- Scrut has a lifted type
- = exprIsHNF scrut
- -- || isStrUsedDmd (idDemandInfo case_bndr)
- -- We no longer look at the demand on the case binder
- -- See Note [Case-to-let for strictly-used binders]
-
--------------------------------------------------
-- 3. Catch-all case
--------------------------------------------------
reallyRebuildCase (saf,env) scrut case_bndr alts cont
- | not (seCaseCase env) -- Only when case-of-case is on.
- -- See GHC.Driver.Config.Core.Opt.Simplify
- -- Note [Case-of-case and full laziness]
- = do { case_expr <- simplAlts (saf,env) scrut case_bndr alts
- (mkBoringStop (contHoleType cont))
- ; rebuild env case_expr cont }
-
- | otherwise
- = do { (floats, env', cont') <- mkDupableCaseCont env alts cont
- ; case_expr <- simplAlts (saf,env') scrut
- (scaleIdBy holeScaling case_bndr)
- (scaleAltsBy holeScaling alts)
- cont'
- ; return (floats, case_expr) }
+ = do { (alt_env, scrut', case_bndr', imposs_deflt_cons, in_alts)
+ <- prepareCase (saf,env) scrut (scaleIdBy holeScaling case_bndr)
+ (scaleAltsBy holeScaling alts)
+ ; case in_alts of
+ [in_alt] -> rebuildSingleAltCase (saf,alt_env) scrut' case_bndr'
+ imposs_deflt_cons bndr_swap cont in_alt
+ _ -> rebuildMultiAltCase (saf,alt_env) scrut' case_bndr'
+ imposs_deflt_cons bndr_swap cont in_alts }
where
holeScaling = contHoleScaling cont
-- Note [Scaling in case-of-case]
+ bndr_swap = scrutOkForBinderSwap scrut
+
+rebuildSingleAltCase :: (SimplAltFlag, SimplEnv)
+ -> OutExpr -> OutId -- Scrutinee and case binder
+ -> [AltCon] -- Constructors impossible in the DEFAULT alt
+ -> BinderSwapDecision
+ -> SimplCont
+ -> InAlt
+ -> SimplM (SimplFloats, OutExpr)
+-- The arguments are prepared by prepareCase
+-- We return the case as a FloatCase float, so that the floats from its RHS
+-- are not trapped inside it. See Note [Floating single-alternative cases]
+-- There is only one alternative, so no need to make `cont` dupable
+rebuildSingleAltCase (saf,alt_env) scrut' case_bndr' imposs_deflt_cons bndr_swap cont in_alt
+ = do { (con, bs', alt_floats, rhs') <- simplAlt (saf,alt_env) (Just scrut') imposs_deflt_cons
+ case_bndr' bndr_swap cont in_alt
+ ; let no_floats = emptyFloats alt_env
+ case_float
+ | DEFAULT <- con
+ , doCaseToLet scrut' case_bndr'
+ = -- Make a let-float, not a case-float, to maintain invariant
+ -- (FFC1) of Note [Case-floats] in GHC.Core.Opt.Simplify.Env.
+ -- We get here (rather than doing case-to-let in rebuildCase) when
+ -- prepareAlts has pruned away all but the DEFAULT alternative
+ no_floats `addLetFloat` NonRec case_bndr' scrut'
+ | otherwise
+ = addCaseFloat no_floats scrut' case_bndr' con bs'
+ ; return (case_float `addFloats` alt_floats, rhs') }
+
+rebuildMultiAltCase :: (SimplAltFlag, SimplEnv)
+ -> OutExpr -> OutId -- Scrutinee and case binder
+ -> [AltCon] -- Constructors impossible in the DEFAULT alt
+ -> BinderSwapDecision
+ -> SimplCont
+ -> [InAlt]
+ -> SimplM (SimplFloats, OutExpr)
+-- The arguments are prepared by prepareCase
+rebuildMultiAltCase (saf,alt_env) scrut' case_bndr' imposs_deflt_cons bndr_swap cont in_alts
+ = do { -- NB: pass alt_env, not the env before prepareCase, to mkDupableCaseCont,
+ -- so that the case binder stays in scope in env'
+ (floats, env', cont') <- mkDupableCaseCont alt_env in_alts cont
+ ; traceSmpl "rebuildMultiAltCase" (vcat [ ppr case_bndr'
+ , text "cont':" <+> ppr cont'
+ , text "in_scope" <+> ppr (seInScope env') ])
+ ; alts' <- forM in_alts $
+ simplAltC (saf,env') (Just scrut') imposs_deflt_cons
+ case_bndr' bndr_swap cont'
+ ; case_expr <- mkCase (seMode env') scrut' case_bndr' (contResultType cont') alts'
+ -- mkCase forces the type; see Note [Avoiding space leaks in OutType]
+ ; return (floats, case_expr) }
+
{-
simplCaseBinder checks whether the scrutinee is a variable, v. If so,
try to eliminate uses of v in the RHSs in favour of case_bndr; that
@@ -3466,7 +3631,6 @@ robust here. (Otherwise, there's a danger that we'll simply drop the
Note [Scaling in case-of-case]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
When two cases commute, if done naively, the multiplicities will be wrong:
case (case u of w[1] { (x[1], y[1]) } -> f x y) of w'[Many]
@@ -3498,17 +3662,16 @@ scale the entire case we are simplifying, by a scaling factor which can be
computed in the continuation (with function `contHoleScaling`).
-}
-simplAlts :: (SimplAltFlag, SimplEnv)
- -> OutExpr -- Scrutinee
- -> InId -> [InAlt] -- Alts (non-empty)
- -> SimplCont
- -> SimplM OutExpr -- Returns the complete simplified case expression
-
-simplAlts (saf,env0) scrut case_bndr alts cont'
- = do { traceSmpl "simplAlts" (vcat [ ppr case_bndr
- , text "cont':" <+> ppr cont'
- , text "in_scope" <+> ppr (seInScope env0) ])
- ; (env1, case_bndr1) <- simplAltIdBinder (saf,env0) case_bndr
+prepareCase :: (SimplAltFlag, SimplEnv)
+ -> OutExpr -- Scrutinee
+ -> InId -> [InAlt] -- Case binder and alts (non-empty)
+ -> SimplM ( SimplEnv -- For the alternatives
+ , OutExpr -- Scrutinee, perhaps improved by improveSeq
+ , OutId -- Case binder
+ , [AltCon] -- Constructors impossible in the DEFAULT alt
+ , [InAlt] ) -- Alternatives, from prepareAlts
+prepareCase (saf,env0) scrut case_bndr alts
+ = do { (env1, case_bndr1) <- simplAltIdBinder (saf,env0) case_bndr
; let case_bndr2 = case_bndr1 `setIdUnfolding` evaldUnfolding
env2 = modifyInScope env1 case_bndr2
-- See Note [Case binder evaluated-ness]
@@ -3523,15 +3686,34 @@ simplAlts (saf,env0) scrut case_bndr alts cont'
-- NB: pass case_bndr::InId, not case_bndr' :: OutId, to prepareAlts
-- See Note [Shadowing in prepareAlts] in GHC.Core.Opt.Simplify.Utils
- ; alts' <- forM in_alts $
- simplAlt (saf,alt_env') (Just scrut') imposs_deflt_cons
- case_bndr' (scrutOkForBinderSwap scrut) cont'
-
- ; let alts_ty' = contResultType cont'
- -- See Note [Avoiding space leaks in OutType]
- ; seqType alts_ty' `seq`
- mkCase (seMode env0) scrut' case_bndr' alts_ty' alts' }
+ ; return (alt_env', scrut', case_bndr', imposs_deflt_cons, in_alts) }
+{- Note [Floating single-alternative cases]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+When reallyRebuildCase finds a single-alternative case (after prepareAlts)
+ case e of b { (# a, c #) -> let x1 = .. in ... let xn = .. in (# e1, e2 #) }
+it does not return the case expression; instead it returns
+ * floats: [FloatCase e b (# a,c #) [a,c], x1 = .., ..., xn = ..]
+ * result: (# e1, e2 #)
+This is done by rebuildSingleAltCase. See Note [LetFloats] in GHC.Core.Opt.Simplify.Env.
+
+Why? Because a caller (notably rebuildWithFloats, when case-of-case is
+switched off) may want to do case-of-known-constructor on the result. If we
+returned the whole case, exprIsConApp_maybe would have to walk all the way
+down through the case and the lets, which can be quadratic (#27737, T18223).
+
+This is not restricted to the no-case-of-case path: when case-of-case is on,
+the continuation has already been pushed into the alternative, and the
+floats are simply wrapped around the result, or floated further out of a
+strict let (which a StrictBind continuation would do anyway). The
+FloatFlag (FltCareful or FltOkSpec) stops a case-float from floating out of
+a lazy let, or to top level; see doFloatFromRhs.
+
+We do not call mkCase when we build the FloatCase. Instead, simplWrapFloats
+calls mkCase when we eventually wrap the FloatCase around an expression, so we
+still get case-merging, identity-case elimination, caseRules, etc.
+See Note [Wrapping case-floats with mkCase] in GHC.Core.Opt.Simplify.Utils.
+-}
------------------------------------
improveSeq :: (FamInstEnv, FamInstEnv)
@@ -3552,6 +3734,16 @@ improveSeq _ (_,env) scrut _ case_bndr1 _
------------------------------------
+simplAltC :: (SimplAltFlag, SimplEnv) -> Maybe OutExpr -> [AltCon] -> OutId
+ -> BinderSwapDecision -> SimplCont -> InAlt
+ -> SimplM OutAlt
+-- Like simplAlt, but wraps the floats around the RHS
+simplAltC env scrut' imposs_deflt_cons case_bndr' bndr_swap' cont' alt
+ = do { (con, bs, floats, rhs) <- simplAlt env scrut' imposs_deflt_cons
+ case_bndr' bndr_swap' cont' alt
+ ; rhs' <- simplWrapFloats (seMode (snd env)) floats rhs (contResultType cont')
+ ; return (Alt con bs rhs') }
+
simplAlt :: (SimplAltFlag, SimplEnv)
-> Maybe OutExpr -- The scrutinee
-> [AltCon] -- These constructors can't be present when
@@ -3561,19 +3753,24 @@ simplAlt :: (SimplAltFlag, SimplEnv)
-- add unfolding `v :-> bndr |> sym co`
-> SimplCont
-> InAlt
- -> SimplM OutAlt
+ -> SimplM (AltCon, [OutVar], SimplFloats, OutExpr)
+ -- Returns the simplified alternative, in pieces
+ -- The floats scope over the RHS only, and may mention the
+ -- binders of the alternative. So the caller must either wrap
+ -- them around the RHS (simplAltC), or put them after a case-float
+ -- that binds the binders (rebuildSingleAltCase)
simplAlt (saf,env) _scrut' imposs_deflt_cons case_bndr' bndr_swap' cont' (Alt DEFAULT bndrs rhs)
= assert (null bndrs) $
do { let env' = addDefaultUnfoldings env case_bndr' bndr_swap' imposs_deflt_cons
- ; rhs' <- simplAltExprC (saf,env') rhs cont'
- ; return (Alt DEFAULT [] rhs') }
+ ; (floats, rhs') <- simplAltExprF (saf,env') rhs cont'
+ ; return (DEFAULT, [], floats, rhs') }
simplAlt (saf,env) _scrut' _ case_bndr' bndr_swap' cont' (Alt (LitAlt lit) bndrs rhs)
= assert (null bndrs) $
do { let env' = addAltUnfoldings env case_bndr' bndr_swap' (Lit lit)
- ; rhs' <- simplAltExprC (saf,env') rhs cont'
- ; return (Alt (LitAlt lit) [] rhs') }
+ ; (floats, rhs') <- simplAltExprF (saf,env') rhs cont'
+ ; return (LitAlt lit, [], floats, rhs') }
simplAlt (saf,env) scrut' _ case_bndr' bndr_swap' cont' (Alt (DataAlt con) vs rhs)
= do { -- See Note [Adding evaluatedness info to pattern-bound variables]
@@ -3591,8 +3788,8 @@ simplAlt (saf,env) scrut' _ case_bndr' bndr_swap' cont' (Alt (DataAlt con) vs rh
con_app = mkConApp2 con inst_tys' vs'
env'' = addAltUnfoldings env' case_bndr' bndr_swap' con_app
- ; rhs' <- simplAltExprC (saf,env'') rhs cont'
- ; return (Alt (DataAlt con) vs' rhs') }
+ ; (floats, rhs') <- simplAltExprF (saf,env'') rhs cont'
+ ; return (DataAlt con, vs', floats, rhs') }
{- Note [Adding evaluatedness info to pattern-bound variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -3773,11 +3970,6 @@ simplAltExprF (saf,env) expr cont
SAF_Out -> simplOutExpr env expr cont
SAF_In -> simplExprF env expr cont
-simplAltExprC :: (SimplAltFlag, SimplEnv) -> CoreExpr -> SimplCont -> SimplM OutExpr
-simplAltExprC env expr cont
- = do { (floats, expr') <- simplAltExprF env expr cont
- ; return (wrapFloats floats expr') }
-
{- Note [Case binder evaluated-ness]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -3854,48 +4046,69 @@ All this should happen in one sweep.
Note [FloatBinds from constructor wrappers]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-If we have FloatBinds coming from the constructor wrapper
-(as in Note [exprIsConApp_maybe on data constructors with wrappers]),
-we cannot float past them. We'd need to float the FloatBind
-together with the simplify floats, unfortunately the
-simplifier doesn't have case-floats. The simplest thing we can
-do is to wrap all the floats here. The next iteration of the
-simplifier will take care of all these cases and lets.
+exprIsConApp_maybe may return FloatBinds, e.g. coming from a constructor
+wrapper (as in Note [exprIsConApp_maybe on data constructors with wrappers]),
+or from looking through lets and single-alternative cases in the scrutinee.
+These floats scope over the result of case-of-known-constructor.
+
+Since the Simplifier's floats can contain case-floats as well as let-floats
+(see Note [LetFloats] in GHC.Core.Opt.Simplify.Env), we simply add them to
+the SimplFloats, outside the floats from simplifying the alternative; see
+knownConCase_maybe. We do not wrap them around the result, because then a
+subsequent case-of-known-constructor on the result would have to walk
+through them all over again, which can be quadratic (#27737).
Given data T = MkT !Bool, this allows us to simplify
case $WMkT b of { MkT x -> f x }
to
case b of { b' -> f b' }.
-
-We could try and be more clever (like maybe `wfloats` only contains
-let binders, so we could float them). But the need for the extra
-complication is not clear.
-}
-wrapDataConFloats :: SimplEnv -> FloatBinds -> InId -> SimplCont
- -> SimplM (SimplFloats, OutExpr)
- -> SimplM (SimplFloats, OutExpr)
--- See Note [FloatBinds from constructor wrappers]
-wrapDataConFloats env wfloats case_bndr cont thing_inside
- | isEmptyFloatBinds wfloats
- = thing_inside
- | otherwise
- = do { (floats, expr) <- thing_inside
- ; return ( emptyFloats env
- , GHC.Core.Make.wrapFloats (fmap scale_float wfloats) $
- wrapFloats floats expr ) }
- where
- -- scale_float scales case-floats by the multiplicity of the continuation hole
- -- (see Note [Scaling in case-of-case]).
- -- Let floats are _not_ scaled, because they are aliases anyway.
- scale_float (GHC.Core.FloatCase scrut case_bndr con vars)
- = GHC.Core.FloatCase scrut (scale_id case_bndr) con (map scale_id vars)
- scale_float flt@(GHC.Core.FloatLet {}) = flt
- scale_float flt@(GHC.Core.FloatTick {}) = flt
+knownConCase_maybe :: (SimplAltFlag, SimplEnv)
+ -> OutExpr -- Scrutinee
+ -> InId -- Case binder
+ -> [InAlt] -- Alternatives (increasing order)
+ -> SimplCont
+ -> Maybe (SimplM (SimplFloats, OutExpr))
+-- Case-of-known-constructor: returns Just if the scrutinee is a literal
+-- or (via exprIsConApp_maybe) a constructor application
+knownConCase_maybe (saf,env) scrut case_bndr alts cont
+ | Lit lit <- scrut -- No need for same treatment as constructors
+ -- because literals are inlined more vigorously
+ , not (litIsLifted lit)
+ = Just $
+ do { tick (KnownBranch case_bndr)
+ ; case findAlt (LitAlt lit) alts of
+ Nothing -> missingAlt env case_bndr alts cont
+ Just (Alt _ bs rhs) -> simpl_rhs env scrut bs rhs }
- scale_id id = scaleVarBy holeScaling id
+ | Just (in_scope', wfloats, con, ty_args, other_args)
+ <- exprIsConApp_maybe (getUnfoldingInRuleMatch env) scrut
+ -- Works when the scrutinee is a variable with a known unfolding
+ -- as well as when it's an explicit constructor application
+ , let env0 = setInScopeSet env in_scope'
+ = Just $
+ do { tick (KnownBranch case_bndr)
+ ; let -- case_bndr_unf: see Note [Do not duplicate constructor applications]
+ case_bndr_rhs | exprIsTrivial scrut = scrut
+ | otherwise = con_app
+ con_app = Var (dataConWorkId con) `mkTyApps` ty_args
+ `mkApps` other_args
+ -- The wfloats scope over the result
+ -- See Note [FloatBinds from constructor wrappers]
+ ; addFloatBinds hole_scaling wfloats $
+ case findAlt (DataAlt con) alts of
+ Nothing -> missingAlt env0 case_bndr alts cont
+ Just (Alt DEFAULT bs rhs) -> simpl_rhs env0 case_bndr_rhs bs rhs
+ Just (Alt _ bs rhs) -> knownCon env0 scrut con other_args
+ case_bndr bs rhs cont }
- holeScaling = contHoleScaling cont `mkMultMul` idMult case_bndr
+ | otherwise
+ = Nothing
+ where
+ hole_scaling = idMult case_bndr `mkMultMul` contHoleScaling cont
+ -- See Note [Scaling in case-of-case]
+ -- This is the contHoleScaling of the original Select continuation
-- We are in the following situation
-- case[p] case[q] u of { D x -> C v } of { C x -> w }
-- And we are producing case[??] u of { D x -> w[x\v]}
@@ -3911,6 +4124,33 @@ wrapDataConFloats env wfloats case_bndr cont thing_inside
-- Which is ill-typed with respect to linearity. So it needs to be a
-- case[Many].
+ simpl_rhs env case_bndr_rhs bs rhs
+ = assert (null bs) $
+ do { (floats1, env') <- simplAuxBind (saf,env) case_bndr case_bndr_rhs
+ -- scrut is a constructor application,
+ -- hence satisfies let-can-float invariant
+ ; (floats2, expr') <- simplExprF env' rhs cont
+ ; return (floats1 `addFloats` floats2, expr') }
+
+addFloatBinds :: Mult -> FloatBinds
+ -> SimplM (SimplFloats, a) -> SimplM (SimplFloats, a)
+-- (addFloatBinds scaling fbs thing_inside) adds `fbs` outside the floats
+-- returned by `thing_inside`. The `scaling` is the multiplicity of the
+-- continuation hole, by which case-floats are scaled, because they now
+-- scope over that continuation: see Note [Scaling in case-of-case].
+-- Let floats do not need this treatment
+addFloatBinds scaling fbs thing_inside
+ | isEmptyFloatBinds fbs -- Short cut
+ = thing_inside
+ | otherwise
+ = do { (floats, res) <- thing_inside
+ ; return (fmap scale_float fbs `addFloatBindsF` floats, res) }
+ where
+ scale_float (FloatCase scrut b con vars)
+ = FloatCase scrut (scale_id b) con (map scale_id vars)
+ scale_float flt = flt
+
+ scale_id id = scaleVarBy scaling id
knownCon :: SimplEnv
-> OutExpr -- The scrutinee
@@ -4149,8 +4389,8 @@ mkDupableContWithDmds env _
-- No need to use mkDupableCont before simplNonRecBody; we
-- use cont once here, and then share the result if necessary
- ; let join_body = wrapFloats floats1 join_inner
- res_ty = contResultType cont
+ ; let res_ty = contResultType cont
+ ; join_body <- simplWrapFloats (seMode env) floats1 join_inner res_ty
; mkDupableStrictBind env bndr' join_body res_ty }
@@ -4185,7 +4425,8 @@ mkDupableContWithDmds env _
; arg_bndr <- newId (fsLit "arg") m arg_ty
; let env' = env `addNewInScopeIds` [arg_bndr]
; (floats, join_rhs) <- rebuildCall env' (addValArgTo fun (Var arg_bndr) fun_ty) cont
- ; mkDupableStrictBind env' arg_bndr (wrapFloats floats join_rhs) rhs_ty }
+ ; join_rhs' <- simplWrapFloats (seMode env) floats join_rhs rhs_ty
+ ; mkDupableStrictBind env' arg_bndr join_rhs' rhs_ty }
where
thumbsUpPlanA (StrictArg {}) = False
thumbsUpPlanA (StrictBind {}) = True
@@ -4244,7 +4485,7 @@ mkDupableContWithDmds env _
scaleIdBy cont_scaling case_bndr
; alts' <- forM (scaleAltsBy cont_scaling alts) $
- simplAlt (saf,alt_env1) Nothing [] case_bndr' NoBinderSwap alt_cont
+ simplAltC (saf,alt_env1) Nothing [] case_bndr' NoBinderSwap alt_cont
-- Safe to say that there are no handled-cons for the DEFAULT case
-- NB: simplBinder does not zap deadness occ-info, so
-- a dead case_bndr' will still advertise its deadness
=====================================
compiler/GHC/Core/Opt/Simplify/Utils.hs
=====================================
@@ -8,7 +8,7 @@ The simplifier utilities
module GHC.Core.Opt.Simplify.Utils (
-- Rebuilding
- rebuildLam, mkCase, prepareAlts,
+ rebuildLam, mkCase, returnCase, prepareAlts, simplWrapFloats,
tryEtaExpandRhs, wantEtaExpansion,
-- Inlining,
@@ -28,7 +28,7 @@ module GHC.Core.Opt.Simplify.Utils (
contIsTrivial, contArgs, contIsRhs, mkBottomCont,
hasArgs, countArgs, contOutArgs, dropContArgs,
mkBoringStop, mkRhsStop, mkLazyArgStop,
- interestingCallContext,
+ interestingCallContext, splitContArgs,
-- ArgInfo
ArgInfo(..), ArgSpec(..), RemainingArgDmds, mkArgInfo,
@@ -74,12 +74,13 @@ import GHC.Types.InlinePragma
import GHC.Types.Tickish
import GHC.Types.Demand
import GHC.Types.Var.Set
+import GHC.Types.Var.Env ( InScopeSet )
import GHC.Types.Basic
import GHC.Types.Name.Env
import GHC.Data.List.Infinite ( Infinite(..) )
import qualified GHC.Data.List.Infinite as Inf
-import GHC.Data.OrdList ( isNilOL )
+import GHC.Data.OrdList ( fromOL )
import GHC.Data.FastString ( fsLit )
import GHC.Utils.Misc
@@ -173,10 +174,11 @@ data SimplCont
, sc_opt :: Bool -- True <=> sc_co has had optCoercion applied to it
-- See Note [Avoid re-simplifying coercions]
-- in GHC.Core.Opt.Simplify.Iteration
- , sc_cont :: SimplCont }
+ , sc_cont :: SimplCont } -- Invariant: never a CastIt; successive casts
+ -- are merged (see pushCast in GHC.Core.Opt.Simplify.Iteration)
| ApplyToVal -- (ApplyToVal arg K)[e] = K[ e arg ]
- { sc_hole_ty :: OutType -- Type of the function, presumably (forall a. blah)
+ { sc_hole_ty :: OutType -- Type of the function, presumably (ty1 -> ty2)
-- See Note [The hole type in ApplyToTy]
, sc_env :: StaticEnv -- See Note [StaticEnv]
, sc_arg :: CoreExpr -- The argument
@@ -495,12 +497,54 @@ contIsDupable :: SimplCont -> Bool
contIsDupable (Stop {}) = True
contIsDupable (ApplyToTy { sc_cont = k }) = contIsDupable k
contIsDupable (ApplyToVal { sc_env = se }) = okToDupSE se -- See (SE1) in Note [StaticEnv]
-contIsDupable (Select { sc_env = se }) = okToDupSE se -- ...ditto...
+contIsDupable (Select { sc_env = se, sc_bndr = bndr, sc_alts = alts, sc_cont = k })
+ = okToDupSE se -- ...ditto...
+ || (isUnpackingAlts bndr alts && contIsDupable k)
+ -- See Note [Duplicating unpacking continuations]
contIsDupable (StrictBind { sc_env = se }) = okToDupSE se -- ...ditto...
contIsDupable (StrictArg { sc_dup = dup }) = okToDup dup -- ...ditto...
contIsDupable (CastIt { sc_cont = k }) = contIsDupable k
contIsDupable (TickIt _ k) = contIsDupable k
+isUnpackingAlts :: InId -> [InAlt] -> Bool
+-- True of the alternatives of case e of b { K x y -> y }
+-- and nested versions thereof; see Note [Duplicating unpacking continuations]
+isUnpackingAlts case_bndr [Alt _ bndrs rhs] = go (case_bndr : bndrs) rhs
+ where
+ go bound (Var v) = v `elem` bound
+ go bound (Case (Var v) b _ [Alt _ bs rhs])
+ | v `elem` bound = go (b : bs ++ bound) rhs
+ go _ _ = False
+isUnpackingAlts _ _ = False
+
+{- Note [Duplicating unpacking continuations]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Worker/wrapper for CPR produces a worker like this
+ $wf = \ds -> case (case ds of { A -> R e1; B -> R e2 }) of ww { __DEFAULT ->
+ case ww of { R y -> y } }
+The intention is that the unboxing (case . of R y -> y) cancels with the boxing
+(R e1) and (R e2). But the continuation pushed into the inner case is
+ (Select ww [__DEFAULT -> case ww of { R y -> y }])
+which has more than one alternative to go into, so mkDupableCont would make it
+dupable by creating a join point
+ join $j ww = case ww of { __DEFAULT -> case ww of { R y -> y } }
+ in case ds of { A -> jump $j (R e1); B -> jump $j (R e2) }
+That is terrible if $j fails to inline; and even if it does inline, it takes an
+extra Simplifier iteration to tidy up (T15304).
+
+So contIsDupable treats a Select as dupable if its alternatives are "unpacking
+alternatives": a single alternative whose RHS is a variable bound by that
+alternative (a pattern variable or the case binder), or a single-alternative case
+on such a variable whose own RHS is again unpacking, and so on (to allow for nested
+CPR). Such a continuation is tiny, so duplicating it costs nothing, and then
+case-of-known-constructor cancels it with the constructor in each branch, giving
+ $wf = \ds -> case ds of { A -> e1; B -> e2 }
+
+We insist that the variables are /bound/ by the continuation: a free variable might
+be mapped by the substitution in the (UnSimplified env) to a big expression, which
+we would then duplicate.
+-}
+
-------------------
contIsTrivial :: SimplCont -> Bool
contIsTrivial (Stop {}) = True
@@ -632,6 +676,65 @@ contOutArgs env cont
-- No more arguments
go _ = []
+splitContArgs :: SimplCont -> Maybe (SimplCont, SimplCont)
+-- Splits `cont` into (inner, outer), where `inner` has only
+-- applications and casts, and `outer` is non-trivial
+-- A cast goes in `inner` only if it is followed by an application;
+-- see Note [Do not push a cast inwards unnecessarily]
+splitContArgs cont@(ApplyToTy { sc_cont = cont1 })
+ = do { (inner, outer) <- splitContArgs cont1
+ ; return (cont { sc_cont = inner }, outer) }
+splitContArgs cont@(ApplyToVal { sc_cont = cont1 })
+ = do { (inner, outer) <- splitContArgs cont1
+ ; return (cont { sc_cont = inner }, outer) }
+splitContArgs cont@(CastIt { sc_cont = cont1 })
+ | isAppCont cont1 -- No need for isAppCont to look past a CastIt, because
+ -- cont1 is never a CastIt; see the invariant on CastIt
+ = do { (inner, outer) <- splitContArgs cont1
+ ; return (cont { sc_cont = inner }, outer) }
+splitContArgs outer
+ | contIsStop outer = Nothing
+ | otherwise = -- pprTrace "splitContHoleType" (ppr hole_ty) $
+ return (mkBoringStop hole_ty, outer)
+ where
+ hole_ty = contHoleType outer
+
+isAppCont :: SimplCont -> Bool
+-- True of an application continuation
+isAppCont (ApplyToVal {}) = True
+isAppCont (ApplyToTy {}) = True
+isAppCont _ = False
+
+{- Note [Do not push a cast inwards unnecessarily]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+When case-of-case is off, splitContArgs splits the continuation into an `inner`
+part, which we push into a `case` or `let`, and an `outer` part, which we
+rebuild around the result. The point of `inner` is to push applications
+inwards, so it should stop as soon as it can. So a cast goes in `inner` only
+if it is followed by an application, e.g. (CastIt (ApplyToVal ..)); otherwise,
+e.g. (CastIt Stop) or (CastIt (Select ..)), the cast goes in `outer`.
+(Successive casts are merged, so we need not look past a CastIt.) Consider
+ f x = Wrap (case x of { 0 -> g 10; 1 -> g 20; _ -> g 30 })
+where Wrap is a newtype constructor, so we have a cast round the case.
+If we pushed the cast into the alternatives we would get
+ f = \x -> case x of { 0 -> g 10 |> co; 1 -> g 20 |> co; _ -> g 30 |> co }
+Then
+ * We duplicate the coercion in every alternative. The coercion can be big:
+ for a derived Generic instance, `from` has one alternative per constructor
+ and the coercion mentions the whole representation type, so the total is
+ quadratic (T5642, T16577).
+ * We lose cast worker/wrapper: the RHS is no longer of form (e |> co), so
+ we never get f = $wf |> co. And nothing ever moves the casts back out
+ of the alternatives, so the duplication lasts all the way to CorePrep.
+
+Leaving the cast in `outer` gives
+ f = \x -> (case x of { 0 -> g 10; 1 -> g 20; _ -> g 30 }) |> co
+We do this for every caller of splitContArgs, including a `let` with join
+points: if we pushed the cast into a join point's RHS we would have to push
+it into every jump too, but the jumps may be in a multi-alternative case
+from which we are keeping it out.
+-}
+
dropContArgs :: FullArgCount -> SimplCont -> SimplCont
dropContArgs 0 cont = cont
dropContArgs n (ApplyToTy { sc_cont = cont }) = dropContArgs (n-1) cont
@@ -2408,7 +2511,7 @@ new binding is abstracted. Several points worth noting
(Why is it OK to float the unlifted `foo` there?
See Note [Core top-level string literals] in GHC.Core;
- it is controlled by GHC.Core.Opt.Simplify.Env.unitLetFloat.)
+ it is controlled by GHC.Core.Opt.Simplify.Env.getFF_Let.)
It is also necessary to do dependency analysis, because
otherwise (in #24551) we might get `foo = \@_ -> "missing"#` at the
@@ -2416,18 +2519,20 @@ new binding is abstracted. Several points worth noting
manifestly a literal string.
-}
-abstractFloats :: UnfoldingOpts -> TopLevelFlag -> [OutTyVar] -> SimplFloats
- -> OutExpr -> SimplM ([OutBind], OutExpr)
-abstractFloats uf_opts top_lvl main_tvs floats body
+abstractFloats :: UnfoldingOpts -> TopLevelFlag -> [OutTyVar]
+ -> InScopeSet -- Includes the binders of the LetFloats
+ -> LetFloats -- Let-bindings only: see (PB1) in Note [prepareBinding]
+ -- in GHC.Core.Opt.Simplify.Iteration
+ -> OutExpr -> SimplM ([OutBind], OutExpr)
+abstractFloats uf_opts top_lvl main_tvs in_scope floats body
= assert (notNull body_floats) $
- assert (isNilOL (sfJoinFloats floats)) $
do { let sccs = concatMap to_sccs body_floats
; (subst, float_binds) <- mapAccumLM abstract empty_subst sccs
; return (float_binds, GHC.Core.Subst.substExpr subst body) }
where
is_top_lvl = isTopLevel top_lvl
- body_floats = letFloatBinds (sfLetFloats floats)
- empty_subst = GHC.Core.Subst.mkEmptySubst (sfInScope floats)
+ body_floats = fromOL floats
+ empty_subst = GHC.Core.Subst.mkEmptySubst in_scope
-- See wrinkle (AB5) in Note [Which type variables to abstract over]
-- for why we need to re-do dependency analysis
@@ -2862,7 +2967,64 @@ and now we can do case-merge again, getting the desired
-}
-mkCase, mkCase1, mkCase2, mkCase3
+simplWrapFloats :: SimplMode -> SimplFloats
+ -> OutExpr -- The body
+ -> OutType -- The type of the body
+ -> SimplM OutExpr
+-- Wrap the floats around the body, using mkCase for case-floats
+-- See Note [Wrapping case-floats with mkCase]
+simplWrapFloats mode (SimplFloats { sfLetFloats = lfs, sfJoinFloats = jbs }) body body_ty
+ = go (fromOL lfs)
+ where
+ go [] = return (wrapJoinFloats jbs body)
+ -- Always safe to put the joins on the inside,
+ -- since the values can't refer to them
+ go (fb : fbs) = do { body' <- go fbs; wrap fb body' }
+
+ wrap (FloatLet bind) body = return (Let bind body)
+ wrap (FloatTick t) body = return (mkTick t body)
+ wrap (FloatCase scrut bndr con bs) body
+ = mkCase mode scrut bndr body_ty [Alt con bs body]
+ -- NB: we must not force body_ty if there are no case-floats; that can
+ -- do a lot of unnecessary work. mkCase forces it when it builds the Case;
+ -- see Note [Avoiding space leaks in OutType] in GHC.Core.Opt.Simplify.Iteration
+ -- body_ty: lets, ticks and cases do not change the type, so every
+ -- case-float has the same result type: the type of the original body.
+ -- And body_ty comes from outside, so it cannot mention `bs`
+
+{- Note [Wrapping case-floats with mkCase]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+The Simplifier returns a single-alternative case as a FloatCase, rather than
+building it with mkCase; see Note [Floating single-alternative cases] in
+GHC.Core.Opt.Simplify.Iteration. So when we eventually wrap the floats around
+an expression, simplWrapFloats uses mkCase for each FloatCase, so that we get
+all the things that mkCase does: case-merging, identity-case elimination,
+caseRules, etc. For example, case-merging turns
+ case x of b { DEFAULT -> case b of { A -> e1; B -> e2 } }
+into case x of b { A -> e1; B -> e2 }
+which arises, for example, from x `seq` case x of { A -> e1; B -> e2 }.
+
+Is the case-merging expensive? mergeCaseAlts looks past lets (wrinkle (MC4) of
+Note [Merge Nested Cases] in GHC.Core.Utils), but it stops at anything else,
+such as a case that does not scrutinise the case binder. So in a chain
+ FloatCase e1 b1, lets1, FloatCase e2 b2, lets2, ...
+each let is examined by only one FloatCase, and the total cost is linear.
+
+It could be quadratic if successive FloatCases evaluated the /same/ value:
+ FloatCase e b1, FloatCase b1 b2, FloatCase b2 b3, lots of lets, case b3 of alts
+Then each FloatCase merges with the case below it, floating the lets out again,
+so that the next one looks past all of them again. But such a chain does not
+survive simplification: a case whose scrutinee is already evaluated (such as
+the case binder b1 of an enclosing case) is eliminated by rebuildCase (see
+Note [Case to let transformation] in GHC.Core.Opt.Simplify.Iteration) long before
+it becomes a FloatCase. (Calling mkCase on every case, as we used to, has
+exactly the same theoretical exposure.)
+
+We do not use simplWrapFloats for the FloatBinds returned by the rule matcher;
+GHC.Core.Make.wrapFloats is fine for those.
+-}
+
+mkCase, mkCase1, mkCase2
:: SimplMode
-> OutExpr -> OutId
-> OutType -> [OutAlt] -- Alternatives in standard (increasing) order
@@ -2957,12 +3119,12 @@ mkCase2 mode scrut bndr alts_ty alts
-- See Note [Unreachable caseRules alternatives]
-- in GHC.Core.Opt.ConstantFold
- ; mkCase3 mode scrut' bndr' alts_ty $
+ ; returnCase scrut' bndr' alts_ty $
add_default (re_sort alts')
}
| otherwise
- = mkCase3 mode scrut bndr alts_ty alts
+ = returnCase scrut bndr alts_ty alts
where
-- We need to keep the correct association between the scrutinee and its
-- binder if the latter isn't dead. Hence we wrap rhs of alternatives with
@@ -3039,8 +3201,12 @@ in GHC.Core.Opt.ConstantFold)
--------------------------------------------------
-- Catch-all
--------------------------------------------------
-mkCase3 _mode scrut bndr alts_ty alts
- = return (Case scrut bndr alts_ty alts)
+returnCase :: OutExpr -> OutId -> OutType -> [OutAlt] -> SimplM OutExpr
+-- Build the Case, forcing alts_ty as we emit it into the output program
+-- See Note [Avoiding space leaks in OutType] in GHC.Core.Opt.Simplify.Iteration
+returnCase scrut bndr alts_ty alts
+ = seqType alts_ty `seq`
+ return (Case scrut bndr alts_ty alts)
-- See Note [Exitification] and Note [Do not inline exit join points] in
-- GHC.Core.Opt.Exitify
=====================================
compiler/GHC/Core/SimpleOpt.hs
=====================================
@@ -11,7 +11,7 @@ module GHC.Core.SimpleOpt (
simpleOptPgm, simpleOptExpr, simpleOptExprNoInline, simpleOptExprWith,
-- ** Join points
- joinPointBinding_maybe, joinPointBindings_maybe,
+ joinPointBinding_maybe, joinPointBindings_maybe, joinPointBind_maybe,
-- ** Predicates on expressions
exprIsConApp_maybe, exprIsLiteral_maybe, exprIsLambda_maybe,
@@ -1199,6 +1199,18 @@ joinPointBindings_maybe :: [(InBndr, InExpr)] -> Maybe [(InBndr, InExpr)]
joinPointBindings_maybe bndrs
= mapM (uncurry joinPointBinding_maybe) bndrs
+joinPointBind_maybe :: InBind -> Maybe InBind
+joinPointBind_maybe (NonRec bndr rhs)
+ | Just (bndr', rhs') <- joinPointBinding_maybe bndr rhs
+ = Just (NonRec bndr' rhs')
+
+joinPointBind_maybe (Rec pairs)
+ | Just pairs' <- joinPointBindings_maybe pairs
+ = Just (Rec pairs')
+
+joinPointBind_maybe _other
+ = Nothing
+
{- Note [JoinId vs TailCallInfo]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Occurrence information is /fundamentally fragile/; that is, it may
@@ -1542,7 +1554,8 @@ exprIsConApp_maybe :: HasDebugCallStack
=> InScopeEnv -> CoreExpr
-> Maybe (InScopeSet, FloatBinds, DataCon, [Type], [CoreExpr])
exprIsConApp_maybe ise@(ISE in_scope id_unf) expr
- = go (Left in_scope) emptyFloatBinds expr (CC [] MRefl)
+ = -- pprTrace "exprIsConApp" (ppr expr) $
+ go (Left in_scope) emptyFloatBinds expr (CC [] MRefl)
where
go :: Either InScopeSet Subst
-- Left in-scope means "empty substitution"
@@ -1655,7 +1668,8 @@ exprIsConApp_maybe ise@(ISE in_scope id_unf) expr
| idArity fun == 0
, Just rhs <- expandUnfolding_maybe unfolding
, let in_scope' = extend_in_scope (exprFreeVars rhs)
- = go (Left in_scope') floats rhs cont
+ = -- pprTrace "exprIsConApp:unf" (ppr fun <+> ppr rhs) $
+ go (Left in_scope') floats rhs cont
-- See Note [exprIsConApp_maybe on literal strings]
| (fun `hasKey` unpackCStringIdKey) ||
@@ -1695,17 +1709,21 @@ exprIsConApp_maybe ise@(ISE in_scope id_unf) expr
subst_co (Right s) co = GHC.Core.Subst.substCo s co
subst_expr (Left {}) e = e
- subst_expr (Right s) e = substExpr s e
+ subst_expr (Right s) e = -- pprTrace "subst_expr" (text "subst" <+> ppr s $$ text "expr" <+> ppr e) $
+ substExpr s e
- subst_bndr msubst bndr
- = (Right subst', bndr')
+ subst_bndrs subst bs = mapAccumL subst_bndr subst bs
+
+ subst_bndr (Left in_scope) bndr
+ | bndr `elemInScopeSet` in_scope = subst_bndr1 (mkEmptySubst in_scope) bndr
+ | otherwise = (Left (in_scope `extendInScopeSet` bndr), bndr)
+ subst_bndr (Right subst) bndr = subst_bndr1 subst bndr
+
+ subst_bndr1 subst bndr
+ = -- pprTrace "subst_bndr1" (ppr bndr <+> ppr bndr' $$ ppr subst) $
+ (Right subst', bndr')
where
(subst', bndr') = substBndr subst bndr
- subst = case msubst of
- Left in_scope -> mkEmptySubst in_scope
- Right subst -> subst
-
- subst_bndrs subst bs = mapAccumL subst_bndr subst bs
extend (Left in_scope) v e = Right (extendSubst (mkEmptySubst in_scope) v e)
extend (Right s) v e = Right (extendSubst s v e)
=====================================
compiler/GHC/Core/Type.hs
=====================================
@@ -55,7 +55,7 @@ module GHC.Core.Type (
splitForAllForAllTyBinders, splitForAllForAllTyBinder_maybe,
splitForAllTyCoVar_maybe, splitForAllTyCoVar,
splitForAllTyVar_maybe, splitForAllCoVar_maybe,
- splitPiTy_maybe, splitPiTy, splitPiTys, collectPiTyBinders,
+ splitPiTy_maybe, splitPiTy, splitPiTys, splitUninstantiatedValArgTys,
getRuntimeArgTys,
mkTyConBindersPreferAnon,
mkPiTy, mkPiTys,
@@ -263,7 +263,6 @@ import GHC.Utils.Monad.StrictReader
import GHC.Data.FastString
import GHC.Data.Maybe ( orElse, isJust )
-import GHC.List (build)
-- $type_classification
-- #type_classification#
@@ -1599,17 +1598,20 @@ splitPiTys ty = split ty ty []
split orig_ty ty bs | Just ty' <- coreView ty = split orig_ty ty' bs
split orig_ty _ bs = (reverse bs, orig_ty)
-collectPiTyBinders :: Type -> [PiTyBinder]
-collectPiTyBinders ty = build $ \c n ->
- let
- split (ForAllTy b res) = Named b `c` split res
- split (FunTy { ft_af = af, ft_mult = w, ft_arg = arg, ft_res = res })
- = Anon (Scaled w arg) af `c` split res
- split ty | Just ty' <- coreView ty = split ty'
- split _ = n
- in
- split ty
-{-# INLINE collectPiTyBinders #-}
+splitUninstantiatedValArgTys :: Type -> [Type]
+-- This function takes a type apart, returning all its /value/
+-- argument types (including (forall (co::t1~t2).t)
+-- doing no instantiation at all.
+-- E.g. splitUinstantiatedValArgTys (forall a. a -> Int -> T a)
+-- returns [a, Int]
+-- It's a pretty specialised function, hence its long name
+splitUninstantiatedValArgTys ty = go ty
+ where
+ go (ForAllTy (Bndr b _) res) | isCoVar b = varType b : go res
+ | otherwise = go res
+ go (FunTy { ft_arg = arg, ft_res = res }) = arg : go res
+ go ty | Just ty' <- coreView ty = go ty'
+ go _ = []
-- | Extracts a list of run-time arguments from a function type,
-- looking through newtypes to the right of arrows.
=====================================
compiler/GHC/Core/Utils.hs
=====================================
@@ -804,6 +804,9 @@ mkSingleAltCase scrut case_bndr con bndrs body
body_ty = exprType body
case_ty -- See Note [Care with the type of a case expression]
+ | not (any isTyCoVar bndrs) -- Fast path: only TyCoVars can occur in body_ty
+ = body_ty
+
| Just body_ty' <- occCheckExpand bndrs body_ty
= body_ty'
@@ -2207,6 +2210,8 @@ fun_always_ok _ = True
-- | A special version of 'exprOkForSpeculation' used during
-- Note [Speculative evaluation]. When the predicate arg `fun_ok` returns False
-- for `b`, then `b` is never considered ok-for-spec.
+--
+-- This is the whole reason for the fun_ok arg to expr_ok.
exprOkForSpecEval :: (Id -> Bool) -> CoreExpr -> Bool
exprOkForSpecEval fun_ok = expr_ok fun_ok primOpOkForSpeculation
@@ -2240,10 +2245,9 @@ expr_ok fun_ok primop_ok (Case scrut bndr _ alts)
&& altsAreExhaustive alts
expr_ok fun_ok primop_ok other_expr
- | (expr, args) <- collectArgs other_expr
+ | (expr, val_args) <- collectValArgs other_expr
= case stripTicksTopE (not . tickishCounts) expr of
- Var f ->
- app_ok fun_ok primop_ok f args
+ Var f -> app_ok fun_ok primop_ok f val_args
-- 'LitRubbish' is the only literal that can occur in the head of an
-- application and will not be matched by the above case (Var /= Lit).
@@ -2258,9 +2262,10 @@ expr_ok fun_ok primop_ok other_expr
-----------------------------
app_ok :: (Id -> Bool) -> (PrimOp -> Bool) -> Id -> [CoreArg] -> Bool
-app_ok fun_ok primop_ok fun args
+app_ok fun_ok primop_ok fun val_args
| not (fun_ok fun)
- = False -- This code path is only taken for Note [Speculative evaluation]
+ = False -- This code path is only taken for exprOkForSpecEval
+ -- See Note [Speculative evaluation]
| idArity fun > n_val_args
-- Partial application: just check passing the arguments is OK
@@ -2281,17 +2286,18 @@ app_ok fun_ok primop_ok fun args
ClassOpId _ is_terminating_result
| is_terminating_result -- See Note [exprOkForSpeculation and type classes]
- -> assertPpr (n_val_args == 1) (ppr fun $$ ppr args) $
+ -> assertPpr (n_val_args == 1) (ppr fun $$ ppr val_args) $
True
-- assert: terminating result type => can't be applied;
-- c.f the _other case below
PrimOpId op _
| primOpIsDiv op
- , Lit divisor <- last args
+ , Lit divisor <- last val_args
-- there can be 2 args (most div primops) or 3 args
-- (WordQuotRem2Op), hence the use of last/init
- -> not (isZeroLit divisor) && all (expr_ok fun_ok primop_ok) (init args)
+ -> not (isZeroLit divisor) &&
+ all ok_for_spec (init val_args)
-- Special case for dividing operations that fail
-- In general they are NOT ok-for-speculation
-- (which primop_ok will catch), but they ARE OK
@@ -2300,12 +2306,14 @@ app_ok fun_ok primop_ok fun args
-- can get rid of a thunk in an inner loop
| otherwise -> primop_ok op && args_ok
+ -- Assumes that the primop does not evaluate its
+ -- definitely-lifted arguments
_other -- Unlifted and terminating types;
-- Also c.f. the Var case of exprIsHNF
| isTerminatingType fun_ty -- See Note [exprOkForSpeculation and type classes]
|| definitelyUnliftedType fun_ty
- -> assertPpr (n_val_args == 0) (ppr fun $$ ppr args)
+ -> assertPpr (n_val_args == 0) (ppr fun $$ ppr val_args)
True -- Both terminating types (e.g. Eq a), and unlifted types (e.g. Int#)
-- are non-functions and so will have no value args. The assert is
-- just to check this.
@@ -2321,32 +2329,43 @@ app_ok fun_ok primop_ok fun args
-- for evaluated-ness of the fun;
-- see Note [exprOkForSpeculation and evaluated variables]
where
- fun_ty = idType fun
- n_val_args = valArgCount args
- (arg_tys, _) = splitPiTys fun_ty
+ ok_for_spec = expr_ok fun_ok primop_ok -- Used for recursive calls
+
+ fun_ty = idType fun
+ n_val_args = length val_args
+ val_arg_tys = splitUninstantiatedValArgTys fun_ty
+ -- val_arg_tys are /uninstantiated/; see (EOKS1)
-- Even if a function call itself is OK, any unlifted
-- args are still evaluated eagerly and must be checked
- args_ok = all2Prefix arg_ok arg_tys args
- arg_ok :: PiTyVarBinder -> CoreExpr -> Bool
- arg_ok (Named _) _ = True -- A type argument
- arg_ok (Anon ty _) arg -- A term argument
- | definitelyLiftedType (scaledThing ty)
- = True -- lifted args are not evaluated eagerly
- | otherwise
- = expr_ok fun_ok primop_ok arg
+ -- arg_ok bndr arg = field_ok bndr NotMarkedStrict arg
+ -- See Note [exprOkForSpeculation] (a,b)
+ args_ok = all2Prefix arg_ok val_arg_tys val_args
+ arg_ok :: Type -> CoreExpr -> Bool
+ arg_ok arg_ty arg = ok_for_spec arg || definitely_lifted arg_ty arg
-- Used for strict DataCon worker arguments
-- See (SFC1) of Note [Strict fields in Core]
- fields_ok str_marks = all3Prefix field_ok arg_tys str_marks args
- field_ok :: PiTyVarBinder -> StrictnessMark -> CoreExpr -> Bool
- field_ok (Named _) _ _ = True
- field_ok (Anon ty _) str arg
- | NotMarkedStrict <- str -- iff it's a lazy field
- , definitelyLiftedType (scaledThing ty) -- and its type is lifted
- = True -- then the worker app does not eval
- | otherwise
- = expr_ok fun_ok primop_ok arg
+ -- See Note [exprOkForSpeculation] (a,b)
+ fields_ok str_marks = all3Prefix field_ok val_arg_tys str_marks val_args
+ field_ok :: Type -> StrictnessMark -> CoreExpr -> Bool
+ field_ok arg_ty str arg
+ = ok_for_spec arg || (definitely_lifted arg_ty arg && str==NotMarkedStrict)
+ -- The (ok_for_spec arg) test works for /both/ for unlifted types, /and/
+ -- for lifted but strict fields. E.g. K (I# 3) is ok-for-spec,
+ -- even if K is strict
+
+ -- We want to see if the argument type is definitely lifted.
+ -- But consider
+ -- (#,#) @rep1 @rep2 @ty1 @ty2 arg1 arg2
+ -- We don't /instantiate/ the type of (#,#) (although we could) so we don't
+ -- know if the argument type is lifted or not. So we look at the type of
+ -- the /actual/ argument (it's usually a variable) instead.
+ definitely_lifted uninstantiated_arg_ty arg
+ = case typeLevity_maybe uninstantiated_arg_ty of
+ Just Lifted -> True
+ Just Unlifted -> False
+ Nothing -> definitelyLiftedType (exprType arg)
-----------------------------
altsAreExhaustive :: [Alt b] -> Bool
@@ -2390,8 +2409,42 @@ cantEtaReduceFun fun
-- Don't undersaturate StrictWorkerIds.
-- See Note [CBV Function Ids: overview] in GHC.Types.Id.Info.
-{- Note [exprOkForSpeculation and type classes]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+{- Note [exprOkForSpeculation]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Suppose we have
+ data T a = K !a Int# a
+
+Is the call (K e1 e2 e3) ok-for-speculation? Look at the arguments e1..e3,
+and their types. The call is ok-for-speculation if each argument satisfies
+`field_ok`, namely:
+ (a) (exprOkForSpeculation arg) holds, OR
+ (b) Arg type is definitely lifted and it is not marked strict
+
+For (a) we conservatively assume we are going to evaluate the argument.
+If it is ok-for-spec, then fine.
+
+But if the argument is of a lifted type, and not marked strict (notably by
+a data constructor) then (b) holds. For example
+ Just (reverse xs)
+is ok-for-spec. See (EOKS1) for the argument liftedness test.
+
+If we have a plain variable `x`, is that ok-for-spec? Not if it is lifted:
+it might be a thunk! Hence the (definitelyUnliftedType fun_ty) test.
+Remember, a naked variable `x` will land in `app_ok x []` with no arguments.
+See Note [exprOkForSpeculation and evaluated variables].
+
+(EOKS1) To get the lifted-ness or otherwise of the arguments we just look at the
+ /uninstantiated/ type of the data constructor or primop. We'd get better information
+ if we instantiated, but it's also more expensive. Example:
+ (#,#) :: forall r1 r2 (a::TYPE r1) (b::TYPE r2). a -> b -> (# a, b #)
+ If we have a call
+ (#,#) @LiftedRep @IntRep @Int @Int# 3 4#
+ then we could see accurate liftedness by instantiation, but we don't try.
+ Instead we get the actual type from (exprType arg). That could be expensive,
+ but it really only happens for unboxed tuples.
+
+Note [exprOkForSpeculation and type classes]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider (#22745, #15205)
\(d :: C a b). case eq_sel (sc_sel d) of
@@ -2674,8 +2727,7 @@ exprIsHNFlike is_con is_con_unf rubbish_lit_result e
-- PAP: Check unlifted val_args
args_hnf = all2Prefix check_arg val_arg_tys val_args
- fun_ty = idType id
- val_arg_tys = mapMaybe anonPiTyBinderType_maybe (collectPiTyBinders fun_ty)
+ val_arg_tys = splitUninstantiatedValArgTys (idType id)
-- val_arg_tys = map exprType val_args, but much less costly.
-- The obvious definition regresses T16577 by 30% so we don't do it.
@@ -2700,7 +2752,6 @@ exprIsHNFlike is_con is_con_unf rubbish_lit_result e
| otherwise
= Nothing
-
{-
Note [exprIsHNF Tick]
~~~~~~~~~~~~~~~~~~~~~
=====================================
compiler/GHC/Driver/Config/Core/Opt/Simplify.hs
=====================================
@@ -80,7 +80,7 @@ initGentleSimplMode :: DynFlags -> SimplMode
initGentleSimplMode dflags = (initSimplMode dflags InitialPhase "Gentle")
{ -- Don't do case-of-case transformations.
-- This makes full laziness work better
- -- See Note [Case-of-case and full laziness]
+ -- See Note [sm_case_case: switching off case continuations]
sm_case_case = False
}
@@ -90,37 +90,3 @@ floatEnable dflags =
(True, True) -> FloatEnabled
(True, False)-> FloatNestedOnly
(False, _) -> FloatDisabled
-
-
-{- Note [Case-of-case and full laziness]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Case-of-case can hide opportunities for let-floating (full laziness).
-For example
- rec { f = \y. case (expensive x) of (a,b) -> blah }
-We might hope to float the (expensive x) out of the \y-loop.
-But if we inline `expensive` we might get
- \y. case (case x of I# x' -> body) of (a,b) -> blah
-Now if we do case-of-case we get
- \y. case x if I# x2 ->
- case body of (a,b) -> blah
-
-Sadly, at this point `body` mentions `x2`, so we can't float it out of the
-\y-loop.
-
-Solution: don't do case-of-case in the "gentle" simplification phase that
-precedes the first float-out transformation. Implementation:
-
- * `sm_case_case` field in SimplMode
-
- * Consult `sm_case_case` (via `seCaseCase`) before doing case-of-case
- in GHC.Core.Opt.Simplify.Iteration.rebuildCall.
-
-Wrinkles
-
-* This applies equally to the case-of-runRW# transformation:
- case (runRW# (\s. body)) of (a,b) -> blah
- --->
- runRW# (\s. case body of (a,b) -> blah)
- Again, don't do this when `sm_case_case` is off. See #25055 for
- a motivating example.
--}
=====================================
testsuite/tests/dmdanal/should_compile/T20510.stderr
=====================================
@@ -1,7 +1,7 @@
==================== Exitification transformation ====================
Result size of Exitification transformation
- = {terms: 50, types: 22, coercions: 0, joins: 2/2}
+ = {terms: 33, types: 15, coercions: 0, joins: 2/2}
-- RHS size: {terms: 2, types: 0, coercions: 0, joins: 0/0}
lvl :: Int
@@ -11,7 +11,7 @@ lvl :: Int
Guidance=IF_ARGS [] 10 10}]
lvl = GHC.Internal.Types.I# 0#
--- RHS size: {terms: 32, types: 14, coercions: 0, joins: 2/2}
+-- RHS size: {terms: 29, types: 12, coercions: 0, joins: 2/2}
small :: Int -> Int
[LclIdX,
Arity=1,
@@ -22,7 +22,7 @@ small :: Int -> Int
Guidance=ALWAYS_IF(arity=1,unsat_ok=True,boring_ok=False)
Tmpl= \ (x [Dmd=S!P(SL)] :: Int) ->
joinrec {
- go [InlPrag=[2], Occ=T[2], Dmd=LC(S,C(1,!P(L)))]
+ go [InlPrag=[2], Occ=Many(T[2]), Dmd=LC(S,C(1,!P(L)))]
:: Int -> Int -> Int
[LclId[JoinId(2)(Nothing)],
Arity=2,
@@ -54,11 +54,11 @@ small :: Int -> Int
Guidance=IF_ARGS [0 51] 63 10}]
$wgo (ww [Occ=Once2] :: GHC.Internal.Prim.Int#)
(ww [Occ=Once1!, Dmd=SL] :: GHC.Internal.Prim.Int#)
- = case ww of ds {
+ = case ww of wild {
__DEFAULT ->
jump go
- (GHC.Internal.Types.I# (GHC.Internal.Prim.+# ww ds))
- (GHC.Internal.Types.I# (GHC.Internal.Prim.-# ds 1#));
+ (GHC.Internal.Types.I# (GHC.Internal.Prim.+# ww wild))
+ (GHC.Internal.Types.I# (GHC.Internal.Prim.-# wild 1#));
0# ->
case x of { GHC.Internal.Types.I# y [Occ=Once1] ->
GHC.Internal.Types.I# (GHC.Internal.Prim.*# ww y)
@@ -67,13 +67,12 @@ small :: Int -> Int
jump go lvl x}]
small
= \ (x [Dmd=S!P(SL)] :: Int) ->
+ case x of { GHC.Internal.Types.I# ww [Dmd=SL] ->
join {
exit :: GHC.Internal.Prim.Int# -> Int
[LclId[JoinId(1)(Nothing)]]
exit (ww :: GHC.Internal.Prim.Int#)
- = case x of { GHC.Internal.Types.I# y ->
- GHC.Internal.Types.I# (GHC.Internal.Prim.*# ww y)
- } } in
+ = GHC.Internal.Types.I# (GHC.Internal.Prim.*# ww ww) } in
joinrec {
$wgo [InlPrag=[2], Occ=LoopBreaker]
:: GHC.Internal.Prim.Int# -> GHC.Internal.Prim.Int# -> Int
@@ -82,56 +81,17 @@ small
Str=<L><SL>,
Unf=Unf{Src=<vanilla>, TopLvl=False,
Value=True, ConLike=True, WorkFree=True, Expandable=True,
- Guidance=IF_ARGS [0 32] 43 10}]
+ Guidance=IF_ARGS [0 32] 33 10}]
$wgo (ww :: GHC.Internal.Prim.Int#)
(ww [Dmd=SL] :: GHC.Internal.Prim.Int#)
- = case ww of ds {
+ = case ww of wild {
__DEFAULT ->
jump $wgo
- (GHC.Internal.Prim.+# ww ds) (GHC.Internal.Prim.-# ds 1#);
+ (GHC.Internal.Prim.+# ww wild) (GHC.Internal.Prim.-# wild 1#);
0# -> jump exit ww
}; } in
- case x of { GHC.Internal.Types.I# ww [Dmd=SL] -> jump $wgo 0# ww }
-
--- RHS size: {terms: 1, types: 0, coercions: 0, joins: 0/0}
-$trModule :: GHC.Internal.Prim.Addr#
-[LclId,
- Unf=Unf{Src=<vanilla>, TopLvl=True,
- Value=True, ConLike=True, WorkFree=True, Expandable=True,
- Guidance=IF_ARGS [] 20 0}]
-$trModule = "main"#
-
--- RHS size: {terms: 2, types: 0, coercions: 0, joins: 0/0}
-$trModule :: GHC.Internal.Types.TrName
-[LclId,
- Unf=Unf{Src=<vanilla>, TopLvl=True,
- Value=True, ConLike=True, WorkFree=True, Expandable=True,
- Guidance=IF_ARGS [] 10 10}]
-$trModule = GHC.Internal.Types.TrNameS $trModule
-
--- RHS size: {terms: 1, types: 0, coercions: 0, joins: 0/0}
-$trModule :: GHC.Internal.Prim.Addr#
-[LclId,
- Unf=Unf{Src=<vanilla>, TopLvl=True,
- Value=True, ConLike=True, WorkFree=True, Expandable=True,
- Guidance=IF_ARGS [] 30 0}]
-$trModule = "T20510"#
-
--- RHS size: {terms: 2, types: 0, coercions: 0, joins: 0/0}
-$trModule :: GHC.Internal.Types.TrName
-[LclId,
- Unf=Unf{Src=<vanilla>, TopLvl=True,
- Value=True, ConLike=True, WorkFree=True, Expandable=True,
- Guidance=IF_ARGS [] 10 10}]
-$trModule = GHC.Internal.Types.TrNameS $trModule
-
--- RHS size: {terms: 3, types: 0, coercions: 0, joins: 0/0}
-T20510.$trModule :: GHC.Internal.Types.Module
-[LclIdX,
- Unf=Unf{Src=<vanilla>, TopLvl=True,
- Value=True, ConLike=True, WorkFree=True, Expandable=True,
- Guidance=IF_ARGS [] 10 10}]
-T20510.$trModule = GHC.Internal.Types.Module $trModule $trModule
+ jump $wgo 0# ww
+ }
=====================================
testsuite/tests/show-bytecode/show-bytecode-hpc.stdout
=====================================
@@ -59,135 +59,133 @@ objects:
arity: 0
literals: label ‘_hpc_tickboxes_Example_hpc’
used items: named item ‘primes’
- object ‘primes2_@name_suffix@’:
+ object ‘primes’:
arity: 0
- literals: label ‘_hpc_tickboxes_Example_hpc’
- used items:
- object ‘primes2_sat_@name_suffix@’:
- arity: 0
- literals: label ‘_hpc_tickboxes_Example_hpc’
- used items:
- object ‘primes2_sat_@name_suffix@’:
- arity: 0
- literals:
- label ‘_hpc_tickboxes_Example_hpc’
- word 3
- info table of ‘IS’
- used items:
- named item ‘$fNumNatural’
- named item ‘fromInteger’
- named item ‘$fEnumNatural’
- named item ‘enumFrom’
- object ‘primes2_sat_@name_suffix@’:
- arity: 0
- literals: label ‘_hpc_tickboxes_Example_hpc’
- used items: named item ‘isPrime_@name_suffix@’
- named item ‘filter’
- object ‘isPrime_@name_suffix@’:
- arity: 1
literals:
label ‘_hpc_tickboxes_Example_hpc’
+ info table of ‘(:)’
used items:
- object ‘isPrime_sat_@name_suffix@’:
+ object ‘isPrime_@name_suffix@’:
arity: 1
- literals: label ‘_hpc_tickboxes_Example_hpc’
+ literals:
+ label ‘_hpc_tickboxes_Example_hpc’
used items:
- object ‘isPrime_sat_@name_suffix@’:
+ object ‘isPrime_primes_sat_@name_suffix@’:
arity: 1
literals: label ‘_hpc_tickboxes_Example_hpc’
used items:
- object ‘isPrime_sat_@name_suffix@’:
- arity: 0
- literals: label ‘_hpc_tickboxes_Example_hpc’
- used items: named item ‘primes’
- object ‘isPrime_sat_@name_suffix@’:
+ object ‘isPrime_primes_sat_@name_suffix@’:
arity: 1
literals: label ‘_hpc_tickboxes_Example_hpc’
used items:
- object ‘isPrime_sat_@name_suffix@’:
+ object ‘isPrime_primes_sat_@name_suffix@’:
arity: 0
literals: label ‘_hpc_tickboxes_Example_hpc’
- used items:
- object ‘v_@name_suffix@’:
- arity: 0
- literals: label ‘_hpc_tickboxes_Example_hpc’
- used items:
- named item ‘$fIntegralInteger’
- named item ‘$fNumNatural’
- named item ‘(^)’
- object ‘v1_@name_suffix@’:
- arity: 0
- literals:
- label ‘_hpc_tickboxes_Example_hpc’
- word 2
- info table of ‘IS’
- used items: <none>
- object ‘pap_@name_suffix@’:
- arity: 3
- literals: <none>
- used items: <none>
- object ‘isPrime_sat_@name_suffix@’:
+ used items: named item ‘primes’
+ object ‘isPrime_primes_sat_@name_suffix@’:
arity: 1
literals: label ‘_hpc_tickboxes_Example_hpc’
used items:
- object ‘v_@name_suffix@’:
+ object ‘isPrime_primes_sat_@name_suffix@’:
arity: 0
literals: label ‘_hpc_tickboxes_Example_hpc’
used items:
- named item ‘$fOrdNatural’
- named item ‘(<=)’
- object ‘v1_@name_suffix@’:
+ object ‘v_@name_suffix@’:
+ arity: 0
+ literals: label ‘_hpc_tickboxes_Example_hpc’
+ used items:
+ named item ‘$fIntegralInteger’
+ named item ‘$fNumNatural’
+ named item ‘(^)’
+ object ‘v1_@name_suffix@’:
+ arity: 0
+ literals:
+ label ‘_hpc_tickboxes_Example_hpc’
+ word 2
+ info table of ‘IS’
+ used items: <none>
+ object ‘pap_@name_suffix@’:
+ arity: 3
+ literals: <none>
+ used items: <none>
+ object ‘isPrime_primes_sat_@name_suffix@’:
arity: 1
literals: label ‘_hpc_tickboxes_Example_hpc’
- used items: <none>
+ used items:
+ object ‘v_@name_suffix@’:
+ arity: 0
+ literals: label ‘_hpc_tickboxes_Example_hpc’
+ used items:
+ named item ‘$fOrdNatural’
+ named item ‘(<=)’
+ object ‘v1_@name_suffix@’:
+ arity: 1
+ literals: label ‘_hpc_tickboxes_Example_hpc’
+ used items: <none>
+ object ‘pap_@name_suffix@’:
+ arity: 3
+ literals: <none>
+ used items: <none>
+ named item ‘(.)’
+ named item ‘takeWhile’
+ object ‘isPrime_primes_sat_@name_suffix@’:
+ arity: 1
+ literals: label ‘_hpc_tickboxes_Example_hpc’
+ used items:
+ object ‘v_@name_suffix@’:
+ arity: 0
+ literals: label ‘_hpc_tickboxes_Example_hpc’
+ used items:
object ‘pap_@name_suffix@’:
- arity: 3
+ arity: 2
literals: <none>
- used items: <none>
- named item ‘(.)’
- named item ‘takeWhile’
- object ‘isPrime_sat_@name_suffix@’:
- arity: 1
+ used items:
+ named item ‘$fIntegralNatural’
+ named item ‘divides’
+ object ‘v1_@name_suffix@’:
+ arity: 1
+ literals: label ‘_hpc_tickboxes_Example_hpc’
+ used items: <none>
+ object ‘pap_@name_suffix@’:
+ arity: 3
+ literals: <none>
+ used items: <none>
+ named item ‘$fFoldableList’
+ named item ‘any’
+ named item ‘not’
+ object ‘primes_sat_@name_suffix@’:
+ arity: 1
+ literals: label ‘_hpc_tickboxes_Example_hpc’
+ used items:
+ object ‘primes_sat_@name_suffix@’:
+ arity: 0
literals: label ‘_hpc_tickboxes_Example_hpc’
used items:
- object ‘v_@name_suffix@’:
+ object ‘primes_sat_@name_suffix@’:
arity: 0
- literals: label ‘_hpc_tickboxes_Example_hpc’
+ literals:
+ label ‘_hpc_tickboxes_Example_hpc’
+ word 3
+ info table of ‘IS’
used items:
- object ‘pap_@name_suffix@’:
- arity: 2
- literals: <none>
- used items:
- named item ‘$fIntegralNatural’
- named item ‘divides’
- object ‘v1_@name_suffix@’:
- arity: 1
- literals: label ‘_hpc_tickboxes_Example_hpc’
- used items: <none>
- object ‘pap_@name_suffix@’:
- arity: 3
- literals: <none>
- used items: <none>
- named item ‘$fFoldableList’
- named item ‘any’
- named item ‘not’
- object ‘primes’:
- arity: 0
- literals:
- label ‘_hpc_tickboxes_Example_hpc’
- info table of ‘(:)’
- used items:
- named item ‘primes2_@name_suffix@’
- named item ‘primes1_@name_suffix@’
- object ‘primes1_@name_suffix@’:
- arity: 0
- literals:
- label ‘_hpc_tickboxes_Example_hpc’
- word 2
- info table of ‘IS’
- used items:
- named item ‘$fNumNatural’
- named item ‘fromInteger’
+ named item ‘$fNumNatural’
+ named item ‘fromInteger’
+ named item ‘$fEnumNatural’
+ named item ‘enumFrom’
+ object ‘primes_sat_@name_suffix@’:
+ arity: 1
+ literals: label ‘_hpc_tickboxes_Example_hpc’
+ used items: <none>
+ named item ‘filter’
+ object ‘primes_sat_@name_suffix@’:
+ arity: 0
+ literals:
+ label ‘_hpc_tickboxes_Example_hpc’
+ word 2
+ info table of ‘IS’
+ used items:
+ named item ‘$fNumNatural’
+ named item ‘fromInteger’
object ‘fibonaccisPtr’:
arity: 0
literals:
@@ -245,63 +243,59 @@ objects:
arity: 0
literals: label ‘_hpc_tickboxes_Example_hpc’
used items: named item ‘fibonaccis’
- object ‘positiveFibonaccis1_@name_suffix@’:
+ object ‘fibonaccis’:
arity: 0
literals:
label ‘_hpc_tickboxes_Example_hpc’
info table of ‘(:)’
used items:
- named item ‘positiveFibonaccis2_@name_suffix@’
- named item ‘positiveFibonaccis_@name_suffix@’
- object ‘positiveFibonaccis2_@name_suffix@’:
- arity: 0
- literals: label ‘_hpc_tickboxes_Example_hpc’
- used items:
- object ‘positiveFibonaccis2_sat_@name_suffix@’:
- arity: 0
- literals: label ‘_hpc_tickboxes_Example_hpc’
- used items: named item ‘positiveFibonaccis1_@name_suffix@’
- object ‘positiveFibonaccis2_sat_@name_suffix@’:
- arity: 0
+ object ‘positiveFibonaccis_@name_suffix@’:
+ arity: 1
+ literals:
+ label ‘_hpc_tickboxes_Example_hpc’
+ info table of ‘(:)’
+ used items:
+ object ‘positiveFibonaccis_fibonaccis_sat_@name_suffix@’:
+ arity: 1
+ literals: label ‘_hpc_tickboxes_Example_hpc’
+ used items:
+ object ‘positiveFibonaccis_fibonaccis_sat_@name_suffix@’:
+ arity: 1
+ literals: label ‘_hpc_tickboxes_Example_hpc’
+ used items: <none>
+ object ‘positiveFibonaccis_fibonaccis_sat_@name_suffix@’:
+ arity: 0
+ literals: label ‘_hpc_tickboxes_Example_hpc’
+ used items: named item ‘fibonaccis’
+ object ‘positiveFibonaccis_fibonaccis_sat_@name_suffix@’:
+ arity: 0
+ literals: label ‘_hpc_tickboxes_Example_hpc’
+ used items:
+ named item ‘$fNumNatural’
+ named item ‘(+)’
+ named item ‘zipWith’
+ object ‘positiveFibonaccis_fibonaccis_sat_@name_suffix@’:
+ arity: 0
+ literals:
+ label ‘_hpc_tickboxes_Example_hpc’
+ word 1
+ info table of ‘IS’
+ used items:
+ named item ‘$fNumNatural’
+ named item ‘fromInteger’
+ object ‘fibonaccis_sat_@name_suffix@’:
+ arity: 1
literals: label ‘_hpc_tickboxes_Example_hpc’
- used items: named item ‘fibonaccis’
- object ‘positiveFibonaccis2_sat_@name_suffix@’:
+ used items: <none>
+ object ‘fibonaccis_sat_@name_suffix@’:
arity: 0
- literals: label ‘_hpc_tickboxes_Example_hpc’
+ literals:
+ label ‘_hpc_tickboxes_Example_hpc’
+ word 0
+ info table of ‘IS’
used items:
named item ‘$fNumNatural’
- named item ‘(+)’
- named item ‘zipWith’
- object ‘fibonaccis’:
- arity: 0
- literals:
- label ‘_hpc_tickboxes_Example_hpc’
- info table of ‘(:)’
- used items:
- named item ‘fibonaccis2_@name_suffix@’
- named item ‘fibonaccis1_@name_suffix@’
- object ‘fibonaccis2_@name_suffix@’:
- arity: 0
- literals: label ‘_hpc_tickboxes_Example_hpc’
- used items: named item ‘positiveFibonaccis1_@name_suffix@’
- object ‘positiveFibonaccis_@name_suffix@’:
- arity: 0
- literals:
- label ‘_hpc_tickboxes_Example_hpc’
- word 1
- info table of ‘IS’
- used items:
- named item ‘$fNumNatural’
- named item ‘fromInteger’
- object ‘fibonaccis1_@name_suffix@’:
- arity: 0
- literals:
- label ‘_hpc_tickboxes_Example_hpc’
- word 0
- info table of ‘IS’
- used items:
- named item ‘$fNumNatural’
- named item ‘fromInteger’
+ named item ‘fromInteger’
object ‘$dTypeable2_@name_suffix@’:
arity: 0
literals: <none>
=====================================
testsuite/tests/simplCore/should_compile/T26903.stderr
=====================================
@@ -1,35 +1,42 @@
==================== Tidy Core ====================
Result size of Tidy Core
- = {terms: 127, types: 130, coercions: 48, joins: 0/0}
+ = {terms: 127, types: 130, coercions: 24, joins: 0/0}
$dmop
- = (\ @a _ $dOrd xs ys ->
- case $fOrdList_$ccompare $dOrd xs ys of {
- __DEFAULT ->
- reverse1 (reverse1 (reverse1 (reverse1 (++ xs ys) []) []) []) [];
- GT -> reverse1 (reverse1 (reverse1 (reverse xs) []) []) []
- })
- `cast` <Co:20> :: ...
+ = \ @a $dC $dOrd xs ys ->
+ case $fOrdList_$ccompare $dOrd xs ys of {
+ __DEFAULT ->
+ (reverse1 (reverse1 (reverse1 (reverse1 (++ xs ys) []) []) []) [])
+ `cast` <Co:3>;
+ GT ->
+ (reverse1 (reverse1 (reverse1 (reverse xs) []) []) [])
+ `cast` <Co:3>
+ }
$fCInt_$cop
- = (\ xs ys ->
- case $fOrdList_$s$ccompare xs ys of {
- __DEFAULT ->
- reverse1 (reverse1 (reverse1 (reverse1 (++ xs ys) []) []) []) [];
- GT -> reverse1 (reverse1 (reverse1 (reverse xs) []) []) []
- })
- `cast` <Co:11> :: ...
+ = \ xs ys ->
+ case $fOrdList_$s$ccompare xs ys of {
+ __DEFAULT ->
+ (reverse1 (reverse1 (reverse1 (reverse1 (++ xs ys) []) []) []) [])
+ `cast` <Co:3>;
+ GT ->
+ (reverse1 (reverse1 (reverse1 (reverse xs) []) []) [])
+ `cast` <Co:3>
+ }
$fCInt1
= \ xs ys ->
case $fOrdList_$s$ccompare xs ys of {
__DEFAULT ->
- reverse1 (reverse1 (reverse1 (reverse1 (++ xs ys) []) []) []) [];
- GT -> reverse1 (reverse1 (reverse1 (reverse xs) []) []) []
+ (reverse1 (reverse1 (reverse1 (reverse1 (++ xs ys) []) []) []) [])
+ `cast` <Co:3>;
+ GT ->
+ (reverse1 (reverse1 (reverse1 (reverse xs) []) []) [])
+ `cast` <Co:3>
}
-$fCInt = C:C ($fCInt1 `cast` <Co:11> :: ...)
+$fCInt = C:C $fCInt1
test4 = reverse1 [] []
@@ -44,8 +51,8 @@ test
case $fOrdList_$s$ccompare [] xs of {
__DEFAULT ->
(reverse1 (reverse1 (reverse1 (reverse1 (++ [] xs) []) []) []) [])
- `cast` <Co:3> :: ...;
- GT -> test1 `cast` <Co:3> :: ...
+ `cast` <Co:3>;
+ GT -> test1 `cast` <Co:3>
}
=====================================
testsuite/tests/simplCore/should_compile/T27737a.hs
=====================================
@@ -0,0 +1,23 @@
+{-# LANGUAGE NoMonoLocalBinds, MagicHash, UnboxedTuples #-}
+
+-- One of several regression tests arising from the work on #27737.
+--
+-- The Simplifier returns a single-alternative case as a case-float
+-- (FloatCase). Here the local binding
+-- g = /\a. case addIntC# x y of (# r, _ #) -> ([], I# r)
+-- is lazy, non-recursive and has a type lambda but no value lambda, so
+-- simplLazyBind strips off the /\a and simplifies the body. The case
+-- becomes a FloatCase; since addIntC# is ok-for-speculation, the float is
+-- FltOkSpec, which doFloatFromRhs allows out of a nested lazy binding.
+-- But then the floats must be abstracted over `a` (abstractFloats), which
+-- can only handle let-floats: at one stage the compiler panicked
+-- with "letFloatBinds".
+
+module T27737a where
+
+import GHC.Exts
+
+f :: Int -> Int -> ([Bool], [Char], Int)
+f (I# x) (I# y) = let g = case addIntC# x y of (# r, _ #) -> ([], I# r)
+ -- g :: forall a. ([a], Int)
+ in (fst g, fst g, snd g)
=====================================
testsuite/tests/simplCore/should_compile/T27910.hs
=====================================
@@ -0,0 +1,17 @@
+{-# LANGUAGE UnboxedTuples, MagicHash #-}
+module T27910 where
+import GHC.Exts
+
+k1 :: (# Int, Bool #) -> (# Int, Bool #) -> Int
+{-# NOINLINE k1 #-}
+k1 _ _ = 3
+
+k2 :: (# Int#, Int# #) -> (# Int#, Int# #) -> Int
+{-# NOINLINE k2 #-}
+k2 _ _ = 3
+
+lifted :: Int -> Bool -> Int
+lifted x y = case (# x, y #) of r -> k1 r r
+
+unlifted :: Int# -> Int# -> Int
+unlifted x y = case (# x, y #) of r -> k2 r r
=====================================
testsuite/tests/simplCore/should_compile/T27910.stderr
=====================================
@@ -0,0 +1,49 @@
+
+==================== FloatOut stats: ====================
+2 Lets floated to top level; 0 Lets floated elsewhere; from 4 Lambda groups
+
+
+
+==================== FloatOut stats: ====================
+4 Lets floated to top level; 0 Lets floated elsewhere; from 6 Lambda groups
+
+
+
+==================== Grand total simplifier statistics ====================
+Total ticks: 30
+
+8 PreInlineUnconditionally
+ 1 ds
+ 1 ds
+ 1 ds
+ 1 ds
+ 1 ds
+ 1 ds
+ 1 ds
+ 1 ds
+2 PostInlineUnconditionally
+ 1 r
+ 1 r
+4 UnfoldingDone
+ 2 GHC.Internal.Prim.void#
+ 1 T27910.k1
+ 1 T27910.k2
+8 BetaReduction
+ 1 ds
+ 1 ds
+ 1 ds
+ 1 ds
+ 1 ds
+ 1 ds
+ 1 ds
+ 1 ds
+4 KnownBranch
+ 2 wild
+ 1 ww
+ 1 ww
+4 CaseElim
+ 2 ww
+ 2 ww
+9 SimplifierDone 9
+
+
=====================================
testsuite/tests/simplCore/should_compile/all.T
=====================================
@@ -627,5 +627,8 @@ test('T27749',
compile, ['-O -g3 -ddump-simpl -dsuppress-uniques'])
test('T27629', only_ways(['optasm']), makefile_test, ['T27629'])
-
test('T27936', normal, compile, [''])
+
+# A case-float reaching abstractFloats used to make the Simplifier panic
+test('T27737a', normal, compile, ['-O'])
+test('T27910', grep_errmsg(r'KnownBranch'), compile, ['-O -dno-typeable-binds -ddump-simpl-stats -dsuppress-uniques'])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/73392ece21336a1f86181d302fe6c9…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/73392ece21336a1f86181d302fe6c9…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc][wip/simpl-clo] 5 commits: Lambda and case binders have vanilla IdInfo (#27965)
by Simon Peyton Jones (@simonpj) 16 Oct '26
by Simon Peyton Jones (@simonpj) 16 Oct '26
16 Oct '26
Simon Peyton Jones pushed to branch wip/simpl-clo at Glasgow Haskell Compiler / GHC
Commits:
5164431c by Simon Peyton Jones at 2026-10-16T16:38:17+01:00
Lambda and case binders have vanilla IdInfo (#27965)
Lambda binders, case binders, and case-alternative binders should never
have RULES, a (non-default) inline pragma, or a stable unfolding. See the
new Note [Lambda and case binders have vanilla IdInfo] in GHC.Core.
This patch
* Makes Core Lint check the invariant, using the new predicate
GHC.Types.Id.lamBndrInfoOK.
* Fixes the desugarer, which violated it. For a strict binding
let !x = rhs in body
we generate
let x = rhs in case x of x { DEFAULT -> body }
re-using x (shadowed) as the case binder; see Note [Desugar Strict binds].
But the case binder inherited x's IdInfo, including, say, a NOINLINE
pragma (e.g. `res1` in GHC.Internal.Control.Monad.ST.Lazy.Imp). Now
GHC.HsToCore.Utils.seqVar gives the case binder vanilla IdInfo.
This was not just a matter of taste. For example
h fm s = let {-# NOINLINE res1 #-}
!res1 = fm s
!(f, s') = res1
in (f+1, s')
The NOINLINE case binder becomes a NOINLINE alias `let res3 = res2`,
which is never inlined, and survives (as a silly join point) into the
final code.
* Fixes the Simplifier, which could violate it when duplicating a
StrictBind continuation, which makes a join point
let x = <> in b ==> join j x = b in j <>
If x has such IdInfo, we now use a fresh binder for the join point
let x = <> in b ==> join j x' = let x = x' in b in j <>
See (DSB1) in Note [Duplicating StrictBind].
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
2a54d5f5 by Simon Peyton Jones at 2026-10-16T16:38:35+01:00
Use SimplClo for the argument of ApplyToVal
This patch renames SimplSR to SimplClo (a "closure"), and uses it not
only as the range of the Simplifier's substitution, but also as the
argument of an ApplyToVal continuation. ApplyToVal used to have three
fields
sc_env :: StaticEnv
sc_arg :: CoreExpr
sc_cast :: MOutCoercion
but now has just
sc_dup :: DupFlag
sc_arg :: SimplClo
An un-simplified argument is (ContEx env arg mco), and an already-simplified
one is (DoneEx arg _). See Note [The argument of ApplyToVal] in
GHC.Core.Opt.Simplify.Utils.
The main payoff is that, since the substitution maps an Id to a SimplClo,
beta-reduction can substitute the argument for the lambda binder without
further ado. Accordingly, preInlineUnconditionally is split into
* preInlineLetUnconditionally, for let-bindings
* preInlineBetaUnconditionally, for beta-redexes, which takes a SimplClo
The latter omits some checks that cannot fire for lambda binders.
Other notes
* The new (ContEx env arg mco) form makes it easy to push a cast into an
argument (mkCloCastMCo), whether or not it has been simplified.
See Note [The MOutCoercion field of ContEx].
* Fixes #27963. contOutArgs, which supplies the arguments for Plan (BEFORE)
rule matching, ignored the sc_cast field of ApplyToVal. So in
(f |> co) n ==> f (n |> co1) -- co1 in sc_cast
a rule for `f` saw `f n` rather than `f (n |> co1)`, and failed to match
(the rule matcher checks the types of template variables). If f's
unfolding is active, f may then be inlined, and the rule is lost for
good. Now contOutArgs uses simplCloExpr, which includes the pending cast.
Almost no change in behaviour, except for the #27963 bug-fix.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
8eb1b3d9 by Simon Peyton Jones at 2026-10-16T16:38:35+01:00
Fix the runRW# case of simplOutId to respect a pending cast
In the runRW# case of simplOutId, if the argument was a literal lambda
we took a short cut, simplifying the lambda body directly. But we
ignored any pending cast on the argument, arising from pushing a cast
into it; e.g. after inlining
myRun :: (State# RealWorld -> N) -> N
myRun = coerce (runRW# :: (State# RealWorld -> Int) -> Int)
That yielded ill-typed Core (#27962).
Fix: only take the short cut if there is no pending cast. Otherwise use
the general case, which deals with the cast properly.
Test: T27962, T27962a
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
f91015ef by Simon Peyton Jones at 2026-10-16T16:38:35+01:00
Get the DupFlag right in the runRW# case of simplOutId
In the runRW# case of simplOutId we built an ApplyToVal continuation
with sc_dup = OkDup, regardless of whether its tail, inner_cont, was
itself dupable. That violates invariant (AV2) in
Note [The argument of ApplyToVal], and could lead mkDupableCont to
duplicate a large continuation.
Fix: use OkDup only if (contIsDupable inner_cont).
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
340161d8 by Simon Peyton Jones at 2026-10-16T16:38:35+01:00
Add regression test for #27963
The bug itself was fixed by "Use SimplClo for the argument of ApplyToVal".
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
11 changed files:
- compiler/GHC/Core.hs
- compiler/GHC/Core/Lint.hs
- compiler/GHC/Core/Opt/Simplify/Env.hs
- compiler/GHC/Core/Opt/Simplify/Iteration.hs
- compiler/GHC/Core/Opt/Simplify/Utils.hs
- compiler/GHC/HsToCore/Utils.hs
- compiler/GHC/Types/Id.hs
- + testsuite/tests/simplCore/should_compile/T27962.hs
- + testsuite/tests/simplCore/should_compile/T27963.hs
- + testsuite/tests/simplCore/should_compile/T27963.stderr
- testsuite/tests/simplCore/should_compile/all.T
Changes:
=====================================
compiler/GHC/Core.hs
=====================================
@@ -1752,6 +1752,44 @@ So unfoldings on lambda binders can never really be trusted when on lambda binde
is the chance of the call site to change. So it's easiest to just never attach any
to lambda binders to begin with, as well as stripping them off if we e.g. float out
and expression while abstracting over some arguments.
+
+See also Note [Lambda and case binders have vanilla IdInfo].
+
+Note [Lambda and case binders have vanilla IdInfo]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Invariant: the following binders
+ * lambda binders (\x. e)
+ * case binders case e of x { ... }
+ * case-alternative binders case e of _ { K x y -> ... }
+have none of
+ (a) RULES
+ (b) a (non-default) inline pragma, such as INLINE or NOINLINE
+ (c) a stable unfolding
+The predicate `GHC.Types.Id.lamBndrInfoOK` checks (a-c), and Core Lint checks
+it (in `lintIdBndr`). Moreover lambda binders have no unfolding at all, not
+even an OtherCon one: see Note [Never put `OtherCon` unfoldings on lambda binders].
+
+Why? RULES, pragmas, and stable unfoldings describe a /let-bound/ Id, whose
+definition is right there in the binding. It is far from clear what they would
+mean for a lambda binder, whose value is supplied by the caller; and we can't
+easily work out the consequences of allowing them. It is much simpler just to
+rule them out. For example, `preInlineBetaUnconditionally` assumes the
+invariant, and so does not check the binder's activation or stable unfolding.
+This is very much in the spirit of #17530, when we stopped adding unfoldings to
+lambda binders.
+
+Why case binders and case-alternative binders? Because they can become lambda
+binders, when `mkDupableAlt` abstracts a join point over them.
+
+Places that must take care to maintain the invariant (#27965):
+
+* The desugarer, when desugaring a strict binding let !x = rhs in body,
+ generates case x of x { DEFAULT -> body }; the case binder must not inherit
+ x's IdInfo. See `GHC.HsToCore.Utils.seqVar`.
+
+* The Simplifier, when duplicating a StrictBind continuation let x = <> in b,
+ makes a join point whose lambda binder must not inherit x's IdInfo.
+ See (DSB1) in Note [Duplicating StrictBind] in GHC.Core.Opt.Simplify.Iteration.
-}
-- | Records the /unfolding/ of an identifier, which is approximately the form the
=====================================
compiler/GHC/Core/Lint.hs
=====================================
@@ -1858,6 +1858,17 @@ lintIdBndr top_lvl bind_site id thing_inside
hang (text "Lambda binder" <+> quotes (ppr id) <+> text "has an unfolding")
2 (ppr unf)
+ -- Check that lambda, case, and case-alternative binders have
+ -- no RULES, no inline pragma, and no stable unfolding
+ -- See Note [Lambda and case binders have vanilla IdInfo] in GHC.Core
+ ; checkL (is_let_bind || lamBndrInfoOK id) $
+ hang (text "Non-let binder" <+> quotes (ppr id)
+ <+> text "has RULES, an inline pragma, or a stable unfolding")
+ 2 (vcat [ text "Binding site:" <+> text (show_site bind_site)
+ , text "Inline pragma:" <+> ppr (idInlinePragma id)
+ , text "Rules:" <+> ppr (idCoreRules id)
+ , text "Unfolding:" <+> ppr (realIdUnfolding id) ])
+
; addLoc (IdTy id) (lintValueType id_ty)
; addInScopeId id thing_inside }
@@ -1869,6 +1880,12 @@ lintIdBndr top_lvl bind_site id thing_inside
LetBind -> True
_ -> False
+ show_site :: BindingSite -> String
+ show_site LambdaBind = "lambda"
+ show_site CaseBind = "case binder"
+ show_site CasePatBind = "case alternative"
+ show_site LetBind = "let"
+
{-
%************************************************************************
%* *
=====================================
compiler/GHC/Core/Opt/Simplify/Env.hs
=====================================
@@ -28,7 +28,7 @@ module GHC.Core.Opt.Simplify.Env (
SimplEnvIS, checkSimplEnvIS, pprBadSimplEnvIS,
-- * Substitution results
- SimplSR(..), substId, lookupRecBndr,
+ SimplClo(..), simplCloExpr, substId, lookupRecBndr,
-- * Simplifying 'Id' binders
simplNonRecBndr, simplNonRecJoinBndr, simplRecBndrs, simplRecJoinBndrs,
@@ -61,7 +61,7 @@ import GHC.Core.Opt.Simplify.Monad
import GHC.Core.Rules.Config ( RuleOpts(..) )
import GHC.Core
import GHC.Core.Utils
-import GHC.Core.Subst( substExprSC )
+import GHC.Core.Subst( substExpr, substExprSC )
import GHC.Core.Unfold
import GHC.Core.TyCo.Subst (emptyIdSubstEnv, mkSubst)
import GHC.Core.Multiplicity( Scaled(..), mkMultMul )
@@ -470,11 +470,16 @@ pprSimplEnv env
ppr_one v | isId v = ppr v <+> ppr (idUnfolding v)
| otherwise = ppr v
-type SimplIdSubst = IdEnv SimplSR -- IdId |--> OutExpr
+type SimplIdSubst = IdEnv SimplClo -- IdId |--> OutExpr
-- See Note [Extending the IdSubstEnv] in GHC.Core.Subst
--- | A substitution result.
-data SimplSR
+-- | A "closure" used in the Simplifier. It is used
+-- * as the range of the substitution, 'SimplIdSubst'
+-- * as the argument in an 'ApplyToVal' continuation
+-- Roughly: either an (InExpr, StaticEnv) pair for an
+-- as-yet-unsimplified expression
+-- or an OutExpr, for an already-simplified one
+data SimplClo
= DoneEx OutExpr JoinPointHood
-- If x :-> DoneEx e ja is in the SimplIdSubst
-- then replace occurrences of x by e
@@ -490,11 +495,11 @@ data SimplSR
| ContEx SimplEnv
InExpr
- MOutCoercion -- See Note [The sc_cast field of ApplyToVal]
+ MOutCoercion -- See Note [The MOutCoercion field of ContEx]
-- If x :-> ContEx static_env e mco is in the SimplISubst
-- then replace occurrences of x by (subst static_env e) |> mco
-instance Outputable SimplSR where
+instance Outputable SimplClo where
ppr (DoneId v) = text "DoneId" <+> ppr v
ppr (DoneEx e mj) = text "DoneEx" <> pp_mj <+> ppr e
where
@@ -637,7 +642,7 @@ reSimplifying :: SimplEnv -> Bool
reSimplifying (SimplEnv { seInlineDepth = n }) = n>0
---------------------
-extendIdSubst :: SimplEnv -> Id -> SimplSR -> SimplEnv
+extendIdSubst :: SimplEnv -> Id -> SimplClo -> SimplEnv
extendIdSubst env@(SimplEnv {seIdSubst = subst}) var res
= assertPpr (isId var && not (isCoVar var)) (ppr var) $
env { seIdSubst = extendVarEnv subst var res }
@@ -1032,7 +1037,7 @@ So we want to look up the inner X.g_34 in the substitution, where we'll
find that it has been substituted by b. (Or conceivably cloned.)
-}
-substId :: SimplEnv -> InId -> SimplSR
+substId :: SimplEnv -> InId -> SimplClo
-- Returns DoneEx only on a non-Var expression
substId (SimplEnv { seInScope = in_scope, seIdSubst = ids }) v
= case lookupVarEnv ids v of -- Note [Global Ids in the substitution]
@@ -1366,7 +1371,7 @@ getFullSubst :: InScopeSet -> SimplEnv -> Subst
getFullSubst in_scope (SimplEnv { seIdSubst = id_env, seTvSubst = tv_env, seCvSubst = cv_env })
= mkSubst in_scope (mapVarEnv to_expr id_env) tv_env cv_env
where
- to_expr :: SimplSR -> CoreExpr
+ to_expr :: SimplClo -> CoreExpr
-- A tiresome impedence-matcher
to_expr (DoneEx e _) = e
to_expr (DoneId v) = Var v
@@ -1374,6 +1379,17 @@ getFullSubst in_scope (SimplEnv { seIdSubst = id_env, seTvSubst = tv_env, seCvSu
where
e' = GHC.Core.Subst.substExprSC (getFullSubst in_scope env) e
+simplCloExpr :: InScopeSet -> SimplClo -> OutExpr
+-- Turn a SimplClo into an OutExpr, by applying the substitution
+-- (if any) and the pending cast (if any)
+simplCloExpr _ (DoneEx e _) = e
+simplCloExpr _ (DoneId v) = Var v
+simplCloExpr in_scope (ContEx env e mco) = mkCastMCo e' mco
+ where
+ e' = GHC.Core.Subst.substExpr (getFullSubst in_scope env) e
+ -- NB: we use substExpr, not substExprSC: we want to get the benefit of
+ -- knowing what is evaluated etc, via the in-scope set
+
substTy :: HasDebugCallStack => SimplEnv -> Type -> Type
substTy env ty = Type.substTy (getTCvSubst env) ty
=====================================
compiler/GHC/Core/Opt/Simplify/Iteration.hs
=====================================
@@ -285,8 +285,8 @@ simplRecOrTopPair :: SimplEnv
-> SimplM (SimplFloats, SimplEnv)
simplRecOrTopPair env bind_cxt old_bndr new_bndr rhs
- | Just env' <- preInlineUnconditionally env (bindContextLevel bind_cxt)
- old_bndr (UnSimplified env) rhs MRefl
+ | Just env' <- preInlineLetUnconditionally env (bindContextLevel bind_cxt)
+ old_bndr rhs env
= {-#SCC "simplRecOrTopPair-pre-inline-uncond" #-}
simplTrace "SimplBindr:inline-uncond1" (ppr old_bndr) $
do { tick (PreInlineUnconditionally old_bndr)
@@ -1264,9 +1264,9 @@ simplExprF1 env (App fun arg) cont
-- observed the quadratic behavior, so this extra entanglement
-- seems not worthwhile.
simplExprF env fun $
- ApplyToVal { sc_arg = arg, sc_env = UnSimplified env
+ ApplyToVal { sc_arg = ContEx env arg MRefl, sc_dup = NoDup
, sc_hole_ty = substTy env (exprType fun)
- , sc_cast = MRefl, sc_cont = cont }
+ , sc_cont = cont }
simplExprF1 env expr@(Lam {}) cont
= {-#SCC "simplExprF1-Lam" #-}
@@ -1301,7 +1301,7 @@ simplExprF1 env (Let (NonRec bndr rhs) body) cont
do { ty' <- simplType env ty
; simplExprF (extendTvSubst env bndr ty') body cont }
- | Just env' <- preInlineUnconditionally env NotTopLevel bndr (UnSimplified env) rhs MRefl
+ | Just env' <- preInlineLetUnconditionally env NotTopLevel bndr rhs env
-- Because of the let-can-float invariant, it's ok to
-- inline freely, or to drop the binding if it is dead.
= do { simplTrace "SimplBindr:inline-uncond2" (ppr bndr) $
@@ -1637,9 +1637,8 @@ rebuild_go env expr cont
ApplyToTy { sc_arg_ty = ty, sc_cont = cont}
-> rebuild_go env (App expr (Type ty)) cont
- ApplyToVal { sc_arg = arg, sc_env = arg_se, sc_cast = arg_mco
- , sc_cont = cont, sc_hole_ty = fun_ty }
- -> do { arg' <- simplArg env Nothing fun_ty arg_se arg arg_mco
+ ApplyToVal { sc_arg = arg, sc_cont = cont, sc_hole_ty = fun_ty }
+ -> do { arg' <- simplArg env Nothing fun_ty arg
; rebuild_go env (App expr arg') cont }
completeBindX :: SimplEnv
@@ -1653,6 +1652,8 @@ completeBindX env from_what bndr rhs body cont
| FromBeta arg_levity <- from_what
, needsCaseBindingL arg_levity rhs -- Enforcing the let-can-float-invariant
= do { (env1, bndr1) <- simplNonRecBndr env bndr -- Lambda binders don't have rules
+ -- See Note [Lambda and case binders have
+ -- vanilla IdInfo] in GHC.Core
; (floats, expr') <- simplNonRecBody env1 from_what body cont
-- Do not float floats past the Case binder below
; let expr'' = wrapFloats floats expr'
@@ -1747,7 +1748,7 @@ on each successive composition -- that's at least quadratic. So:
duplicating a CastIt, optimise the coercion. Otherwise we'll end up
optimising it separately in the duplicate copies.
-* See also Note [The sc_cast field of ApplyToVal] in GHC.Core.Opt.Simplify.Utils.
+* See also Note [The MOutCoercion field of ContEx] in GHC.Core.Opt.Simplify.Utils.
-}
simplArg :: SimplEnvIS -- ^ Used only for its InScopeSet
@@ -1756,15 +1757,12 @@ simplArg :: SimplEnvIS -- ^ Used only for its InScopeSet
-- how `f` uses `ai`, affecting the Stop
-- continuation passed to 'simplExprC'
-> OutType -- ^ Type of the function applied to this arg
- -> StaticEnv -> CoreExpr -- ^ Expression with its static envt
- -> MOutCoercion -- Wrap this around the result
+ -> SimplClo -- ^ The argument
-> SimplM OutExpr
-simplArg _ _ _ (Simplified {}) arg mco
- = -- See Note [Avoid repeated simplification]
- case mco of
- MRefl -> return arg -- Vastly common case
- MCo co -> return (mkCast arg co)
-simplArg env mb_arg_info fun_ty (UnSimplified arg_se) arg mco
+-- See Note [The argument of ApplyToVal] in GHC.Core.Opt.Simplify.Utils
+simplArg _ _ _ (DoneEx arg _) = return arg -- See Note [Avoid repeated simplification]
+simplArg _ _ _ (DoneId v) = return (Var v)
+simplArg env mb_arg_info fun_ty (ContEx arg_se arg mco)
= do { let arg_env' = arg_se `setInScopeFromE` env
arg_ty = funArgTy fun_ty
stop = case mb_arg_info of
@@ -1806,13 +1804,9 @@ simpl_lam env bndr body (ApplyToTy { sc_arg_ty = arg_ty, sc_cont = cont })
-- Value beta-reduction
-- This works for /coercion/ lambdas too
-simpl_lam env bndr body (ApplyToVal { sc_arg = arg, sc_env = arg_se
- , sc_cast = arg_mco, sc_cont = cont
+simpl_lam env bndr body (ApplyToVal { sc_arg = arg, sc_cont = cont
, sc_hole_ty = fun_ty})
- | Just env' <- preInlineUnconditionally env NotTopLevel bndr arg_se arg arg_mco
- , not (needsCaseBindingL arg_levity arg)
- -- Ok to test arg::InExpr in needsCaseBinding because
- -- exprOkForSpeculation is stable under simplification
+ | Just env' <- preInlineBetaUnconditionally env arg_levity bndr arg
= simplTrace "SimplBindr:inline-uncond3"
(ppr bndr <+> text ":=" <+> ppr arg) $
do { tick (BetaReduction bndr)
@@ -1823,14 +1817,14 @@ simpl_lam env bndr body (ApplyToVal { sc_arg = arg, sc_env = arg_se
= do { tick (BetaReduction bndr)
; let from_what = FromBeta arg_levity
- ; case (arg_se, arg_mco) of
- (UnSimplified arg_env, MRefl)
+ ; case arg of
+ ContEx arg_env arg_expr MRefl
-- Optimisation: when there is no wrapping coercion use simplNonRecE
-- so that the clever floating out of let-bindings can take place
-- in this round of the Simplifier
- -> simplNonRecE env from_what bndr (arg, arg_env) body cont
+ -> simplNonRecE env from_what bndr (arg_expr, arg_env) body cont
- _ -> do { arg' <- simplArg env Nothing fun_ty arg_se arg arg_mco
+ _ -> do { arg' <- simplArg env Nothing fun_ty arg
; completeBindX env from_what bndr arg' body cont }
}
where
@@ -2262,11 +2256,14 @@ simplOutId env fun cont
| fun `hasKey` runRWKey
, ApplyToTy { sc_cont = cont1 } <- cont
, ApplyToTy { sc_cont = cont2, sc_arg_ty = hole_ty } <- cont1
- , ApplyToVal { sc_cont = cont3, sc_arg = arg, sc_cast = arg_mco
- , sc_env = arg_se, sc_hole_ty = fun_ty } <- cont2
+ , ApplyToVal { sc_cont = cont3, sc_arg = arg_clo, sc_hole_ty = fun_ty } <- cont2
-- Do this even if (contIsStop cont), or if seCaseCase is off.
-- See Note [No eta-expansion in runRW#]
- = do { let (_saf,arg_env) = mkAltEnv env arg_se
+ = do { let (arg_env, arg, arg_mco)
+ = case arg_clo of
+ ContEx se e mco -> (se `setInScopeFromE` env, e, mco)
+ DoneEx e _ -> (env, e, MRefl)
+ DoneId v -> (env, Var v, MRefl)
overall_res_ty = contResultType cont3
-- hole_ty is the type of the current runRW# application
@@ -2281,23 +2278,32 @@ simplOutId env fun cont
-- * If we don't do this we get a beta-redex every time, so the
-- simplifier keeps doing more iterations.
-- * Even more important: see Note [No eta-expansion in runRW#]
+ --
+ -- But only if there is no pending cast on the argument (#27962);
+ -- if there is, the general case below deals with it properly
; arg' <- case arg of
- Lam s body -> do { (env', s') <- simplBinder arg_env s
- ; body' <- simplExprC env' body inner_cont
- ; return (Lam s' body') }
- -- Important: do not try to eta-expand this lambda
- -- See Note [No eta-expansion in runRW#]
+ Lam s body
+ | MRefl <- arg_mco
+ -> do { (env', s') <- simplBinder arg_env s
+ ; body' <- simplExprC env' body inner_cont
+ ; return (Lam s' body') }
+ -- Important: do not try to eta-expand this lambda
+ -- See Note [No eta-expansion in runRW#]
_ -> do { s' <- newId (fsLit "s") ManyTy realWorldStatePrimTy
; let (m,_,_) = splitFunTy fun_ty
env' = arg_env `addNewInScopeIds` [s']
hole_ty = mkVisFunTy m realWorldStatePrimTy new_runrw_res_ty
cont' = pushCastMCo env' arg_mco $
- ApplyToVal { sc_arg = Var s', sc_cast = MRefl
- , sc_env = Simplified OkDup
+ ApplyToVal { sc_arg = DoneEx (Var s') NotJoinPoint
+ , sc_dup = dup
, sc_cont = inner_cont
, sc_hole_ty = hole_ty }
-- cont' applies to s', then K
+ -- The argument (Var s') is small, but inner_cont may not be
+ -- dupable; see (AV2) in Note [The argument of ApplyToVal]
+ dup | contIsDupable inner_cont = OkDup
+ | otherwise = NoDup
; body' <- simplExprC env' arg cont'
; return (Lam s' body') }
@@ -2364,13 +2370,12 @@ rebuildCall env info (ApplyToTy { sc_arg_ty = arg_ty, sc_hole_ty = hole_ty, sc_c
---------- Simplify value arguments --------------------
rebuildCall env fun_info
- (ApplyToVal { sc_arg = arg, sc_env = arg_se, sc_cast = arg_mco
- , sc_hole_ty = fun_ty, sc_cont = cont })
- | UnSimplified arg_env <- arg_se
+ (ApplyToVal { sc_arg = arg, sc_hole_ty = fun_ty, sc_cont = cont })
+ | ContEx arg_env arg_expr arg_mco <- arg
, isStrictArgInfo fun_info -- Strict arguments
, seCaseCase env -- But only when case-of-case is on.
-- See Note [Case-of-case and full laziness]
- = simplExprF (arg_env `setInScopeFromE` env) arg $
+ = simplExprF (arg_env `setInScopeFromE` env) arg_expr $
addCastMCo arg_mco $
StrictArg { sc_fun = fun_info, sc_fun_ty = fun_ty
, sc_dup = NoDup
@@ -2382,7 +2387,7 @@ rebuildCall env fun_info
-- There is no benefit (unlike in a let-binding), and we'd
-- have to be very careful about bogus strictness through
-- floating a demanded let.
- = do { arg' <- simplArg env (Just fun_info) fun_ty arg_se arg arg_mco
+ = do { arg' <- simplArg env (Just fun_info) fun_ty arg
; rebuildCall env (addValArgTo fun_info arg' fun_ty) cont }
---------- No further useful info, revert to generic rebuild ------------
@@ -2530,11 +2535,11 @@ Then
* We simplify BIG before trying the rule; but the rule does not fire
(forcing this simplification is why we have the RULE in this example)
* We inline f = \x. g x, in `simpl_lam`
- * So if `simpl_lam` did preInlineUnconditionally we get (g BIG)
+ * So if `simpl_lam` did preInlineBetaUnconditionally we get (g BIG)
* Now if g has a RULE we'll simplify BIG again, and this whole thing can
iterate.
* However, if `f` did not have a RULE, so that BIG has /not/ already been
- simplified, we /want/ to do preInlineUnconditionally in simpl_lam.
+ simplified, we /want/ to do preInlineBetaUnconditionally in simpl_lam.
So we go to some effort to avoid repeatedly simplifying the same thing.
Suppose we are in the Plan (AFTER) case of rule application, for a rule
@@ -2543,8 +2548,9 @@ and a call
f (e1,e2)
Then:
-* The (sc_env :: StaticEnv) field of ApplyToVal records if the argument
- has been evaluated. See Note [StaticEnv] in GHC.Core.Opt.Simplify.Utils.
+* The (sc_arg :: SimplClo) field of ApplyToVal records if the argument
+ has been simplified: it is a DoneEx if so, and a ContEx if not.
+ See Note [The argument of ApplyToVal] in GHC.Core.Opt.Simplify.Utils.
* The rule fires returning
RuleMatch { rm_rhs = (\x y. ...x..), rm_args = [ e1, e2 ] }
@@ -2557,17 +2563,17 @@ Then:
is the reason that `RuleMatch` separates the two.
* `fireRuleAFTER` uses `pushOutArgs` to push [ e1, e2 ] back onto the
- continuation with sc_env=Simplified NoDup.
+ continuation as (DoneEx e1) and (DoneEx e2).
* Beta-reduction fires (in `simpl_lam`) for the \x.
* Suppose `x` occurs many times. Then we want to behave like `let x=e1 in ..`,
- but we use `simplArg`, which in turn uses that `sc_env` flag to avoid
+ but we use `simplArg`, which in turn uses the DoneEx to avoid
re-simplifying `e1`.
* Suppose `x` occurs just once or not at all; then the call to
- `preInlineUnconditionally` in `simpl_lam` will fire, and extend the
- substitution with
+ `preInlineBetaUnconditionally` in `simpl_lam` will fire, and extend the
+ substitution with the very same SimplClo
x :-> DoneEx e1
* At the /occurrence/ of `x`, the function `simplInId` calls `simplOutExpr`
@@ -2774,8 +2780,7 @@ trySeqRules in_env scrut rhs cont
, ValArg { as_arg = no_cast_scrut
, as_dmd = seqDmd
, as_hole_ty = res3_ty } ]
- rule_cont = ApplyToVal { sc_env = UnSimplified in_env, sc_arg = rhs
- , sc_cast = MRefl
+ rule_cont = ApplyToVal { sc_arg = ContEx in_env rhs MRefl, sc_dup = NoDup
, sc_cont = cont, sc_hole_ty = res4_ty }
out_args = [Type rhs_rep, Type scrut_ty, Type rhs_ty, no_cast_scrut]
@@ -3879,8 +3884,8 @@ knownCon env scrut dc dc_args case_bndr alt_bndrs rhs cont
return ( emptyFloats env
, extendIdSubst env case_bndr (DoneEx scrut NotJoinPoint))
- | Just env' <- preInlineUnconditionally env NotTopLevel case_bndr
- (UnSimplified env) con_app MRefl
+ | Just env' <- preInlineLetUnconditionally env NotTopLevel case_bndr
+ con_app env
= return (emptyFloats env', env')
| otherwise
@@ -4060,7 +4065,15 @@ mkDupableContWithDmds env _
; let join_body = wrapFloats floats1 join_inner
res_ty = contResultType cont
- ; mkDupableStrictBind env bndr' join_body res_ty }
+ -- If bndr' has IdInfo that a lambda binder must not have,
+ -- use a fresh lambda binder; see (DSB1) in Note [Duplicating StrictBind]
+ ; (arg_bndr, join_body')
+ <- if lamBndrInfoOK bndr'
+ then return (bndr', join_body)
+ else do { arg_bndr <- newId (fsLit "x") (idMult bndr') (idType bndr')
+ ; return (arg_bndr, Let (NonRec bndr' (Var arg_bndr)) join_body) }
+
+ ; mkDupableStrictBind env arg_bndr join_body' res_ty }
mkDupableContWithDmds env _
(StrictArg { sc_fun = fun, sc_cont = cont
@@ -4111,8 +4124,7 @@ mkDupableContWithDmds env dmds
, sc_arg_ty = arg_ty, sc_hole_ty = hole_ty }) }
mkDupableContWithDmds env dmds
- (ApplyToVal { sc_arg = arg, sc_env = se, sc_cast = arg_mco
- , sc_cont = cont, sc_hole_ty = hole_ty })
+ (ApplyToVal { sc_arg = arg, sc_cont = cont, sc_hole_ty = hole_ty })
= -- e.g. [...hole...] (...arg...)
-- ==>
-- let a = ...arg...
@@ -4124,12 +4136,12 @@ mkDupableContWithDmds env dmds
expectNonEmpty dmds
; (floats1, cont') <- mkDupableContWithDmds env cont_dmds cont
; let env' = env `setInScopeFromF` floats1
- ; arg' <- simplArg env' Nothing hole_ty se arg arg_mco
+ ; arg' <- simplArg env' Nothing hole_ty arg
; (let_floats2, triv_arg) <- makeTrivial env' NotTopLevel dmd (fsLit "karg") arg'
; let all_floats = floats1 `addLetFloats` let_floats2
; return ( all_floats
- , ApplyToVal { sc_arg = triv_arg, sc_env = Simplified OkDup
- , sc_cast = MRefl, sc_cont = cont', sc_hole_ty = hole_ty }) }
+ , ApplyToVal { sc_arg = DoneEx triv_arg NotJoinPoint, sc_dup = OkDup
+ , sc_cont = cont', sc_hole_ty = hole_ty }) }
mkDupableContWithDmds env _
(Select { sc_bndr = case_bndr, sc_alts = alts, sc_env = se, sc_cont = cont })
@@ -4253,7 +4265,9 @@ mkDupableAlt _env case_bndr jfloats (Alt con alt_bndrs alt_rhs_in)
| otherwise = v
-- No lambda binder has an unfolding, but (currently) case binders can,
- -- so we must zap them here.
+ -- so we must zap them here. But case binders never have a pragma,
+ -- stable unfolding or RULES, so there is no need to zap those.
+ -- See Note [Lambda and case binders have vanilla IdInfo] in GHC.Core
join_rhs = mkLams (map zapIdUnfolding final_bndrs) rhs_with_seqs
; join_bndr <- newJoinId filtered_binders rhs_ty'
@@ -4660,6 +4674,20 @@ So we potentially make a join-point for the body, thus:
Just like StrictArg in fact -- and indeed they share code.
+(DSB1) Lambda binders must not have a (non-default) inline pragma, a stable
+ unfolding, or RULES; see Note [Lambda and case binders have vanilla IdInfo]
+ in GHC.Core, and #27965. But the let-binder `x` may well
+ have them; e.g. in GHC.Internal.Control.Monad.ST.Lazy.Imp we have
+ {-# NOINLINE res1 #-}
+ !res1 = unST fm s
+ So if `x` has such IdInfo, we use a fresh binder `x'` for the join point,
+ and keep `x` as a let-binder, retaining all its IdInfo:
+ let x = <> in b ==> join j x' = let x = x' in b
+ in j <>
+ The hole is evaluated before the jump, so `x'` is a value, and `let x = x'`
+ is just an alias. We do this only when necessary, to avoid leaving an
+ alias in the common case.
+
Note [Join point abstraction] Historical note
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
NB: This note is now historical, describing how (in the past) we used
=====================================
compiler/GHC/Core/Opt/Simplify/Utils.hs
=====================================
@@ -12,7 +12,8 @@ module GHC.Core.Opt.Simplify.Utils (
tryEtaExpandRhs, wantEtaExpansion,
-- Inlining,
- preInlineUnconditionally, postInlineUnconditionally,
+ preInlineLetUnconditionally, preInlineBetaUnconditionally,
+ postInlineUnconditionally,
activeRule,
getUnfoldingInRuleMatch,
updModeForStableUnfoldings, updModeForRuleLHS, updModeForRuleRHS,
@@ -180,10 +181,9 @@ data SimplCont
| ApplyToVal -- (ApplyToVal arg K)[e] = K[ e arg ]
{ sc_hole_ty :: OutType -- Type of the function, presumably (forall a. blah)
-- See Note [The hole type in ApplyToTy]
- , sc_env :: StaticEnv -- See Note [StaticEnv]
- , sc_arg :: CoreExpr -- The argument
- , sc_cast :: MOutCoercion -- Wrap this OutCoercion around the (simplified) argument
- -- See Note [The sc_cast field of ApplyToVal]
+ , sc_dup :: DupFlag -- See Note [The argument of ApplyToVal]
+ , sc_arg :: SimplClo -- The argument
+ -- Invariant: if sc_arg is a ContEx, then sc_dup = NoDup
, sc_cont :: SimplCont }
| ApplyToTy -- (ApplyToTy ty K)[e] = K[ e ty ]
@@ -252,49 +252,85 @@ perhapsSubstTy (UnSimplified env) ty = substTy env ty
{- Note [StaticEnv]
~~~~~~~~~~~~~~~~~~~
-Consider ApplyToVal, which has
- sc_env :: StaticEnv
- sc_arg :: CoreExpr
-Initially, `sc_arg` is an un-simplified InExpr, and `sc_env` is (UnSimplified env),
-where `env` gives meaning to the free variables of `sc_arg`; in particular, `env`
-may have substitutions that must apply to the argument.
-
-But sometimes we simplify the argument, and in that case, `sc_arg` is an OutExpr,
-the simplified argument, and `sc_env` is (Simplified NoDup) or (Simplified OkDup).
-The former is the safe, conservative option, but in `mkDupableCont` we want to make
-the continuation duplicable, so we make the argument small and tag it with
-(Simplified OkDup).
-
-We later simplify the argument, e.g. in `simplArg`. Then
- * If sc_env is Simplified, it's a no-op
- * If sc_env is (UnSimplified arg_env) we simplify `sc_arg` with
- - Its captured envt `arg_env`
+Consider Select, which has
+ sc_env :: StaticEnv
+ sc_bndr :: Id
+ sc_alts :: [CoreAlt]
+Initially, `sc_bndr` and `sc_alts` are un-simplified InThings, and `sc_env` is
+(UnSimplified env), where `env` gives meaning to their free variables; in
+particular, `env` may have substitutions that must apply to them.
+
+But sometimes (notably in `mkDupableCont`) we simplify them, and in that case
+`sc_bndr` and `sc_alts` are OutThings, and `sc_env` is (Simplified dup).
+
+When we finally simplify the alternatives (see `mkAltEnv`)
+ * If sc_env is Simplified, there is nothing to do
+ * If sc_env is (UnSimplified alt_env) we simplify them with
+ - Their captured envt `alt_env`
- but overriding its InScopeSet with the larger one at the
simplification point.
Why override the InScopeSet? Example:
- (let y = ey in f) ex
- By the time we simplify ex, 'y' will be in scope.
- All this is done in `simplArg`.
+ case (let y = ey in f) of alts
+ By the time we simplify alts, 'y' will be in scope.
Note that:
* In the Simplified case there is no environment, because the substitution has
already been applied.
-* We say sc_arg :: CoreExpr, rather than sc_arg :: InExpr or sc_arg :: OutExpr,
- because whether it is InExpr or OutExpr depends on `sc_env`
+* We say sc_alts :: [CoreAlt], rather than [InAlt] or [OutAlt],
+ because whether they are InAlts or OutAlts depends on `sc_env`
-* Same deal for Select, and StrictBind, but the StaticEnv scopes over
- * sc_bndr and sc_alts (for Select)
- * sc_bndr and sc_body (for StrictBind)
+* Same deal for StrictBind, where the StaticEnv scopes over sc_bndr and sc_body.
-* Even though the InScopeSet of an (UnSimplified se) is overridden in `simplArg`,
- that InScopeSet is not irrelevant: it should include all the free vars of
- applying the substitution to the InExpr. Reason: contHoleType uses perhapsSubstTy
- to apply the substitution to the expression, and that (rightly) gives ASSERT
- failures if the InScopeSet isn't big enough.
+* ApplyToVal is similar, but simpler: it uses a SimplClo instead.
+ See Note [The argument of ApplyToVal].
+
+* Even though the InScopeSet of an (UnSimplified se) is overridden, that
+ InScopeSet is not irrelevant: it should include all the free vars of
+ applying the substitution to the InThing. Reason: contHoleType uses
+ perhapsSubstTy to apply the substitution to the binder, and that
+ (rightly) gives ASSERT failures if the InScopeSet isn't big enough.
(SE1) If dup = OkToDup, then continuation k is also ok-to-dup
+
+Note [The argument of ApplyToVal]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ApplyToVal has
+ sc_dup :: DupFlag
+ sc_arg :: SimplClo
+
+Initially, `sc_arg` is (ContEx env arg MRefl), where `arg` is the un-simplified
+InExpr, and `env` gives meaning to the free variables of `arg`; in particular,
+`env` may have substitutions that must apply to the argument.
+
+But sometimes we simplify the argument, and in that case, `sc_arg` is
+(DoneEx arg' NotJoinPoint), where `arg'` is the simplified argument.
+
+The `sc_dup` flag says whether the continuation can be duplicated. NoDup is
+the safe, conservative option, but in `mkDupableCont` we want to make the
+continuation duplicable, so we make the argument small (and hence a DoneEx)
+and set `sc_dup` to OkDup. Invariants:
+
+ (AV1) If `sc_arg` is a ContEx, then `sc_dup` is NoDup.
+
+ (AV2) If `sc_dup` is OkDup then `sc_cont` is also ok-to-dup; see (SE1)
+ in Note [StaticEnv].
+
+We later simplify the argument, in `simplArg`. Then
+ * If `sc_arg` is a DoneEx (or DoneId), it's a no-op
+ * If `sc_arg` is (ContEx arg_env arg mco) we simplify `arg` with
+ - Its captured envt `arg_env`
+ - but overriding its InScopeSet with the larger one at the
+ simplification point.
+ Why override the InScopeSet? Example:
+ (let y = ey in f) ex
+ By the time we simplify ex, 'y' will be in scope.
+ Then we wrap the cast `mco` around the result.
+ See Note [The MOutCoercion field of ContEx].
+
+Using a SimplClo for the argument means that it can be substituted for a lambda
+binder, in `preInlineBetaUnconditionally`, without further ado.
-}
instance Outputable DupFlag where
@@ -312,9 +348,9 @@ instance Outputable SimplCont where
= (text "TickIt" <+> ppr t) $$ ppr cont
ppr (ApplyToTy { sc_arg_ty = ty, sc_cont = cont })
= (text "ApplyToTy" <+> pprParendType ty) $$ ppr cont
- ppr (ApplyToVal { sc_arg = arg, sc_env = env, sc_cont = cont, sc_hole_ty = hole_ty })
- = (hang (text "ApplyToVal" <> braces (ppr env) <+> text "hole-ty:" <+> pprParendType hole_ty)
- 2 (pprParendExpr arg))
+ ppr (ApplyToVal { sc_arg = arg, sc_dup = dup, sc_cont = cont, sc_hole_ty = hole_ty })
+ = (hang (text "ApplyToVal" <> braces (ppr dup) <+> text "hole-ty:" <+> pprParendType hole_ty)
+ 2 (ppr arg))
$$ ppr cont
ppr (StrictBind { sc_bndr = b, sc_cont = cont })
= (text "StrictBind" <+> ppr b) $$ ppr cont
@@ -433,8 +469,8 @@ pushOutArgs fun_ty (arg:args) cont
= ApplyToTy { sc_hole_ty = fun_ty, sc_arg_ty = ty
, sc_cont = pushOutArgs (piResultTy fun_ty ty) args cont }
| otherwise
- = ApplyToVal { sc_hole_ty = fun_ty, sc_cast = MRefl
- , sc_arg = arg, sc_env = Simplified NoDup
+ = ApplyToVal { sc_hole_ty = fun_ty
+ , sc_arg = DoneEx arg NotJoinPoint, sc_dup = NoDup
, sc_cont = pushOutArgs (funResultTy fun_ty) args cont}
pushArgSpecs :: [ArgSpec] -- In normal, forward order
@@ -445,7 +481,7 @@ pushArgSpec :: ArgSpec -> SimplCont -> SimplCont
pushArgSpec (TyArg { as_arg_ty = arg_ty, as_hole_ty = hole_ty }) cont
= ApplyToTy { sc_arg_ty = arg_ty, sc_hole_ty = hole_ty, sc_cont = cont }
pushArgSpec (ValArg { as_arg = arg, as_hole_ty = hole_ty }) cont
- = ApplyToVal { sc_arg = arg, sc_env = Simplified NoDup, sc_cast = MRefl
+ = ApplyToVal { sc_arg = DoneEx arg NotJoinPoint, sc_dup = NoDup
, sc_hole_ty = hole_ty, sc_cont = cont }
argSpecArg :: ArgSpec -> OutExpr
@@ -496,7 +532,12 @@ contIsStop _ = False
contIsDupable :: SimplCont -> Bool
contIsDupable (Stop {}) = True
contIsDupable (ApplyToTy { sc_cont = k }) = contIsDupable k
-contIsDupable (ApplyToVal { sc_env = se }) = okToDupSE se -- See (SE1) in Note [StaticEnv]
+contIsDupable (ApplyToVal { sc_dup = dup, sc_arg = arg })
+ = assertPpr (not (okToDup dup && is_cont_ex arg)) (ppr arg) $
+ okToDup dup -- See (AV1,AV2) in Note [The argument of ApplyToVal]
+ where
+ is_cont_ex (ContEx {}) = True
+ is_cont_ex _ = False
contIsDupable (Select { sc_env = se }) = okToDupSE se -- ...ditto...
contIsDupable (StrictBind { sc_env = se }) = okToDupSE se -- ...ditto...
contIsDupable (StrictArg { sc_dup = dup }) = okToDup dup -- ...ditto...
@@ -605,8 +646,8 @@ contArgs env cont
lone (CastIt {}) = False -- stops it being "lone"
lone _ = True
- go args (ApplyToVal { sc_arg = arg, sc_env = se, sc_cont = k })
- = go (interestingArg env se arg : args) k
+ go args (ApplyToVal { sc_arg = arg, sc_cont = k })
+ = go (interestingArg env arg : args) k
go args (ApplyToTy { sc_cont = k }) = go args k
go args (CastIt { sc_cont = k }) = go args k
go args k = (False, reverse args, k)
@@ -621,15 +662,13 @@ contOutArgs env cont
go (ApplyToTy { sc_arg_ty = ty, sc_cont = cont })
= Type ty : go cont
- go (ApplyToVal { sc_arg = arg, sc_env = se, sc_cont = cont })
- = case se of
- Simplified {} -> arg : go cont
- UnSimplified env -> GHC.Core.Subst.substExpr (getFullSubst in_scope env) arg : go cont
- -- Make sure we apply the static environment `sc_env` as a substitution
+ go (ApplyToVal { sc_arg = arg, sc_cont = cont })
+ = simplCloExpr in_scope arg : go cont
+ -- Make sure we apply the static environment of a ContEx as a substitution
-- to get an OutExpr. See (BF1) in Note [tryRules: plan (BEFORE)]
-- in GHC.Core.Opt.Simplify.Iteration
- -- NB: we use substExpr, not substExprSC: we want to get the benefit of
- -- knowing what is evaluated etc, via the in-scope set
+ -- simplCloExpr also wraps the pending cast (if any) around the argument;
+ -- omitting it can make a rule fail to match (#27963)
-- No more arguments
go _ = []
@@ -826,19 +865,27 @@ make use of the strictness info for the function.
* *
********************************************************************* -}
-{- Note [The sc_cast field of ApplyToVal]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+{- Note [The MOutCoercion field of ContEx]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In the `ApplyToVal` case of `pushCast` we want to push an `OutCoercion` into the
-argument. But the argument may or may not have been simplified (see Note [StaticEnv])
-so we definitely can't just wrap the cast around the argument. Instead we store it
-in the `sc_cast` field -- this is the whole reason for the `sc_cast` field.
+argument. But the argument may or may not have been simplified (see Note [The
+argument of ApplyToVal]):
+
+* If it has been simplified, it is (DoneEx arg' _), and we can simply wrap the
+ cast around `arg'`.
+
+* If it has not, it is (ContEx env arg mco), and we definitely can't just wrap
+ the (Out)cast around the InExpr `arg`. Instead we compose it with `mco` --
+ this is the whole reason for the MOutCoercion field of `ContEx`.
+
+All this is done by `mkCloCastMCo`.
We deal with that pending cast mainly in `simplArg`.
But we /also/ sometimes want to substitute that argument for a lambda-binder, in
-`preInlineUnconditionally`. So we also have to put that pending cast into
-`ContEx`; hence the MOutCoercion field of `ContEx`. Then we deal with it
-appropriately when /applying/ the substitution in `simplInId`.
+`preInlineBetaUnconditionally`; and since the substitution maps an Id to a SimplClo,
+the pending cast comes along for free. Then we deal with it appropriately when
+/applying/ the substitution in `simplInId`.
-}
optOutCoercion :: SimplEnvIS -> OutCoercion -> Bool -> OutCoercion
@@ -886,21 +933,17 @@ pushCast env co cont
-- where co :: (s1->s2) ~ (t1->t2)
-- co1 :: t1 ~ s1
-- co2 :: s2 ~ t2
- go co co_is_opt cont@(ApplyToVal { sc_arg = arg, sc_env = arg_se
- , sc_cast = arg_mco, sc_cont = tail })
+ go co co_is_opt cont@(ApplyToVal { sc_arg = arg, sc_cont = tail })
| not co_is_opt
= -- pushCoValArg duplicates the coercion, so optimise first
go (optOutCoercion (zapSubstEnv env) co co_is_opt) True cont
| Just (tyL, m_co1, m_co2) <- pushCoValArg co
= {-#SCC "addCoerce-pushCoValArg" #-}
- -- Dealing with m_co1 is the entire reason for the sc_cast field
- -- of ApplyToVal; see Note [The sc_cast field of ApplyToVal]
- ApplyToVal { sc_arg = arg
- , sc_env = arg_se
- , sc_cast = arg_mco `mkTransMCo` m_co1
- , sc_cont = go_mco m_co2 True tail
- , sc_hole_ty = tyL }
+ -- See Note [The MOutCoercion field of ContEx]
+ cont { sc_arg = mkCloCastMCo arg m_co1
+ , sc_cont = go_mco m_co2 True tail
+ , sc_hole_ty = tyL }
go co co_is_opt cont
| isReflCo co = cont -- Having this at the end makes a huge
@@ -914,6 +957,13 @@ pushCast env co cont
go_mco MRefl _ cont = cont
go_mco (MCo co) opt cont = go co opt cont
+mkCloCastMCo :: SimplClo -> MOutCoercion -> SimplClo
+-- See Note [The MOutCoercion field of ContEx]
+mkCloCastMCo clo MRefl = clo
+mkCloCastMCo (DoneId v) (MCo co) = DoneEx (mkCast (Var v) co) NotJoinPoint
+mkCloCastMCo (DoneEx e _) (MCo co) = DoneEx (mkCast e co) NotJoinPoint
+mkCloCastMCo (ContEx se e mco) (MCo co) = ContEx se e (mco `mkTransMCo` MCo co)
+
{-
************************************************************************
@@ -1227,19 +1277,17 @@ Wrinkles:
-}
-interestingArg :: SimplEnv -> StaticEnv -> CoreExpr -> ArgSummary
+interestingArg :: SimplEnv -> SimplClo -> ArgSummary
-- See Note [Interesting arguments]
-interestingArg env se e
- = case se of
- Simplified {} -> go env 0 e
- UnSimplified static_env -> go (static_env `setInScopeFromE` env) 0 e
+interestingArg env clo
+ = go_clo env 0 clo
where
+ go_clo _ n (DoneId v) = go_var n v
+ go_clo env n (DoneEx e _) = go (zapSubstEnv env) n e
+ go_clo env n (ContEx se e _) = go (se `setInScopeFromE` env) n e
+
-- n is # value args to which the expression is applied
- go env n (Var v)
- = case substId env v of
- DoneId v' -> go_var n v'
- DoneEx e _ -> go (zapSubstEnv env) n e
- ContEx se e _mco -> go (se `setInScopeFromE` env) n e
+ go env n (Var v) = go_clo env n (substId env v)
go _ _ (Lit l)
| isLitRubbish l = NonTrivArg -- See (IA3) in Note [Interesting arguments]
@@ -1738,15 +1786,15 @@ is a term (not a coercion) so we can't necessarily inline the latter in
the former.
-}
-preInlineUnconditionally
+preInlineLetUnconditionally
:: SimplEnv -> TopLevelFlag -> InId
- -> StaticEnv -> CoreExpr -> MOutCoercion -- The argument
+ -> InExpr -> SimplEnv -- These two go together
-> Maybe SimplEnv -- Returned env has extended substitution
-- Precondition: rhs satisfies the let-can-float invariant
-- See Note [Core let-can-float invariant] in GHC.Core
-- Reason: we don't want to inline single uses, or discard dead bindings,
-- for unlifted, side-effect-ful bindings
-preInlineUnconditionally env top_lvl bndr rhs_se rhs rhs_mco
+preInlineLetUnconditionally env top_lvl bndr rhs rhs_env
| not pre_inline_unconditionally = Nothing
| not active = Nothing
| isTopLevel top_lvl && isDeadEndId bndr = Nothing -- Note [Top-level bottoming Ids]
@@ -1758,26 +1806,15 @@ preInlineUnconditionally env top_lvl bndr rhs_se rhs rhs_mco
-- See Note [Stable unfoldings and preInlineUnconditionally]
| not (isInlinePragma inline_prag)
- , Just inl <- maybeUnfoldingTemplate unf = assertPpr (isReflMCo rhs_mco) (ppr bndr) $
- Just $! (extend_subst_with inl)
+ , Just inl <- maybeUnfoldingTemplate unf = Just $! (extend_subst_with inl)
| otherwise = Nothing
where
unf = idUnfolding bndr
- -- If the rhs is /not/ already simplified, extend the envt with ContEx, which captures
- -- the the lexical environment for us to restore in `simplInId`.
- -- If the rhs /is/ already simplified, then extend the envt with DoneEx;
- -- That makes `simplInId` call `simplOutExpr` which avoids re-simplifying
- -- the RHS.
- -- See Note [Avoid repeated simplification] in GHC.Core.Opt.Simplify.Iteration
- extend_subst_with inl_rhs
- = extendIdSubst env bndr $!
- case rhs_se of
- Simplified _ -> case rhs_mco of
- MRefl -> DoneEx inl_rhs NotJoinPoint -- Common case
- MCo co -> DoneEx (mkCast inl_rhs co) NotJoinPoint
- UnSimplified rhs_env -> ContEx rhs_env inl_rhs rhs_mco
+ -- The rhs is not yet simplified, so extend the envt with ContEx, which
+ -- captures the lexical environment for us to restore in `simplInId`.
+ extend_subst_with inl_rhs = extendIdSubst env bndr $! ContEx rhs_env inl_rhs MRefl
one_occ IAmDead = True -- Happens in ((\x.1) v)
one_occ OneOcc{ occ_n_br = 1
@@ -1793,39 +1830,6 @@ preInlineUnconditionally env top_lvl bndr rhs_se rhs rhs_mco
-- See Note [pre/postInlineUnconditionally in gentle mode]
inline_prag = idInlinePragma bndr
--- Be very careful before inlining inside a lambda, because (a) we must not
--- invalidate occurrence information, and (b) we want to avoid pushing a
--- single allocation (here) into multiple allocations (inside lambda).
--- Inlining a *function* with a single *saturated* call would be ok, mind you.
--- || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok)
--- where
--- is_cheap = exprIsCheap rhs
--- ok = is_cheap && int_cxt
-
- -- int_cxt The context isn't totally boring
- -- E.g. let f = \ab.BIG in \y. map f xs
- -- Don't want to substitute for f, because then we allocate
- -- its closure every time the \y is called
- -- But: let f = \ab.BIG in \y. map (f y) xs
- -- Now we do want to substitute for f, even though it's not
- -- saturated, because we're going to allocate a closure for
- -- (f y) every time round the loop anyhow.
-
- -- canInlineInLam => free vars of rhs are (Once in_lam) or Many,
- -- so substituting rhs inside a lambda doesn't change the occ info.
- -- Sadly, not quite the same as exprIsHNF.
- canInlineInLam (Lit _) = True
- canInlineInLam (Cast e _) = canInlineInLam e
- canInlineInLam (Lam b e) = isRuntimeVar b || canInlineInLam e
- canInlineInLam (Tick t e) = not (tickishIsCode t) && canInlineInLam e
- canInlineInLam (Var v) = case idOccInfo v of
- OneOcc { occ_in_lam = IsInsideLam } -> True
- ManyOccs {} -> True
- _ -> False
- canInlineInLam _ = False
- -- not ticks. Counting ticks cannot be duplicated, and non-counting
- -- ticks around a Lam will disappear anyway.
-
early_phase =
case sePhase env of
SimplPhase p -> p /= FinalPhase
@@ -1856,6 +1860,90 @@ preInlineUnconditionally env top_lvl bndr rhs_se rhs rhs_mco
-- (Nor can we check for `exprIsExpandable rhs`, because that needs to look
-- at the non-existent unfolding for the `I# 2#` which is also floated out.)
+preInlineBetaUnconditionally
+ :: SimplEnv -> Levity -> InId
+ -> SimplClo -- The argument
+ -> Maybe SimplEnv -- Returned env has extended substitution
+-- Like preInlineLetUnconditionally, but for a beta-redex (\bndr. body) arg
+-- The argument may or may not be already simplified (DoneEx or ContEx)
+--
+-- Compared to preInlineLetUnconditionally we omit some checks:
+-- * The binder is never top-level, so no need for the
+-- Note [Top-level bottoming Ids] check, nor for `early_phase`
+-- * A lambda binder is never a join point, so no need for the
+-- Note [Do not inline exit join points] check
+-- * A lambda binder never has an inline pragma, a stable unfolding, or RULES
+-- (see `lamBndrInfoOK`), so no need to check activation, nor for
+-- Note [Stable unfoldings and preInlineUnconditionally]
+preInlineBetaUnconditionally env levity bndr arg
+ | assertPpr (lamBndrInfoOK bndr) (ppr bndr) $
+ not pre_inline_unconditionally = Nothing
+ | isCoVar bndr = Nothing -- Note [Do not inline CoVars unconditionally]
+ | not (one_occ (idOccInfo bndr)) = Nothing
+ | needs_case_binding = Nothing
+ | otherwise = Just $! extendIdSubst env bndr arg
+ -- If the arg is not yet simplified, it is a ContEx, which captures the
+ -- lexical environment for us to restore in `simplInId`.
+ -- If the arg is already simplified, then it is a DoneEx;
+ -- That makes `simplInId` call `simplOutExpr` which avoids re-simplifying
+ -- the arg.
+ -- See Note [Avoid repeated simplification] in GHC.Core.Opt.Simplify.Iteration
+ where
+ pre_inline_unconditionally = sePreInline env
+
+ one_occ IAmDead = True -- Happens in ((\x.1) v)
+ one_occ OneOcc{ occ_n_br = 1
+ , occ_in_lam = NotInsideLam } = True
+ one_occ OneOcc{ occ_n_br = 1
+ , occ_in_lam = IsInsideLam
+ , occ_int_cxt = IsInteresting } = case arg of
+ ContEx _ e _ -> canInlineInLam e
+ DoneEx e _ -> canInlineInLam e
+ DoneId v -> canInlineInLam (Var v)
+ one_occ _ = False
+
+ -- Enforce the let-can-float invariant
+ -- Ok to test an InExpr in needsCaseBinding because
+ -- exprOkForSpeculation is stable under simplification
+ needs_case_binding = case arg of
+ ContEx _ e _ -> needsCaseBindingL levity e
+ DoneEx e _ -> needsCaseBindingL levity e
+ DoneId v -> needsCaseBindingL levity (Var v)
+
+canInlineInLam :: CoreExpr -> Bool
+-- Be very careful before inlining inside a lambda, because (a) we must not
+-- invalidate occurrence information, and (b) we want to avoid pushing a
+-- single allocation (here) into multiple allocations (inside lambda).
+-- Inlining a *function* with a single *saturated* call would be ok, mind you.
+-- || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok)
+-- where
+-- is_cheap = exprIsCheap rhs
+-- ok = is_cheap && int_cxt
+
+ -- int_cxt The context isn't totally boring
+ -- E.g. let f = \ab.BIG in \y. map f xs
+ -- Don't want to substitute for f, because then we allocate
+ -- its closure every time the \y is called
+ -- But: let f = \ab.BIG in \y. map (f y) xs
+ -- Now we do want to substitute for f, even though it's not
+ -- saturated, because we're going to allocate a closure for
+ -- (f y) every time round the loop anyhow.
+
+ -- canInlineInLam => free vars of rhs are (Once in_lam) or Many,
+ -- so substituting rhs inside a lambda doesn't change the occ info.
+ -- Sadly, not quite the same as exprIsHNF.
+canInlineInLam (Lit _) = True
+canInlineInLam (Cast e _) = canInlineInLam e
+canInlineInLam (Lam b e) = isRuntimeVar b || canInlineInLam e
+canInlineInLam (Tick t e) = not (tickishIsCode t) && canInlineInLam e
+canInlineInLam (Var v) = case idOccInfo v of
+ OneOcc { occ_in_lam = IsInsideLam } -> True
+ ManyOccs {} -> True
+ _ -> False
+canInlineInLam _ = False
+ -- not ticks. Counting ticks cannot be duplicated, and non-counting
+ -- ticks around a Lam will disappear anyway.
+
{-
************************************************************************
* *
=====================================
compiler/GHC/HsToCore/Utils.hs
=====================================
@@ -57,6 +57,7 @@ import GHC.Core.Make
import GHC.Core.Make.Box ( boxTy )
import GHC.Core.Make.BigTuple
import GHC.Types.Id
+import GHC.Types.Id.Info ( vanillaIdInfo )
import GHC.Types.Literal
import GHC.Core.TyCon
import GHC.Core.DataCon
@@ -264,8 +265,14 @@ bindMatchId new mid body
-- Used to force variables when desugaring strict binders. It's crucial that the
-- variable is shadowed by the case binder. See Wrinkle 1 in
-- Note [Desugar Strict binds] in GHC.HsToCore.Binds.
+--
+-- The case binder has the same Name (and hence Unique), type and multiplicity
+-- as `var`, but vanilla IdInfo: `var` may have, say, a NOINLINE pragma, but a
+-- case binder must not; see Note [Lambda and case binders have vanilla IdInfo]
+-- in GHC.Core, and #27965. E.g. `res1` in GHC.Internal.Control.Monad.ST.Lazy.Imp
+-- has a NOINLINE pragma.
seqVar :: Var -> CoreExpr -> CoreExpr
-seqVar var body = mkDefaultCase (Var var) var body
+seqVar var body = mkDefaultCase (Var var) (var `setIdInfo` vanillaIdInfo) body
mkCoLetMatchResult :: HasDebugCallStack => CoreBind -> MatchResult CoreExpr -> MatchResult CoreExpr
mkCoLetMatchResult bind = fmap (mkCoreLet bind)
=====================================
compiler/GHC/Types/Id.hs
=====================================
@@ -94,6 +94,7 @@ module GHC.Types.Id (
idArity,
idCallArity, idFunRepArity,
idSpecialisation, idCoreRules, idHasRules,
+ lamBndrInfoOK,
idCafInfo, idLFInfo_maybe,
idOneShotInfo,
idOccInfo,
@@ -905,6 +906,16 @@ idCoreRules id = ruleInfoRules (idSpecialisation id)
idHasRules :: Id -> Bool
idHasRules id = not (isEmptyRuleInfo (idSpecialisation id))
+-- | True <=> the Id has no (non-default) inline pragma, no stable unfolding,
+-- and no RULES. Lambda binders, case binders, and case-alternative binders
+-- must all satisfy this.
+-- See Note [Lambda and case binders have vanilla IdInfo] in GHC.Core
+lamBndrInfoOK :: Id -> Bool
+lamBndrInfoOK id
+ = isDefaultInlinePragma (idInlinePragma id)
+ && not (isStableUnfolding (realIdUnfolding id))
+ && not (idHasRules id)
+
setIdSpecialisation :: Id -> RuleInfo -> Id
setIdSpecialisation id spec_info = modifyIdInfo (`setRuleInfo` spec_info) id
=====================================
testsuite/tests/simplCore/should_compile/T27962.hs
=====================================
@@ -0,0 +1,16 @@
+{-# LANGUAGE MagicHash #-}
+
+module T27962 where
+
+import GHC.Exts
+
+newtype N = MkN Int
+
+-- After inlining myRun, we get (runRW# @LiftedRep @Int |> co) (\_ -> ...)
+-- and the simplifier pushes co into the argument of runRW#.
+-- #27962: the simplifier dropped that cast, yielding ill-typed Core
+myRun :: (State# RealWorld -> N) -> N
+myRun = coerce (runRW# :: (State# RealWorld -> Int) -> Int)
+{-# INLINE myRun #-}
+
+foo x = myRun (\_ -> MkN (x+1))
=====================================
testsuite/tests/simplCore/should_compile/T27963.hs
=====================================
@@ -0,0 +1,23 @@
+{-# OPTIONS_GHC -Wno-inline-rule-shadowing #-}
+
+module T27963 where
+
+-- This test is pretty delicate because it relies on a function
+-- that has BOTH a rule AND an INLINE pragma
+--
+-- See #27963 for some discussion
+--
+-- Still, it should (just) work
+
+import GHC.Exts
+
+newtype N = MkN Int
+
+f x = x
+{-# INLINE f #-}
+{-# RULES "f/42" forall x. f x = 42::Int #-}
+
+-- The rule "f/42" should fire in both h1 and h2
+h1,h2 :: N -> Int
+h1 n = f (coerce n) + 0
+h2 n = (coerce f) n + 0 -- #27963: the rule did not fire here
=====================================
testsuite/tests/simplCore/should_compile/T27963.stderr
=====================================
@@ -0,0 +1,2 @@
+Rule fired: f/42 (T27963)
+Rule fired: f/42 (T27963)
=====================================
testsuite/tests/simplCore/should_compile/all.T
=====================================
@@ -629,3 +629,6 @@ test('T27749',
test('T27629', only_ways(['optasm']), makefile_test, ['T27629'])
test('T27936', normal, compile, [''])
+test('T27962', normal, compile, [''])
+test('T27962a', [extra_files(['T27962.hs'])], multimod_compile, ['T27962', '-v0 -O'])
+test('T27963', [grep_errmsg(r'f/42')], compile, ['-O -ddump-rule-firings'])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/1b942ca218de354620547f010a7d83…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/1b942ca218de354620547f010a7d83…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0