{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE ScopedTypeVariables #-} {- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1993-1998 A ``lint'' pass to check for Core correctness. See Note [Core Lint guarantee]. -} module GHC.Core.Lint ( lintCoreBindings, lintUnfolding, lintPassResult, lintInteractiveExpr, lintExpr, lintAnnots, lintAxioms, interactiveInScope, -- ** Debug output endPass, endPassIO, displayLintResults, dumpPassResult ) where import GHC.Prelude import GHC.Driver.Session import GHC.Driver.Ppr import GHC.Driver.Env import GHC.Driver.Config.Diagnostic import GHC.Tc.Utils.TcType ( isFloatingPrimTy, isTyFamFree ) import GHC.Unit.Module.ModGuts import GHC.Runtime.Context import GHC.Core import GHC.Core.FVs import GHC.Core.Utils import GHC.Core.Stats ( coreBindsStats ) import GHC.Core.Opt.Monad import GHC.Core.DataCon import GHC.Core.Ppr import GHC.Core.Coercion import GHC.Core.Type as Type import GHC.Core.Multiplicity import GHC.Core.UsageEnv import GHC.Core.TyCo.Rep -- checks validity of types/coercions import GHC.Core.TyCo.Subst import GHC.Core.TyCo.FVs import GHC.Core.TyCo.Ppr ( pprTyVar, pprTyVars ) import GHC.Core.TyCon as TyCon import GHC.Core.Coercion.Axiom import GHC.Core.Unify import GHC.Core.InstEnv ( instanceDFunId, instEnvElts ) import GHC.Core.Coercion.Opt ( checkAxInstCo ) import GHC.Core.Opt.Arity ( typeArity ) import GHC.Types.Literal import GHC.Types.Var as Var import GHC.Types.Var.Env import GHC.Types.Var.Set import GHC.Types.Unique.Set( nonDetEltsUniqSet ) import GHC.Types.Name import GHC.Types.Name.Env import GHC.Types.Id import GHC.Types.Id.Info import GHC.Types.SrcLoc import GHC.Types.Tickish import GHC.Types.RepType import GHC.Types.Basic import GHC.Types.Demand ( splitDmdSig, isDeadEndDiv ) import GHC.Types.TypeEnv import GHC.Builtin.Names import GHC.Builtin.Types.Prim import GHC.Builtin.Types ( multiplicityTy ) import GHC.Data.Bag import GHC.Data.List.SetOps import GHC.Utils.Monad import GHC.Utils.Outputable as Outputable import GHC.Utils.Panic import GHC.Utils.Constants (debugIsOn) import GHC.Utils.Misc import GHC.Utils.Trace import GHC.Utils.Error import qualified GHC.Utils.Error as Err import GHC.Utils.Logger import Control.Monad import Data.Foldable ( toList ) import Data.List.NonEmpty ( NonEmpty(..), groupWith ) import Data.List ( partition ) import Data.Maybe import GHC.Data.Pair import qualified GHC.LanguageExtensions as LangExt {- Note [Core Lint guarantee] ~~~~~~~~~~~~~~~~~~~~~~~~~~ Core Lint is the type-checker for Core. Using it, we get the following guarantee: If all of: 1. Core Lint passes, 2. there are no unsafe coercions (i.e. unsafeEqualityProof), 3. all plugin-supplied coercions (i.e. PluginProv) are valid, and 4. all case-matches are complete then running the compiled program will not seg-fault, assuming no bugs downstream (e.g. in the code generator). This guarantee is quite powerful, in that it allows us to decouple the safety of the resulting program from the type inference algorithm. However, do note point (4) above. Core Lint does not check for incomplete case-matches; see Note [Case expression invariants] in GHC.Core, invariant (4). As explained there, an incomplete case-match might slip by Core Lint and cause trouble at runtime. Note [GHC Formalism] ~~~~~~~~~~~~~~~~~~~~ This file implements the type-checking algorithm for System FC, the "official" name of the Core language. Type safety of FC is heart of the claim that executables produced by GHC do not have segmentation faults. Thus, it is useful to be able to reason about System FC independently of reading the code. To this purpose, there is a document core-spec.pdf built in docs/core-spec that contains a formalism of the types and functions dealt with here. If you change just about anything in this file or you change other types/functions throughout the Core language (all signposted to this note), you should update that formalism. See docs/core-spec/README for more info about how to do so. Note [check vs lint] ~~~~~~~~~~~~~~~~~~~~ This file implements both a type checking algorithm and also general sanity checking. For example, the "sanity checking" checks for TyConApp on the left of an AppTy, which should never happen. These sanity checks don't really affect any notion of type soundness. Yet, it is convenient to do the sanity checks at the same time as the type checks. So, we use the following naming convention: - Functions that begin with 'lint'... are involved in type checking. These functions might also do some sanity checking. - Functions that begin with 'check'... are *not* involved in type checking. They exist only for sanity checking. Issues surrounding variable naming, shadowing, and such are considered *not* to be part of type checking, as the formalism omits these details. Summary of checks ~~~~~~~~~~~~~~~~~ Checks that a set of core bindings is well-formed. The PprStyle and String just control what we print in the event of an error. The Bool value indicates whether we have done any specialisation yet (in which case we do some extra checks). We check for (a) type errors (b) Out-of-scope type variables (c) Out-of-scope local variables (d) Ill-kinded types (e) Incorrect unsafe coercions If we have done specialisation the we check that there are (a) No top-level bindings of primitive (unboxed type) Note [Linting function types] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ As described in Note [Representation of function types], all saturated applications of funTyCon are represented with the FunTy constructor. We check this invariant in lintType. Note [Linting type lets] ~~~~~~~~~~~~~~~~~~~~~~~~ In the desugarer, it's very very convenient to be able to say (in effect) let a = Type Bool in let x::a = True in
That is, use a type let. See Note [Core type and coercion invariant] in "GHC.Core". One place it is used is in mkWwBodies; see Note [Join points and beta-redexes] in GHC.Core.Opt.WorkWrap.Utils. (Maybe there are other "clients" of this feature; I'm not sure). * Hence when linting we need to remember that a=Int, else we might reject a correct program. So we carry a type substitution (in this example [a -> Bool]) and apply this substitution before comparing types. In effect, in Lint, type equality is always equality-modulo-le-subst. This is in the le_subst field of LintEnv. But nota bene: (SI1) The le_subst substitution is applied to types and coercions only (SI2) The result of that substitution is used only to check for type equality, to check well-typed-ness, /but is then discarded/. The result of substittion does not outlive the CoreLint pass. (SI3) The InScopeSet of le_subst includes only TyVar and CoVar binders. * The function lintInTy :: Type -> LintM (Type, Kind) returns a substituted type. * When we encounter a binder (like x::a) we must apply the substitution to the type of the binding variable. lintBinders does this. * Clearly we need to clone tyvar binders as we go. * But take care (#17590)! We must also clone CoVar binders: let a = TYPE (ty |> cv) in \cv -> blah blindly substituting for `a` might capture `cv`. * Alas, when cloning a coercion variable we might choose a unique that happens to clash with an inner Id, thus \cv_66 -> let wild_X7 = blah in blah We decide to clone `cv_66` because it's already in scope. Fine, choose a new unique. Aha, X7 looks good. So we check the lambda body with le_subst of [cv_66 :-> cv_X7] This is all fine, even though we use the same unique as wild_X7. As (SI2) says, we do /not/ return a new lambda (\cv_X7 -> let wild_X7 = blah in ...) We simply use the le_subst substitution in types/coercions only, when checking for equality. * We still need to check that Id occurrences are bound by some enclosing binding. We do /not/ use the InScopeSet for the le_subst for this purpose -- it contains only TyCoVars. Instead we have a separate le_ids for the in-scope Id binders. Sigh. We might want to explore getting rid of type-let! Note [Bad unsafe coercion] ~~~~~~~~~~~~~~~~~~~~~~~~~~ For discussion see https://gitlab.haskell.org/ghc/ghc/wikis/bad-unsafe-coercions Linter introduces additional rules that checks improper coercion between different types, called bad coercions. Following coercions are forbidden: (a) coercions between boxed and unboxed values; (b) coercions between unlifted values of the different sizes, here active size is checked, i.e. size of the actual value but not the space allocated for value; (c) coercions between floating and integral boxed values, this check is not yet supported for unboxed tuples, as no semantics were specified for that; (d) coercions from / to vector type (e) If types are unboxed tuples then tuple (# A_1,..,A_n #) can be coerced to (# B_1,..,B_m #) if n=m and for each pair A_i, B_i rules (a-e) holds. Note [Join points] ~~~~~~~~~~~~~~~~~~ We check the rules listed in Note [Invariants on join points] in GHC.Core. The only one that causes any difficulty is the first: All occurrences must be tail calls. To this end, along with the in-scope set, we remember in le_joins the subset of in-scope Ids that are valid join ids. For example: join j x = ... in case e of A -> jump j y -- good B -> case (jump j z) of -- BAD C -> join h = jump j w in ... -- good D -> let x = jump j v in ... -- BAD A join point remains valid in case branches, so when checking the A branch, j is still valid. When we check the scrutinee of the inner case, however, we set le_joins to empty, and catch the error. Similarly, join points can occur free in RHSes of other join points but not the RHSes of value bindings (thunks and functions). ************************************************************************ * * Beginning and ending passes * * ************************************************************************ These functions are not CoreM monad stuff, but they probably ought to be, and it makes a convenient place for them. They print out stuff before and after core passes, and do Core Lint when necessary. -} endPass :: CoreToDo -> CoreProgram -> [CoreRule] -> CoreM () endPass pass binds rules = do { hsc_env <- getHscEnv ; print_unqual <- getPrintUnqualified ; liftIO $ endPassIO hsc_env print_unqual pass binds rules } endPassIO :: HscEnv -> PrintUnqualified -> CoreToDo -> CoreProgram -> [CoreRule] -> IO () -- Used by the IO-is CorePrep too endPassIO hsc_env print_unqual pass binds rules = do { dumpPassResult logger dump_core_sizes print_unqual mb_flag (showSDoc dflags (ppr pass)) (pprPassDetails pass) binds rules ; lintPassResult hsc_env pass binds } where dump_core_sizes = not (gopt Opt_SuppressCoreSizes dflags) logger = hsc_logger hsc_env dflags = hsc_dflags hsc_env mb_flag = case coreDumpFlag pass of Just flag | logHasDumpFlag logger flag -> Just flag | logHasDumpFlag logger Opt_D_verbose_core2core -> Just flag _ -> Nothing dumpPassResult :: Logger -> Bool -- dump core sizes? -> PrintUnqualified -> Maybe DumpFlag -- Just df => show details in a file whose -- name is specified by df -> String -- Header -> SDoc -- Extra info to appear after header -> CoreProgram -> [CoreRule] -> IO () dumpPassResult logger dump_core_sizes unqual mb_flag hdr extra_info binds rules = do { forM_ mb_flag $ \flag -> do logDumpFile logger (mkDumpStyle unqual) flag hdr FormatCore dump_doc -- Report result size -- This has the side effect of forcing the intermediate to be evaluated -- if it's not already forced by a -ddump flag. ; Err.debugTraceMsg logger 2 size_doc } where size_doc = sep [text "Result size of" <+> text hdr, nest 2 (equals <+> ppr (coreBindsStats binds))] dump_doc = vcat [ nest 2 extra_info , size_doc , blankLine , if dump_core_sizes then pprCoreBindingsWithSize binds else pprCoreBindings binds , ppUnless (null rules) pp_rules ] pp_rules = vcat [ blankLine , text "------ Local rules for imported ids --------" , pprRules rules ] coreDumpFlag :: CoreToDo -> Maybe DumpFlag coreDumpFlag (CoreDoSimplify {}) = Just Opt_D_verbose_core2core coreDumpFlag (CoreDoPluginPass {}) = Just Opt_D_verbose_core2core coreDumpFlag CoreDoFloatInwards = Just Opt_D_verbose_core2core coreDumpFlag (CoreDoFloatOutwards {}) = Just Opt_D_verbose_core2core coreDumpFlag CoreLiberateCase = Just Opt_D_verbose_core2core coreDumpFlag CoreDoStaticArgs = Just Opt_D_verbose_core2core coreDumpFlag CoreDoCallArity = Just Opt_D_dump_call_arity coreDumpFlag CoreDoExitify = Just Opt_D_dump_exitify coreDumpFlag CoreDoDemand = Just Opt_D_dump_stranal coreDumpFlag CoreDoCpr = Just Opt_D_dump_cpranal coreDumpFlag CoreDoWorkerWrapper = Just Opt_D_dump_worker_wrapper coreDumpFlag CoreDoSpecialising = Just Opt_D_dump_spec coreDumpFlag CoreDoSpecConstr = Just Opt_D_dump_spec coreDumpFlag CoreCSE = Just Opt_D_dump_cse coreDumpFlag CoreDesugar = Just Opt_D_dump_ds_preopt coreDumpFlag CoreDesugarOpt = Just Opt_D_dump_ds coreDumpFlag CoreTidy = Just Opt_D_dump_simpl coreDumpFlag CorePrep = Just Opt_D_dump_prep coreDumpFlag CoreOccurAnal = Just Opt_D_dump_occur_anal coreDumpFlag CoreAddCallerCcs = Nothing coreDumpFlag CoreAddLateCcs = Nothing coreDumpFlag CoreDoPrintCore = Nothing coreDumpFlag (CoreDoRuleCheck {}) = Nothing coreDumpFlag CoreDoNothing = Nothing coreDumpFlag (CoreDoPasses {}) = Nothing {- ************************************************************************ * * Top-level interfaces * * ************************************************************************ -} lintPassResult :: HscEnv -> CoreToDo -> CoreProgram -> IO () lintPassResult hsc_env pass binds | not (gopt Opt_DoCoreLinting dflags) = return () | otherwise = do { let warns_and_errs = lintCoreBindings dflags pass (interactiveInScope $ hsc_IC hsc_env) binds ; Err.showPass logger ("Core Linted result of " ++ showPpr dflags pass) ; displayLintResults logger (showLintWarnings pass) (ppr pass) (pprCoreBindings binds) warns_and_errs } where dflags = hsc_dflags hsc_env logger = hsc_logger hsc_env displayLintResults :: Logger -> Bool -- ^ If 'True', display linter warnings. -- If 'False', ignore linter warnings. -> SDoc -- ^ The source of the linted program -> SDoc -- ^ The linted program, pretty-printed -> WarnsAndErrs -> IO () displayLintResults logger display_warnings pp_what pp_pgm (warns, errs) | not (isEmptyBag errs) = do { logMsg logger Err.MCDump noSrcSpan $ withPprStyle defaultDumpStyle (vcat [ lint_banner "errors" pp_what, Err.pprMessageBag errs , text "*** Offending Program ***" , pp_pgm , text "*** End of Offense ***" ]) ; Err.ghcExit logger 1 } | not (isEmptyBag warns) , log_enable_debug (logFlags logger) , display_warnings -- If the Core linter encounters an error, output to stderr instead of -- stdout (#13342) = logMsg logger Err.MCInfo noSrcSpan $ withPprStyle defaultDumpStyle (lint_banner "warnings" pp_what $$ Err.pprMessageBag (mapBag ($$ blankLine) warns)) | otherwise = return () lint_banner :: String -> SDoc -> SDoc lint_banner string pass = text "*** Core Lint" <+> text string <+> text ": in result of" <+> pass <+> text "***" showLintWarnings :: CoreToDo -> Bool -- Disable Lint warnings on the first simplifier pass, because -- there may be some INLINE knots still tied, which is tiresomely noisy showLintWarnings (CoreDoSimplify _ (SimplMode { sm_phase = InitialPhase })) = False showLintWarnings _ = True lintInteractiveExpr :: SDoc -- ^ The source of the linted expression -> HscEnv -> CoreExpr -> IO () lintInteractiveExpr what hsc_env expr | not (gopt Opt_DoCoreLinting dflags) = return () | Just err <- lintExpr dflags (interactiveInScope $ hsc_IC hsc_env) expr = displayLintResults logger False what (pprCoreExpr expr) (emptyBag, err) | otherwise = return () where dflags = hsc_dflags hsc_env logger = hsc_logger hsc_env interactiveInScope :: InteractiveContext -> [Var] -- In GHCi we may lint expressions, or bindings arising from 'deriving' -- clauses, that mention variables bound in the interactive context. -- These are Local things (see Note [Interactively-bound Ids in GHCi] in GHC.Runtime.Context). -- So we have to tell Lint about them, lest it reports them as out of scope. -- -- We do this by find local-named things that may appear free in interactive -- context. This function is pretty revolting and quite possibly not quite right. -- When we are not in GHCi, the interactive context (hsc_IC hsc_env) is empty -- so this is a (cheap) no-op. -- -- See #8215 for an example interactiveInScope ictxt = tyvars ++ ids where -- C.f. GHC.Tc.Module.setInteractiveContext, Desugar.deSugarExpr (cls_insts, _fam_insts) = ic_instances ictxt te1 = mkTypeEnvWithImplicits (ic_tythings ictxt) te = extendTypeEnvWithIds te1 (map instanceDFunId $ instEnvElts cls_insts) ids = typeEnvIds te tyvars = tyCoVarsOfTypesList $ map idType ids -- Why the type variables? How can the top level envt have free tyvars? -- I think it's because of the GHCi debugger, which can bind variables -- f :: [t] -> [t] -- where t is a RuntimeUnk (see TcType) -- | Type-check a 'CoreProgram'. See Note [Core Lint guarantee]. lintCoreBindings :: DynFlags -> CoreToDo -> [Var] -> CoreProgram -> WarnsAndErrs -- Returns (warnings, errors) -- If you edit this function, you may need to update the GHC formalism -- See Note [GHC Formalism] lintCoreBindings dflags pass local_in_scope binds = initL dflags flags local_in_scope $ addLoc TopLevelBindings $ do { checkL (null dups) (dupVars dups) ; checkL (null ext_dups) (dupExtVars ext_dups) ; lintRecBindings TopLevel all_pairs $ \_ -> return () } where all_pairs = flattenBinds binds -- Put all the top-level binders in scope at the start -- This is because rewrite rules can bring something -- into use 'unexpectedly'; see Note [Glomming] in "GHC.Core.Opt.OccurAnal" binders = map fst all_pairs flags = (defaultLintFlags dflags) { lf_check_global_ids = check_globals , lf_check_inline_loop_breakers = check_lbs , lf_check_static_ptrs = check_static_ptrs , lf_check_linearity = check_linearity , lf_check_fixed_rep = check_fixed_rep } -- In the output of the desugarer, before optimisation, -- we have eta-expanded data constructors with representation-polymorphic -- bindings; so we switch off the representation-polymorphism checks. -- The very simple optimiser will beta-reduce them away. -- See Note [Checking for representation-polymorphic built-ins] -- in GHC.HsToCore.Expr. check_fixed_rep = case pass of CoreDesugar -> False _ -> True -- See Note [Checking for global Ids] check_globals = case pass of CoreTidy -> False CorePrep -> False _ -> True -- See Note [Checking for INLINE loop breakers] check_lbs = case pass of CoreDesugar -> False CoreDesugarOpt -> False _ -> True -- See Note [Checking StaticPtrs] check_static_ptrs | not (xopt LangExt.StaticPointers dflags) = AllowAnywhere | otherwise = case pass of CoreDoFloatOutwards _ -> AllowAtTopLevel CoreTidy -> RejectEverywhere CorePrep -> AllowAtTopLevel _ -> AllowAnywhere -- See Note [Linting linearity] check_linearity = gopt Opt_DoLinearCoreLinting dflags || ( case pass of CoreDesugar -> True _ -> False) (_, dups) = removeDups compare binders -- dups_ext checks for names with different uniques -- but the same External name M.n. We don't -- allow this at top level: -- M.n{r3} = ... -- M.n{r29} = ... -- because they both get the same linker symbol ext_dups = snd (removeDups ord_ext (map Var.varName binders)) ord_ext n1 n2 | Just m1 <- nameModule_maybe n1 , Just m2 <- nameModule_maybe n2 = compare (m1, nameOccName n1) (m2, nameOccName n2) | otherwise = LT {- ************************************************************************ * * \subsection[lintUnfolding]{lintUnfolding} * * ************************************************************************ Note [Linting Unfoldings from Interfaces] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We use this to check all top-level unfoldings that come in from interfaces (it is very painful to catch errors otherwise). We do not need to call lintUnfolding on unfoldings that are nested within top-level unfoldings; they are linted when we lint the top-level unfolding; hence the `TopLevelFlag` on `tcPragExpr` in GHC.IfaceToCore. -} lintUnfolding :: Bool -- ^ True <=> is a compulsory unfolding -> DynFlags -> SrcLoc -> VarSet -- ^ Treat these as in scope -> CoreExpr -> Maybe (Bag SDoc) -- Nothing => OK lintUnfolding is_compulsory dflags locn var_set expr | isEmptyBag errs = Nothing | otherwise = Just errs where vars = nonDetEltsUniqSet var_set (_warns, errs) = initL dflags (defaultLintFlags dflags) vars $ if is_compulsory -- See Note [Checking for representation polymorphism] then noFixedRuntimeRepChecks linter else linter linter = addLoc (ImportedUnfolding locn) $ lintCoreExpr expr lintExpr :: DynFlags -> [Var] -- Treat these as in scope -> CoreExpr -> Maybe (Bag SDoc) -- Nothing => OK lintExpr dflags vars expr | isEmptyBag errs = Nothing | otherwise = Just errs where (_warns, errs) = initL dflags (defaultLintFlags dflags) vars linter linter = addLoc TopLevelBindings $ lintCoreExpr expr {- ************************************************************************ * * \subsection[lintCoreBinding]{lintCoreBinding} * * ************************************************************************ Check a core binding, returning the list of variables bound. -} -- Returns a UsageEnv because this function is called in lintCoreExpr for -- Let lintRecBindings :: TopLevelFlag -> [(Id, CoreExpr)] -> ([LintedId] -> LintM a) -> LintM (a, [UsageEnv]) lintRecBindings top_lvl pairs thing_inside = lintIdBndrs top_lvl bndrs $ \ bndrs' -> do { ues <- zipWithM lint_pair bndrs' rhss ; a <- thing_inside bndrs' ; return (a, ues) } where (bndrs, rhss) = unzip pairs lint_pair bndr' rhs = addLoc (RhsOf bndr') $ do { (rhs_ty, ue) <- lintRhs bndr' rhs -- Check the rhs ; lintLetBind top_lvl Recursive bndr' rhs rhs_ty ; return ue } lintLetBody :: [LintedId] -> CoreExpr -> LintM (LintedType, UsageEnv) lintLetBody bndrs body = do { (body_ty, body_ue) <- addLoc (BodyOfLetRec bndrs) (lintCoreExpr body) ; mapM_ (lintJoinBndrType body_ty) bndrs ; return (body_ty, body_ue) } lintLetBind :: TopLevelFlag -> RecFlag -> LintedId -> CoreExpr -> LintedType -> LintM () -- Binder's type, and the RHS, have already been linted -- This function checks other invariants lintLetBind top_lvl rec_flag binder rhs rhs_ty = do { let binder_ty = idType binder ; ensureEqTys binder_ty rhs_ty (mkRhsMsg binder (text "RHS") rhs_ty) -- If the binding is for a CoVar, the RHS should be (Coercion co) -- See Note [Core type and coercion invariant] in GHC.Core ; checkL (not (isCoVar binder) || isCoArg rhs) (mkLetErr binder rhs) -- Check the let/app invariant -- See Note [Core let/app invariant] in GHC.Core ; checkL ( isJoinId binder || mightBeLiftedType binder_ty || (isNonRec rec_flag && exprOkForSpeculation rhs) || isDataConWorkId binder || isDataConWrapId binder -- until #17521 is fixed || exprIsTickedString rhs) (badBndrTyMsg binder (text "unlifted")) -- Check that if the binder is at the top level and has type Addr#, -- that it is a string literal. -- See Note [Core top-level string literals]. ; checkL (not (isTopLevel top_lvl && binder_ty `eqType` addrPrimTy) || exprIsTickedString rhs) (mkTopNonLitStrMsg binder) ; flags <- getLintFlags -- Check that a join-point binder has a valid type -- NB: lintIdBinder has checked that it is not top-level bound ; case isJoinId_maybe binder of Nothing -> return () Just arity -> checkL (isValidJoinPointType arity binder_ty) (mkInvalidJoinPointMsg binder binder_ty) ; when (lf_check_inline_loop_breakers flags && isStableUnfolding (realIdUnfolding binder) && isStrongLoopBreaker (idOccInfo binder) && isInlinePragma (idInlinePragma binder)) (addWarnL (text "INLINE binder is (non-rule) loop breaker:" <+> ppr binder)) -- Only non-rule loop breakers inhibit inlining -- We used to check that the dmdTypeDepth of a demand signature never -- exceeds idArity, but that is an unnecessary complication, see -- Note [idArity varies independently of dmdTypeDepth] in GHC.Core.Opt.DmdAnal -- Check that the binder's arity is within the bounds imposed by -- the type and the strictness signature. See Note [exprArity invariant] -- and Note [Trimming arity] ; checkL (typeArity (idType binder) `lengthAtLeast` idArity binder) (text "idArity" <+> ppr (idArity binder) <+> text "exceeds typeArity" <+> ppr (length (typeArity (idType binder))) <> colon <+> ppr binder) ; case splitDmdSig (idDmdSig binder) of (demands, result_info) | isDeadEndDiv result_info -> checkL (demands `lengthAtLeast` idArity binder) (text "idArity" <+> ppr (idArity binder) <+> text "exceeds arity imposed by the strictness signature" <+> ppr (idDmdSig binder) <> colon <+> ppr binder) _ -> return () ; addLoc (RuleOf binder) $ mapM_ (lintCoreRule binder binder_ty) (idCoreRules binder) ; addLoc (UnfoldingOf binder) $ lintIdUnfolding binder binder_ty (idUnfolding binder) ; return () } -- We should check the unfolding, if any, but this is tricky because -- the unfolding is a SimplifiableCoreExpr. Give up for now. -- | Checks the RHS of bindings. It only differs from 'lintCoreExpr' -- in that it doesn't reject occurrences of the function 'makeStatic' when they -- appear at the top level and @lf_check_static_ptrs == AllowAtTopLevel@, and -- for join points, it skips the outer lambdas that take arguments to the -- join point. -- -- See Note [Checking StaticPtrs]. lintRhs :: Id -> CoreExpr -> LintM (LintedType, UsageEnv) -- NB: the Id can be Linted or not -- it's only used for -- its OccInfo and join-pointer-hood lintRhs bndr rhs | Just arity <- isJoinId_maybe bndr = lintJoinLams arity (Just bndr) rhs | AlwaysTailCalled arity <- tailCallInfo (idOccInfo bndr) = lintJoinLams arity Nothing rhs -- Allow applications of the data constructor @StaticPtr@ at the top -- but produce errors otherwise. lintRhs _bndr rhs = fmap lf_check_static_ptrs getLintFlags >>= go where -- Allow occurrences of 'makeStatic' at the top-level but produce errors -- otherwise. go :: StaticPtrCheck -> LintM (OutType, UsageEnv) go AllowAtTopLevel | (binders0, rhs') <- collectTyBinders rhs , Just (fun, t, info, e) <- collectMakeStaticArgs rhs' = markAllJoinsBad $ foldr -- imitate @lintCoreExpr (Lam ...)@ lintLambda -- imitate @lintCoreExpr (App ...)@ (do fun_ty_ue <- lintCoreExpr fun lintCoreArgs fun_ty_ue [Type t, info, e] ) binders0 go _ = markAllJoinsBad $ lintCoreExpr rhs -- | Lint the RHS of a join point with expected join arity of @n@ (see Note -- [Join points] in "GHC.Core"). lintJoinLams :: JoinArity -> Maybe Id -> CoreExpr -> LintM (LintedType, UsageEnv) lintJoinLams join_arity enforce rhs = go join_arity rhs where go 0 expr = lintCoreExpr expr go n (Lam var body) = lintLambda var $ go (n-1) body go n expr | Just bndr <- enforce -- Join point with too few RHS lambdas = failWithL $ mkBadJoinArityMsg bndr join_arity n rhs | otherwise -- Future join point, not yet eta-expanded = markAllJoinsBad $ lintCoreExpr expr -- Body of lambda is not a tail position lintIdUnfolding :: Id -> Type -> Unfolding -> LintM () lintIdUnfolding bndr bndr_ty uf | isStableUnfolding uf , Just rhs <- maybeUnfoldingTemplate uf = do { ty <- fst <$> (if isCompulsoryUnfolding uf then noFixedRuntimeRepChecks $ lintRhs bndr rhs -- ^^^^^^^^^^^^^^^^^^^^^^^ -- See Note [Checking for representation polymorphism] else lintRhs bndr rhs) ; ensureEqTys bndr_ty ty (mkRhsMsg bndr (text "unfolding") ty) } lintIdUnfolding _ _ _ = return () -- Do not Lint unstable unfoldings, because that leads -- to exponential behaviour; c.f. GHC.Core.FVs.idUnfoldingVars {- Note [Checking for INLINE loop breakers] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It's very suspicious if a strong loop breaker is marked INLINE. However, the desugarer generates instance methods with INLINE pragmas that form a mutually recursive group. Only after a round of simplification are they unravelled. So we suppress the test for the desugarer. Note [Checking for representation polymorphism] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We ordinarily want to check for bad representation polymorphism. See Note [Representation polymorphism invariants] in GHC.Core. However, we do *not* want to do this in a compulsory unfolding. Compulsory unfoldings arise only internally, for things like newtype wrappers, dictionaries, and (notably) unsafeCoerce#. These might legitimately be representation-polymorphic; indeed representation-polymorphic unfoldings are a primary reason for the very existence of compulsory unfoldings (we can't compile code for the original, representation-polymorphic, binding). It is vitally important that we do representation polymorphism checks *after* performing the unfolding, but not beforehand. This is all safe because we will check any unfolding after it has been unfolded; checking the unfolding beforehand is merely an optimization, and one that actively hurts us here. Note [Linting of runRW#] ~~~~~~~~~~~~~~~~~~~~~~~~ runRW# has some very special behavior (see Note [runRW magic] in GHC.CoreToStg.Prep) which CoreLint must accommodate, by allowing join points in its argument. For example, this is fine: join j x = ... in runRW# (\s. case v of A -> j 3 B -> j 4) Usually those calls to the join point 'j' would not be valid tail calls, because they occur in a function argument. But in the case of runRW# they are fine, because runRW# (\s.e) behaves operationally just like e. (runRW# is ultimately inlined in GHC.CoreToStg.Prep.) In the case that the continuation is /not/ a lambda we simply disable this special behaviour. For example, this is /not/ fine: join j = ... in runRW# @r @ty (jump j) ************************************************************************ * * \subsection[lintCoreExpr]{lintCoreExpr} * * ************************************************************************ -} -- Linted things: substitution applied, and type is linted type LintedType = Type type LintedKind = Kind type LintedCoercion = Coercion type LintedTyCoVar = TyCoVar type LintedId = Id -- | Lint an expression cast through the given coercion, returning the type -- resulting from the cast. lintCastExpr :: CoreExpr -> LintedType -> Coercion -> LintM LintedType lintCastExpr expr expr_ty co = do { co' <- lintCoercion co ; let (Pair from_ty to_ty, role) = coercionKindRole co' ; checkValueType to_ty $ text "target of cast" <+> quotes (ppr co') ; lintRole co' Representational role ; ensureEqTys from_ty expr_ty (mkCastErr expr co' from_ty expr_ty) ; return to_ty } lintCoreExpr :: CoreExpr -> LintM (LintedType, UsageEnv) -- The returned type has the substitution from the monad -- already applied to it: -- lintCoreExpr e subst = exprType (subst e) -- -- The returned "type" can be a kind, if the expression is (Type ty) -- If you edit this function, you may need to update the GHC formalism -- See Note [GHC Formalism] lintCoreExpr (Var var) = do var_pair@(var_ty, _) <- lintIdOcc var 0 checkCanEtaExpand (Var var) [] var_ty return var_pair lintCoreExpr (Lit lit) = return (literalType lit, zeroUE) lintCoreExpr (Cast expr co) = do (expr_ty, ue) <- markAllJoinsBad $ lintCoreExpr expr to_ty <- lintCastExpr expr expr_ty co return (to_ty, ue) lintCoreExpr (Tick tickish expr) = do case tickish of Breakpoint _ _ ids -> forM_ ids $ \id -> do checkDeadIdOcc id lookupIdInScope id _ -> return () markAllJoinsBadIf block_joins $ lintCoreExpr expr where block_joins = not (tickish `tickishScopesLike` SoftScope) -- TODO Consider whether this is the correct rule. It is consistent with -- the simplifier's behaviour - cost-centre-scoped ticks become part of -- the continuation, and thus they behave like part of an evaluation -- context, but soft-scoped and non-scoped ticks simply wrap the result -- (see Simplify.simplTick). lintCoreExpr (Let (NonRec tv (Type ty)) body) | isTyVar tv = -- See Note [Linting type lets] do { ty' <- lintType ty ; lintTyBndr tv $ \ tv' -> do { addLoc (RhsOf tv) $ lintTyKind tv' ty' -- Now extend the substitution so we -- take advantage of it in the body ; extendTvSubstL tv ty' $ addLoc (BodyOfLetRec [tv]) $ lintCoreExpr body } } lintCoreExpr (Let (NonRec bndr rhs) body) | isId bndr = do { -- First Lint the RHS, before bringing the binder into scope (rhs_ty, let_ue) <- lintRhs bndr rhs -- See Note [Multiplicity of let binders] in Var -- Now lint the binder ; lintBinder LetBind bndr $ \bndr' -> do { lintLetBind NotTopLevel NonRecursive bndr' rhs rhs_ty ; addAliasUE bndr let_ue (lintLetBody [bndr'] body) } } | otherwise = failWithL (mkLetErr bndr rhs) -- Not quite accurate lintCoreExpr e@(Let (Rec pairs) body) = do { -- Check that the list of pairs is non-empty checkL (not (null pairs)) (emptyRec e) -- Check that there are no duplicated binders ; let (_, dups) = removeDups compare bndrs ; checkL (null dups) (dupVars dups) -- Check that either all the binders are joins, or none ; checkL (all isJoinId bndrs || all (not . isJoinId) bndrs) $ mkInconsistentRecMsg bndrs -- See Note [Multiplicity of let binders] in Var ; ((body_type, body_ue), ues) <- lintRecBindings NotTopLevel pairs $ \ bndrs' -> lintLetBody bndrs' body ; return (body_type, body_ue `addUE` scaleUE Many (foldr1 addUE ues)) } where bndrs = map fst pairs lintCoreExpr e@(App _ _) | Var fun <- fun , fun `hasKey` runRWKey -- N.B. we may have an over-saturated application of the form: -- runRW (\s -> \x -> ...) y , ty_arg1 : ty_arg2 : arg3 : rest <- args = do { fun_pair1 <- lintCoreArg (idType fun, zeroUE) ty_arg1 ; (fun_ty2, ue2) <- lintCoreArg fun_pair1 ty_arg2 -- See Note [Linting of runRW#] ; let lintRunRWCont :: CoreArg -> LintM (LintedType, UsageEnv) lintRunRWCont expr@(Lam _ _) = lintJoinLams 1 (Just fun) expr lintRunRWCont other = markAllJoinsBad $ lintCoreExpr other -- TODO: Look through ticks? ; (arg3_ty, ue3) <- lintRunRWCont arg3 ; app_ty <- lintValApp arg3 fun_ty2 arg3_ty ue2 ue3 ; lintCoreArgs app_ty rest } | otherwise = do { fun_pair <- lintCoreFun fun (length args) ; app_pair@(app_ty, _) <- lintCoreArgs fun_pair args ; checkCanEtaExpand fun args app_ty ; return app_pair} where (fun, args, _source_ticks) = collectArgsTicks tickishFloatable e -- We must look through source ticks to avoid #21152, for example: -- -- reallyUnsafePtrEquality -- = \ @a -> -- (src