{"id":"1aa3d4d83362ba49","repo":"rust-lang/rust","slug":"could-not-compute-layout-for-ty-e","errorCode":null,"errorMessage":"could not compute layout for {ty:?}: {e:?}","messagePattern":"could not compute layout for (.+?): (.+?)","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"critical","filePath":"compiler/rustc_middle/src/mir/statement.rs","lineNumber":666,"sourceCode":"    }\n\n    pub fn is_move(&self) -> bool {\n        matches!(self, Operand::Move(..))\n    }\n\n    /// Convenience helper to make a literal-like constant from a given scalar value.\n    /// Since this is used to synthesize MIR, assumes `user_ty` is None.\n    pub fn const_from_scalar(\n        tcx: TyCtxt<'tcx>,\n        ty: Ty<'tcx>,\n        val: Scalar,\n        span: Span,\n    ) -> Operand<'tcx> {\n        debug_assert!({\n            let typing_env = ty::TypingEnv::fully_monomorphized();\n            let type_size = tcx\n                .layout_of(typing_env.as_query_input(ty))\n                .unwrap_or_else(|e| panic!(\"could not compute layout for {ty:?}: {e:?}\"))\n                .size;\n            let scalar_size = match val {\n                Scalar::Int(int) => int.size(),\n                _ => panic!(\"Invalid scalar type {val:?}\"),\n            };\n            scalar_size == type_size\n        });\n        Operand::Constant(Box::new(ConstOperand {\n            span,\n            user_ty: None,\n            const_: Const::Val(ConstValue::Scalar(val), ty),\n        }))\n    }\n\n    pub fn to_copy(&self) -> Self {\n        match *self {\n            Operand::Copy(_) | Operand::Constant(_) | Operand::RuntimeChecks(_) => self.clone(),\n            Operand::Move(place) => Operand::Copy(place),","sourceCodeStart":648,"sourceCodeEnd":684,"githubUrl":"https://github.com/rust-lang/rust/blob/22057b88b091743bc0fd8d592a9264f0a6951403/compiler/rustc_middle/src/mir/statement.rs#L648-L684","documentation":"`Operand::const_from_scalar` has a debug-only assertion that calls `tcx.layout_of(ty)` under a fully-monomorphized `TypingEnv` and panics if it returns Err. rustc_middle throws this to catch codegen/const-eval paths that build a scalar constant for a type whose layout cannot be computed (e.g. unsized, recursive, or not-yet-monomorphized types). Because it sits inside `debug_assert!`, this only fires on debug builds of the compiler.","triggerScenarios":"Triggered in a debug rustc build when a caller invokes `const_from_scalar(tcx, ty, val, span)` with a `ty` for which `tcx.layout_of` errors under `TypingEnv::fully_monomorphized()` — e.g. a generic type whose monomorphization is incomplete, an unsized type, or a type with a cycle/error in its layout computation.","commonSituations":"Building/using a debug (non-release) rustc to compile code that synthesizes scalar constants; const-eval or mir-opt test that passes an errorful/generic type; out-of-tree codegen backend that calls `const_from_scalar` with the wrong type; regression where a normalization step is skipped.","solutions":["Confirm the type passed to `const_from_scalar` is fully monomorphized and sized; substitute generic params before calling.","If you only see this on a debug rustc, also test on a release build to confirm whether the assertion is the only problem (release will skip it but may ICE later).","In your own backend/pass, gate `const_from_scalar` behind a `layout_of` probe and route layout-less types elsewhere instead of relying on the assert.","Report an ICE against rustc with the failing type, attaching the layout error (`{e:?}`) and the call site."],"exampleFix":"// before\nlet op = Operand::const_from_scalar(tcx, ty, val, span);\n// debug rustc panic: could not compute layout for Generic<T>: ...\n\n// after: substitute / monomorphize first\nlet mono_ty = ty.subst(tcx, concrete_args);\nassert!(tcx.layout_of(typing_env.as_query_input(mono_ty)).is_ok());\nlet op = Operand::const_from_scalar(tcx, mono_ty, val, span);","handlingStrategy":"validation","validationCode":"// const_from_scalar() computes layout_of(ty) and panics if it errors.\n// (It is wrapped in debug_assert!, so it bites debug builds / assertions-on builds.)\n// Pre-compute the layout and skip scalar const construction if it can't be laid out.\nuse rustc_middle::ty::{self, Ty, TyCtxt, TypingEnv};\nfn ty_has_layout<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool {\n    let typing_env = TypingEnv::fully_monomorphized();\n    tcx.layout_of(typing_env.as_query_input(ty)).is_ok()\n}\n// Usage:\n//   if ty_has_layout(tcx, ty) {\n//       Operand::const_from_scalar(tcx, ty, scalar, span)\n//   } else {\n//       // type is not sized/representable: synthesize via const-eval instead\n//   }","typeGuard":null,"tryCatchPattern":"// Guard the whole scalar-const synthesis so an opaque layout failure degrades gracefully.\nuse std::panic::{catch_unwind, AssertUnwindSafe};\nlet operand = catch_unwind(AssertUnwindSafe(|| {\n    Operand::const_from_scalar(tcx, ty, scalar, span)\n}));\nmatch operand {\n    Ok(op) => op,\n    Err(_payload) => {\n        // layout could not be computed: fall back to an evaluated/unreduced constant\n        // rather than feeding a scalar whose size we cannot verify.\n        Operand::Constant(Box::new(ConstOperand { span, user_ty: None, const_: Const::Ty(ty, err_const) }))\n    }\n}","preventionTips":["Only synthesize scalar constants for fully-monomorphized, sized, representable types; extern types, unsized types, and types needing recursion-depth layout will fail layout_of.","Run `tcx.layout_of` yourself before building a scalar constant so a layout error is a handled branch, not a debug-assertion panic.","Remember this check lives in `debug_assert!`: it is silent in optimized builds but will crash debug builds of rustc/rustdoc/clippy/miri — test your driver in debug mode.","If you receive a Scalar from external data (e.g. deserialized rmeta), validate both the layout AND the scalar size (see [259]) before constructing the Operand."],"tags":["rustc","mir","layout","debug-assert","const-eval"],"analyzedSha":"22057b88b091743bc0fd8d592a9264f0a6951403","analyzedAt":"2026-08-03T08:09:25.915Z","schemaVersion":2}