390 lines
22 KiB
HTML
390 lines
22 KiB
HTML
<!DOCTYPE HTML>
|
|
<html lang="en" class="light sidebar-visible" dir="ltr">
|
|
<head>
|
|
<!-- Book generated using mdBook -->
|
|
<meta charset="UTF-8">
|
|
<title>Drop elaboration - Rust Compiler Development Guide</title>
|
|
|
|
|
|
<!-- Custom HTML head -->
|
|
|
|
<meta name="description" content="A guide to developing the Rust compiler (rustc)">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
<meta name="theme-color" content="#ffffff">
|
|
|
|
<link rel="icon" href="../favicon.svg">
|
|
<link rel="shortcut icon" href="../favicon.png">
|
|
<link rel="stylesheet" href="../css/variables.css">
|
|
<link rel="stylesheet" href="../css/general.css">
|
|
<link rel="stylesheet" href="../css/chrome.css">
|
|
<link rel="stylesheet" href="../css/print.css" media="print">
|
|
|
|
<!-- Fonts -->
|
|
<link rel="stylesheet" href="../FontAwesome/css/font-awesome.css">
|
|
<link rel="stylesheet" href="../fonts/fonts.css">
|
|
|
|
<!-- Highlight.js Stylesheets -->
|
|
<link rel="stylesheet" id="highlight-css" href="../highlight.css">
|
|
<link rel="stylesheet" id="tomorrow-night-css" href="../tomorrow-night.css">
|
|
<link rel="stylesheet" id="ayu-highlight-css" href="../ayu-highlight.css">
|
|
|
|
<!-- Custom theme stylesheets -->
|
|
|
|
|
|
<!-- Provide site root and default themes to javascript -->
|
|
<script>
|
|
const path_to_root = "../";
|
|
const default_light_theme = "light";
|
|
const default_dark_theme = "navy";
|
|
</script>
|
|
<!-- Start loading toc.js asap -->
|
|
<script src="../toc.js"></script>
|
|
</head>
|
|
<body>
|
|
<div id="body-container">
|
|
<!-- Work around some values being stored in localStorage wrapped in quotes -->
|
|
<script>
|
|
try {
|
|
let theme = localStorage.getItem('mdbook-theme');
|
|
let sidebar = localStorage.getItem('mdbook-sidebar');
|
|
|
|
if (theme.startsWith('"') && theme.endsWith('"')) {
|
|
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
|
|
}
|
|
|
|
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
|
|
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
|
|
}
|
|
} catch (e) { }
|
|
</script>
|
|
|
|
<!-- Set the theme before any content is loaded, prevents flash -->
|
|
<script>
|
|
const default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? default_dark_theme : default_light_theme;
|
|
let theme;
|
|
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
|
|
if (theme === null || theme === undefined) { theme = default_theme; }
|
|
const html = document.documentElement;
|
|
html.classList.remove('light')
|
|
html.classList.add(theme);
|
|
html.classList.add("js");
|
|
</script>
|
|
|
|
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
|
|
|
|
<!-- Hide / unhide sidebar before it is displayed -->
|
|
<script>
|
|
let sidebar = null;
|
|
const sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
|
|
if (document.body.clientWidth >= 1080) {
|
|
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
|
|
sidebar = sidebar || 'visible';
|
|
} else {
|
|
sidebar = 'hidden';
|
|
}
|
|
sidebar_toggle.checked = sidebar === 'visible';
|
|
html.classList.remove('sidebar-visible');
|
|
html.classList.add("sidebar-" + sidebar);
|
|
</script>
|
|
|
|
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
|
|
<!-- populated by js -->
|
|
<mdbook-sidebar-scrollbox class="sidebar-scrollbox"></mdbook-sidebar-scrollbox>
|
|
<noscript>
|
|
<iframe class="sidebar-iframe-outer" src="../toc.html"></iframe>
|
|
</noscript>
|
|
<div id="sidebar-resize-handle" class="sidebar-resize-handle">
|
|
<div class="sidebar-resize-indicator"></div>
|
|
</div>
|
|
</nav>
|
|
|
|
<div id="page-wrapper" class="page-wrapper">
|
|
|
|
<div class="page">
|
|
<div id="menu-bar-hover-placeholder"></div>
|
|
<div id="menu-bar" class="menu-bar sticky">
|
|
<div class="left-buttons">
|
|
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
|
|
<i class="fa fa-bars"></i>
|
|
</label>
|
|
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
|
|
<i class="fa fa-paint-brush"></i>
|
|
</button>
|
|
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
|
|
<li role="none"><button role="menuitem" class="theme" id="default_theme">Auto</button></li>
|
|
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
|
|
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
|
|
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
|
|
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
|
|
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
|
|
</ul>
|
|
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
|
|
<i class="fa fa-search"></i>
|
|
</button>
|
|
</div>
|
|
|
|
<h1 class="menu-title">Rust Compiler Development Guide</h1>
|
|
|
|
<div class="right-buttons">
|
|
<a href="../print.html" title="Print this book" aria-label="Print this book">
|
|
<i id="print-button" class="fa fa-print"></i>
|
|
</a>
|
|
<a href="https://github.com/rust-lang/rustc-dev-guide" title="Git repository" aria-label="Git repository">
|
|
<i id="git-repository-button" class="fa fa-github"></i>
|
|
</a>
|
|
<a href="https://github.com/rust-lang/rustc-dev-guide/edit/master/src/mir/drop-elaboration.md" title="Suggest an edit" aria-label="Suggest an edit">
|
|
<i id="git-edit-button" class="fa fa-edit"></i>
|
|
</a>
|
|
|
|
</div>
|
|
</div>
|
|
|
|
<div id="search-wrapper" class="hidden">
|
|
<form id="searchbar-outer" class="searchbar-outer">
|
|
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
|
|
</form>
|
|
<div id="searchresults-outer" class="searchresults-outer hidden">
|
|
<div id="searchresults-header" class="searchresults-header"></div>
|
|
<ul id="searchresults">
|
|
</ul>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
|
|
<script>
|
|
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
|
|
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
|
|
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
|
|
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
|
|
});
|
|
</script>
|
|
|
|
<div id="content" class="content">
|
|
<main>
|
|
<h1 id="drop-elaboration"><a class="header" href="#drop-elaboration">Drop elaboration</a></h1>
|
|
<ul>
|
|
<li><a href="#dynamic-drops">Dynamic drops</a></li>
|
|
<li><a href="#drop-obligations">Drop obligations</a></li>
|
|
<li><a href="#drop-elaboration">Drop elaboration</a></li>
|
|
<li><a href="#drop-elaboration-in-rustc">Drop elaboration in <code>rustc</code></a>
|
|
<ul>
|
|
<li><a href="#open-drops"><code>Open</code> drops</a></li>
|
|
<li><a href="#cleanup-paths">Cleanup paths</a></li>
|
|
</ul>
|
|
</li>
|
|
<li><a href="#aside-drop-elaboration-and-const-eval">Aside: drop elaboration and const-eval</a></li>
|
|
</ul>
|
|
<h2 id="dynamic-drops"><a class="header" href="#dynamic-drops">Dynamic drops</a></h2>
|
|
<p>According to the <a href="https://doc.rust-lang.org/reference/destructors.html">reference</a>:</p>
|
|
<blockquote>
|
|
<p>When an initialized variable or temporary goes out of scope, its destructor
|
|
is run, or it is dropped. Assignment also runs the destructor of its
|
|
left-hand operand, if it's initialized. If a variable has been partially
|
|
initialized, only its initialized fields are dropped.</p>
|
|
</blockquote>
|
|
<p>When building the MIR, the <code>Drop</code> and <code>DropAndReplace</code> terminators represent
|
|
places where drops may occur. However, in this phase, the presence of these
|
|
terminators does not guarantee that a destructor will run. That's because the
|
|
target of a drop may be uninitialized (usually because it has been moved from)
|
|
before the terminator is reached. In general, we cannot know at compile-time whether a
|
|
variable is initialized.</p>
|
|
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
|
</span><span class="boring">fn main() {
|
|
</span>let mut y = vec![];
|
|
|
|
{
|
|
let x = vec![1, 2, 3];
|
|
if std::process::id() % 2 == 0 {
|
|
y = x; // conditionally move `x` into `y`
|
|
}
|
|
} // `x` goes out of scope here. Should it be dropped?
|
|
<span class="boring">}</span></code></pre></pre>
|
|
<p>In these cases, we need to keep track of whether a variable is initialized
|
|
<em>dynamically</em>. The rules are laid out in detail in <a href="https://rust-lang.github.io/rfcs/0320-nonzeroing-dynamic-drop.html">RFC 320: Non-zeroing
|
|
dynamic drops</a>.</p>
|
|
<h2 id="drop-obligations"><a class="header" href="#drop-obligations">Drop obligations</a></h2>
|
|
<p>From the RFC:</p>
|
|
<blockquote>
|
|
<p>When a local variable becomes initialized, it establishes a set of "drop
|
|
obligations": a set of structural paths (e.g. a local <code>a</code>, or a path to a
|
|
field <code>b.f.y</code>) that need to be dropped.</p>
|
|
<p>The drop obligations for a local variable x of struct-type <code>T</code> are computed
|
|
from analyzing the structure of <code>T</code>. If <code>T</code> itself implements <code>Drop</code>, then <code>x</code> is a
|
|
drop obligation. If <code>T</code> does not implement <code>Drop</code>, then the set of drop
|
|
obligations is the union of the drop obligations of the fields of <code>T</code>.</p>
|
|
</blockquote>
|
|
<p>When a structural path is moved from (and thus becomes uninitialized), any drop
|
|
obligations for that path or its descendants (<code>path.f</code>, <code>path.f.g.h</code>, etc.) are
|
|
released. Types with <code>Drop</code> implementations do not permit moves from individual
|
|
fields, so there is no need to track initializedness through them.</p>
|
|
<p>When a local variable goes out of scope (<code>Drop</code>), or when a structural path is
|
|
overwritten via assignment (<code>DropAndReplace</code>), we check for any drop
|
|
obligations for that variable or path. Unless that obligation has been
|
|
released by this point, its associated <code>Drop</code> implementation will be called.
|
|
For <code>enum</code> types, only fields corresponding to the "active" variant need to be
|
|
dropped. When processing drop obligations for such types, we first check the
|
|
discriminant to determine the active variant. All drop obligations for variants
|
|
besides the active one are ignored.</p>
|
|
<p>Here are a few interesting types to help illustrate these rules:</p>
|
|
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
|
</span><span class="boring">fn main() {
|
|
</span>struct NoDrop(u8); // No `Drop` impl. No fields with `Drop` impls.
|
|
|
|
struct NeedsDrop(Vec<u8>); // No `Drop` impl but has fields with `Drop` impls.
|
|
|
|
struct ThinVec(*const u8); // Custom `Drop` impl. Individual fields cannot be moved from.
|
|
|
|
impl Drop for ThinVec {
|
|
fn drop(&mut self) { /* ... */ }
|
|
}
|
|
|
|
enum MaybeDrop {
|
|
Yes(NeedsDrop),
|
|
No(NoDrop),
|
|
}
|
|
<span class="boring">}</span></code></pre></pre>
|
|
<h2 id="drop-elaboration-1"><a class="header" href="#drop-elaboration-1">Drop elaboration</a></h2>
|
|
<p>One valid model for these rules is to keep a boolean flag (a "drop flag") for
|
|
every structural path that is used at any point in the function. This flag is
|
|
set when its path is initialized and is cleared when the path is moved from.
|
|
When a <code>Drop</code> occurs, we check the flags for every obligation associated with
|
|
the target of the <code>Drop</code> and call the associated <code>Drop</code> impl for those that are
|
|
still applicable.</p>
|
|
<p>This process—transforming the newly built MIR with its imprecise <code>Drop</code> and
|
|
<code>DropAndReplace</code> terminators into one with drop flags—is known as drop
|
|
elaboration. When a MIR statement causes a variable to become initialized (or
|
|
uninitialized), drop elaboration inserts code that sets (or clears) the drop
|
|
flag for that variable. It wraps <code>Drop</code> terminators in conditionals that check
|
|
the newly inserted drop flags.</p>
|
|
<p>Drop elaboration also splits <code>DropAndReplace</code> terminators into a <code>Drop</code> of the
|
|
target and a write of the newly dropped place. This is somewhat unrelated to what
|
|
we've discussed above.</p>
|
|
<p>Once this is complete, <code>Drop</code> terminators in the MIR correspond to a call to
|
|
the "drop glue" or "drop shim" for the type of the dropped place. The drop
|
|
glue for a type calls the <code>Drop</code> impl for that type (if one exists), and then
|
|
recursively calls the drop glue for all fields of that type.</p>
|
|
<h2 id="drop-elaboration-in-rustc"><a class="header" href="#drop-elaboration-in-rustc">Drop elaboration in <code>rustc</code></a></h2>
|
|
<p>The approach described above is more expensive than necessary. One can imagine
|
|
a few optimizations:</p>
|
|
<ul>
|
|
<li>Only paths that are the target of a <code>Drop</code> (or have the target as a prefix)
|
|
need drop flags.</li>
|
|
<li>Some variables are known to be initialized (or uninitialized) when they are
|
|
dropped. These do not need drop flags.</li>
|
|
<li>If a set of paths are only dropped or moved from via a shared prefix, those
|
|
paths can share a single drop flag.</li>
|
|
</ul>
|
|
<p>A subset of these are implemented in <code>rustc</code>.</p>
|
|
<p>In the compiler, drop elaboration is split across several modules. The pass
|
|
itself is defined <a href="https://github.com/rust-lang/rust/blob/master/compiler/rustc_mir_transform/src/elaborate_drops.rs">here</a>, but the <a href="https://github.com/rust-lang/rust/blob/master/compiler/rustc_mir_dataflow/src/elaborate_drops.rs">main logic</a> is
|
|
defined elsewhere since it is also used to build <a href="https://github.com/rust-lang/rust/blob/master/compiler/rustc_mir_transform/src/shim.rs">drop shims</a>.</p>
|
|
<p>Drop elaboration designates each <code>Drop</code> in the newly built MIR as one of four
|
|
kinds:</p>
|
|
<ul>
|
|
<li><code>Static</code>, the target is always initialized.</li>
|
|
<li><code>Dead</code>, the target is always <strong>un</strong>initialized.</li>
|
|
<li><code>Conditional</code>, the target is either wholly initialized or wholly
|
|
uninitialized. It is not partly initialized.</li>
|
|
<li><code>Open</code>, the target may be partly initialized.</li>
|
|
</ul>
|
|
<p>For this, it uses a pair of dataflow analyses, <code>MaybeInitializedPlaces</code> and
|
|
<code>MaybeUninitializedPlaces</code>. If a place is in one but not the other, then the
|
|
initializedness of the target is known at compile-time (<code>Dead</code> or <code>Static</code>).
|
|
In this case, drop elaboration does not add a flag for the target. It simply
|
|
removes (<code>Dead</code>) or preserves (<code>Static</code>) the <code>Drop</code> terminator.</p>
|
|
<p>For <code>Conditional</code> drops, we know that the initializedness of the variable as a
|
|
whole is the same as the initializedness of its fields. Therefore, once we
|
|
generate a drop flag for the target of that drop, it's safe to call the drop
|
|
glue for that target.</p>
|
|
<h3 id="open-drops"><a class="header" href="#open-drops"><code>Open</code> drops</a></h3>
|
|
<p><code>Open</code> drops are the most complex, since we need to break down a single <code>Drop</code>
|
|
terminator into several different ones, one for each field of the target whose
|
|
type has drop glue (<code>Ty::needs_drop</code>). We cannot call the drop glue for the
|
|
target itself because that requires all fields of the target to be initialized.
|
|
Remember, variables whose type has a custom <code>Drop</code> impl do not allow <code>Open</code>
|
|
drops because their fields cannot be moved from.</p>
|
|
<p>This is accomplished by recursively categorizing each field as <code>Dead</code>,
|
|
<code>Static</code>, <code>Conditional</code> or <code>Open</code>. Fields whose type does not have drop glue
|
|
are automatically <code>Dead</code> and need not be considered during the recursion. When
|
|
we reach a field whose kind is not <code>Open</code>, we handle it as we did above. If the
|
|
field is also <code>Open</code>, the recursion continues.</p>
|
|
<p>It's worth noting how we handle <code>Open</code> drops of enums. Inside drop elaboration,
|
|
each variant of the enum is treated like a field, with the invariant that only
|
|
one of those "variant fields" can be initialized at any given time. In the
|
|
general case, we do not know which variant is the active one, so we will have
|
|
to call the drop glue for the enum (which checks the discriminant) or check the
|
|
discriminant ourselves as part of an elaborated <code>Open</code> drop. However, in
|
|
certain cases (within a <code>match</code> arm, for example) we do know which variant of
|
|
an enum is active. This information is encoded in the <code>MaybeInitializedPlaces</code>
|
|
and <code>MaybeUninitializedPlaces</code> dataflow analyses by marking all places
|
|
corresponding to inactive variants as uninitialized.</p>
|
|
<h3 id="cleanup-paths"><a class="header" href="#cleanup-paths">Cleanup paths</a></h3>
|
|
<p>TODO: Discuss drop elaboration and unwinding.</p>
|
|
<h2 id="aside-drop-elaboration-and-const-eval"><a class="header" href="#aside-drop-elaboration-and-const-eval">Aside: drop elaboration and const-eval</a></h2>
|
|
<p>In Rust, functions that are eligible for evaluation at compile-time must be
|
|
marked explicitly using the <code>const</code> keyword. This includes implementations of
|
|
the <code>Drop</code> trait, which may or may not be <code>const</code>. Code that is eligible for
|
|
compile-time evaluation may only call <code>const</code> functions, so any calls to
|
|
non-const <code>Drop</code> implementations in such code must be forbidden.</p>
|
|
<p>A call to a <code>Drop</code> impl is encoded as a <code>Drop</code> terminator in the MIR. However,
|
|
as we discussed above, a <code>Drop</code> terminator in newly built MIR does not
|
|
necessarily result in a call to <code>Drop::drop</code>. The drop target may be
|
|
uninitialized at that point. This means that checking for non-const <code>Drop</code>s on
|
|
the newly built MIR can result in spurious errors. Instead, we wait until after
|
|
drop elaboration runs, which eliminates <code>Dead</code> drops (ones where the target is
|
|
known to be uninitialized) to run these checks.</p>
|
|
|
|
</main>
|
|
|
|
<nav class="nav-wrapper" aria-label="Page navigation">
|
|
<!-- Mobile navigation buttons -->
|
|
<a rel="prev" href="../mir/dataflow.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
|
|
<i class="fa fa-angle-left"></i>
|
|
</a>
|
|
|
|
<a rel="next prefetch" href="../borrow_check.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
|
|
<i class="fa fa-angle-right"></i>
|
|
</a>
|
|
|
|
<div style="clear: both"></div>
|
|
</nav>
|
|
</div>
|
|
</div>
|
|
|
|
<nav class="nav-wide-wrapper" aria-label="Page navigation">
|
|
<a rel="prev" href="../mir/dataflow.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
|
|
<i class="fa fa-angle-left"></i>
|
|
</a>
|
|
|
|
<a rel="next prefetch" href="../borrow_check.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
|
|
<i class="fa fa-angle-right"></i>
|
|
</a>
|
|
</nav>
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<script>
|
|
window.playground_copyable = true;
|
|
</script>
|
|
|
|
|
|
<script src="../elasticlunr.min.js"></script>
|
|
<script src="../mark.min.js"></script>
|
|
<script src="../searcher.js"></script>
|
|
|
|
<script src="../clipboard.min.js"></script>
|
|
<script src="../highlight.js"></script>
|
|
<script src="../book.js"></script>
|
|
|
|
<!-- Custom JS scripts -->
|
|
<script src="../mermaid.min.js"></script>
|
|
<script src="../mermaid-init.js"></script>
|
|
|
|
|
|
</div>
|
|
</body>
|
|
</html>
|