blob: 74506b04b15b0c38482eaef39f1b6af211288316 [file] [log] [blame]
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00001<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2 "http://www.w3.org/TR/html4/strict.dtd">
John McCall82467022011-06-15 21:21:53 +00003<html>
4<head>
5<title>Objective-C Automatic Reference Counting (ARC)</title>
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00006<link type="text/css" rel="stylesheet" href="../menu.css">
7<link type="text/css" rel="stylesheet" href="../content.css">
John McCall82467022011-06-15 21:21:53 +00008<style type="text/css">
9/* Collapse the items in the ToC to the left. */
10div#toc ul {
11 padding-left: 0
12}
13
14/* Rationales appear in italic. */
15div.rationale {
16 font-style: italic
17}
18
John McCallf3d08a62011-06-18 07:31:30 +000019div.rationale em {
20 font-style: normal
21}
22
John McCall82467022011-06-15 21:21:53 +000023div h1 { font-size: 2em; margin: .67em 0 }
24div div h1 { font-size: 1.5em; margin: .75em 0 }
25div div div h1 { font-size: 1.17em; margin: .83em 0 }
26div div div div h1 { margin: 1.12em 0 }
27
28span.term { font-style: italic; font-weight: bold }
29</style>
30
Benjamin Kramer665a8dc2012-01-15 15:26:07 +000031<script type="text/javascript">
John McCall82467022011-06-15 21:21:53 +000032/// A little script to recursively build a table of contents.
33function buildTOC(div, toc, ancestry) {
34 var children = div.childNodes;
35 var len = children.length;
36
37 var childNumber = 0;
38
39 var list = null;
40 for (var i = 0; i < len; ++i) {
41 var child = children[i];
42 if (child.nodeName != "DIV") continue;
43 if (child.getAttribute("class") == "rationale") continue;
44 if (child.id == "toc") continue;
45
46 // Okay, we're actually going to build a list node.
47 if (list === null) list = document.createElement("ul");
48
49 var childAncestry = ancestry + ++childNumber + ".";
50
51 var headerNode = child.childNodes[1];
52 var title = headerNode.innerHTML;
53 headerNode.insertBefore(document.createTextNode(childAncestry + " "),
54 headerNode.firstChild);
55
56 var item = document.createElement("li");
57 item.appendChild(document.createTextNode(childAncestry + " "));
58
59 var anchor = document.createElement("a");
60 anchor.href = "#" + child.id;
61 anchor.innerHTML = title;
62 item.appendChild(anchor);
63
64 buildTOC(child, item, childAncestry);
65
66 list.appendChild(item);
67 }
68 if (list) toc.appendChild(list);
69}
70
71function onLoad() {
72 var toc = document.getElementById("toc");
73 var content = document.getElementById("content");
74 buildTOC(content, toc, "");
75}
76window.onload = onLoad;
77
78</script>
79</head>
80<body>
81
82<!--#include virtual="../menu.html.incl"-->
83
84<div id="content">
85<h1>Automatic Reference Counting</h1>
86
87<div id="toc">
88</div>
89
90<div id="meta">
91<h1>About this document</h1>
92
93<div id="meta.purpose">
94<h1>Purpose</h1>
95
96<p>The first and primary purpose of this document is to serve as a
97complete technical specification of Automatic Reference Counting.
98Given a core Objective-C compiler and runtime, it should be possible
99to write a compiler and runtime which implements these new
100semantics.</p>
101
102<p>The secondary purpose is to act as a rationale for why ARC was
103designed in this way. This should remain tightly focused on the
104technical design and should not stray into marketing speculation.</p>
105
106</div> <!-- meta.purpose -->
107
108<div id="meta.background">
109<h1>Background</h1>
110
111<p>This document assumes a basic familiarity with C.</p>
112
113<p><span class="term">Blocks</span> are a C language extension for
114creating anonymous functions. Users interact with and transfer block
115objects using <span class="term">block pointers</span>, which are
116represented like a normal pointer. A block may capture values from
117local variables; when this occurs, memory must be dynamically
118allocated. The initial allocation is done on the stack, but the
119runtime provides a <tt>Block_copy</tt> function which, given a block
120pointer, either copies the underlying block object to the heap,
121setting its reference count to 1 and returning the new block pointer,
122or (if the block object is already on the heap) increases its
123reference count by 1. The paired function is <tt>Block_release</tt>,
124which decreases the reference count by 1 and destroys the object if
125the count reaches zero and is on the heap.</p>
126
127<p>Objective-C is a set of language extensions, significant enough to
128be considered a different language. It is a strict superset of C.
129The extensions can also be imposed on C++, producing a language called
130Objective-C++. The primary feature is a single-inheritance object
131system; we briefly describe the modern dialect.</p>
132
133<p>Objective-C defines a new type kind, collectively called
134the <span class="term">object pointer types</span>. This kind has two
135notable builtin members, <tt>id</tt> and <tt>Class</tt>; <tt>id</tt>
136is the final supertype of all object pointers. The validity of
137conversions between object pointer types is not checked at runtime.
138Users may define <span class="term">classes</span>; each class is a
139type, and the pointer to that type is an object pointer type. A class
140may have a superclass; its pointer type is a subtype of its
141superclass's pointer type. A class has a set
142of <span class="term">ivars</span>, fields which appear on all
143instances of that class. For every class <i>T</i> there's an
144associated metaclass; it has no fields, its superclass is the
145metaclass of <i>T</i>'s superclass, and its metaclass is a global
146class. Every class has a global object whose class is the
147class's metaclass; metaclasses have no associated type, so pointers to
148this object have type <tt>Class</tt>.</p>
149
150<p>A class declaration (<tt>@interface</tt>) declares a set
151of <span class="term">methods</span>. A method has a return type, a
152list of argument types, and a <span class="term">selector</span>: a
153name like <tt>foo:bar:baz:</tt>, where the number of colons
154corresponds to the number of formal arguments. A method may be an
155instance method, in which case it can be invoked on objects of the
156class, or a class method, in which case it can be invoked on objects
157of the metaclass. A method may be invoked by providing an object
158(called the <span class="term">receiver</span>) and a list of formal
159arguments interspersed with the selector, like so:</p>
160
161<pre>[receiver foo: fooArg bar: barArg baz: bazArg]</pre>
162
163<p>This looks in the dynamic class of the receiver for a method with
164this name, then in that class's superclass, etc., until it finds
165something it can execute. The receiver <q>expression</q> may also be
166the name of a class, in which case the actual receiver is the class
167object for that class, or (within method definitions) it may
168be <tt>super</tt>, in which case the lookup algorithm starts with the
169static superclass instead of the dynamic class. The actual methods
170dynamically found in a class are not those declared in the
171<tt>@interface</tt>, but those defined in a separate
172<tt>@implementation</tt> declaration; however, when compiling a
173call, typechecking is done based on the methods declared in the
174<tt>@interface</tt>.</p>
175
176<p>Method declarations may also be grouped into
177<span class="term">protocols</span>, which are not inherently
178associated with any class, but which classes may claim to follow.
179Object pointer types may be qualified with additional protocols that
180the object is known to support.</p>
181
182<p><span class="term">Class extensions</span> are collections of ivars
183and methods, designed to allow a class's <tt>@interface</tt> to be
184split across multiple files; however, there is still a primary
185implementation file which must see the <tt>@interface</tt>s of all
186class extensions.
187<span class="term">Categories</span> allow methods (but not ivars) to
188be declared <i>post hoc</i> on an arbitrary class; the methods in the
189category's <tt>@implementation</tt> will be dynamically added to that
190class's method tables which the category is loaded at runtime,
191replacing those methods in case of a collision.</p>
192
193<p>In the standard environment, objects are allocated on the heap, and
194their lifetime is manually managed using a reference count. This is
195done using two instance methods which all classes are expected to
196implement: <tt>retain</tt> increases the object's reference count by
1971, whereas <tt>release</tt> decreases it by 1 and calls the instance
198method <tt>dealloc</tt> if the count reaches 0. To simplify certain
199operations, there is also an <span class="term">autorelease
200pool</span>, a thread-local list of objects to call <tt>release</tt>
201on later; an object can be added to this pool by
202calling <tt>autorelease</tt> on it.</p>
203
204<p>Block pointers may be converted to type <tt>id</tt>; block objects
205are laid out in a way that makes them compatible with Objective-C
206objects. There is a builtin class that all block objects are
207considered to be objects of; this class implements <tt>retain</tt> by
208adjusting the reference count, not by calling <tt>Block_copy</tt>.</p>
209
210</div> <!-- meta.background -->
211
212</div> <!-- meta -->
213
214<div id="general">
215<h1>General</h1>
216
217<p>Automatic Reference Counting implements automatic memory management
218for Objective-C objects and blocks, freeing the programmer from the
219need explicitly insert retains and releases. It does not provide a
220cycle collector; users must explicitly manage lifetime instead.</p>
221
222<p>ARC may be explicitly enabled with the compiler
223flag <tt>-fobjc-arc</tt>. It may also be explicitly disabled with the
224compiler flag <tt>-fno-objc-arc</tt>. The last of these two flags
225appearing on the compile line <q>wins</q>.</p>
226
227<p>If ARC is enabled, <tt>__has_feature(objc_arc)</tt> will expand to
2281 in the preprocessor. For more information about <tt>__has_feature</tt>,
229see the <a href="LanguageExtensions.html#__has_feature_extension">language
230extensions</a> document.</p>
231
232</div>
233
234<div id="objects">
235<h1>Retainable object pointers</h1>
236
237<p>This section describes retainable object pointers, their basic
238operations, and the restrictions imposed on their use under ARC. Note
239in particular that it covers the rules for pointer <em>values</em>
240(patterns of bits indicating the location of a pointed-to object), not
241pointer
242<em>objects</em> (locations in memory which store pointer values).
243The rules for objects are covered in the next section.</p>
244
245<p>A <span class="term">retainable object pointer</span>
246(or <q>retainable pointer</q>) is a value of
247a <span class="term">retainable object pointer type</span>
248(<q>retainable type</q>). There are three kinds of retainable object
249pointer types:</p>
250<ul>
251<li>block pointers (formed by applying the caret (<tt>^</tt>)
252declarator sigil to a function type)</li>
253<li>Objective-C object pointers (<tt>id</tt>, <tt>Class</tt>, <tt>NSFoo*</tt>, etc.)</li>
254<li>typedefs marked with <tt>__attribute__((NSObject))</tt></li>
255</ul>
256
257<p>Other pointer types, such as <tt>int*</tt> and <tt>CFStringRef</tt>,
258are not subject to ARC's semantics and restrictions.</p>
259
260<div class="rationale">
261
262<p>Rationale: We are not at liberty to require
263all code to be recompiled with ARC; therefore, ARC must interoperate
264with Objective-C code which manages retains and releases manually. In
265general, there are three requirements in order for a
266compiler-supported reference-count system to provide reliable
267interoperation:</p>
268
269<ul>
270<li>The type system must reliably identify which objects are to be
271managed. An <tt>int*</tt> might be a pointer to a <tt>malloc</tt>'ed
272array, or it might be a interior pointer to such an array, or it might
273point to some field or local variable. In contrast, values of the
274retainable object pointer types are never interior.</li>
275<li>The type system must reliably indicate how to
276manage objects of a type. This usually means that the type must imply
277a procedure for incrementing and decrementing retain counts.
278Supporting single-ownership objects requires a lot more explicit
279mediation in the language.</li>
280<li>There must be reliable conventions for whether and
281when <q>ownership</q> is passed between caller and callee, for both
282arguments and return values. Objective-C methods follow such a
283convention very reliably, at least for system libraries on Mac OS X,
284and functions always pass objects at +0. The C-based APIs for Core
285Foundation objects, on the other hand, have much more varied transfer
286semantics.</li>
287</ul>
288</div> <!-- rationale -->
289
290<p>The use of <tt>__attribute__((NSObject))</tt> typedefs is not
291recommended. If it's absolutely necessary to use this attribute, be
292very explicit about using the typedef, and do not assume that it will
293be preserved by language features like <tt>__typeof</tt> and C++
294template argument substitution.</p>
295
296<div class="rationale"><p>Rationale: any compiler operation which
297incidentally strips type <q>sugar</q> from a type will yield a type
298without the attribute, which may result in unexpected
299behavior.</p></div>
300
301<div id="objects.retains">
302<h1>Retain count semantics</h1>
303
304<p>A retainable object pointer is either a <span class="term">null
305pointer</span> or a pointer to a valid object. Furthermore, if it has
306block pointer type and is not <tt>null</tt> then it must actually be a
307pointer to a block object, and if it has <tt>Class</tt> type (possibly
308protocol-qualified) then it must actually be a pointer to a class
309object. Otherwise ARC does not enforce the Objective-C type system as
310long as the implementing methods follow the signature of the static
311type. It is undefined behavior if ARC is exposed to an invalid
312pointer.</p>
313
314<p>For ARC's purposes, a valid object is one with <q>well-behaved</q>
315retaining operations. Specifically, the object must be laid out such
316that the Objective-C message send machinery can successfully send it
317the following messages:</p>
318
319<ul>
320<li><tt>retain</tt>, taking no arguments and returning a pointer to
321the object.</li>
322<li><tt>release</tt>, taking no arguments and returning <tt>void</tt>.</li>
323<li><tt>autorelease</tt>, taking no arguments and returning a pointer
324to the object.</li>
325</ul>
326
327<p>The behavior of these methods is constrained in the following ways.
328The term <span class="term">high-level semantics</span> is an
329intentionally vague term; the intent is that programmers must
330implement these methods in a way such that the compiler, modifying
331code in ways it deems safe according to these constraints, will not
332violate their requirements. For example, if the user puts logging
333statements in <tt>retain</tt>, they should not be surprised if those
334statements are executed more or less often depending on optimization
335settings. These constraints are not exhaustive of the optimization
336opportunities: values held in local variables are subject to
337additional restrictions, described later in this document.</p>
338
339<p>It is undefined behavior if a computation history featuring a send
340of <tt>retain</tt> followed by a send of <tt>release</tt> to the same
341object, with no intervening <tt>release</tt> on that object, is not
342equivalent under the high-level semantics to a computation
343history in which these sends are removed. Note that this implies that
344these methods may not raise exceptions.</p>
345
346<p>It is undefined behavior if a computation history features any use
347whatsoever of an object following the completion of a send
348of <tt>release</tt> that is not preceded by a send of <tt>retain</tt>
349to the same object.</p>
350
351<p>The behavior of <tt>autorelease</tt> must be equivalent to sending
352<tt>release</tt> when one of the autorelease pools currently in scope
353is popped. It may not throw an exception.</p>
354
355<p>When the semantics call for performing one of these operations on a
356retainable object pointer, if that pointer is <tt>null</tt> then the
357effect is a no-op.</p>
358
359<p>All of the semantics described in this document are subject to
360additional <a href="#optimization">optimization rules</a> which permit
361the removal or optimization of operations based on local knowledge of
362data flow. The semantics describe the high-level behaviors that the
363compiler implements, not an exact sequence of operations that a
364program will be compiled into.</p>
365
366</div> <!-- objects.retains -->
367
368<div id="objects.operands">
369<h1>Retainable object pointers as operands and arguments</h1>
370
371<p>In general, ARC does not perform retain or release operations when
372simply using a retainable object pointer as an operand within an
373expression. This includes:</p>
374<ul>
375<li>loading a retainable pointer from an object with non-weak
376<a href="#ownership">ownership</a>,</li>
377<li>passing a retainable pointer as an argument to a function or
378method, and</li>
379<li>receiving a retainable pointer as the result of a function or
380method call.</li>
381</ul>
382
383<div class="rationale"><p>Rationale: while this might seem
384uncontroversial, it is actually unsafe when multiple expressions are
385evaluated in <q>parallel</q>, as with binary operators and calls,
386because (for example) one expression might load from an object while
387another writes to it. However, C and C++ already call this undefined
388behavior because the evaluations are unsequenced, and ARC simply
389exploits that here to avoid needing to retain arguments across a large
390number of calls.</p></div>
391
392<p>The remainder of this section describes exceptions to these rules,
393how those exceptions are detected, and what those exceptions imply
394semantically.</p>
395
396<div id="objects.operands.consumed">
397<h1>Consumed parameters</h1>
398
399<p>A function or method parameter of retainable object pointer type
400may be marked as <span class="term">consumed</span>, signifying that
401the callee expects to take ownership of a +1 retain count. This is
402done by adding the <tt>ns_consumed</tt> attribute to the parameter
403declaration, like so:</p>
404
405<pre>void foo(__attribute((ns_consumed)) id x);
406- (void) foo: (id) __attribute((ns_consumed)) x;</pre>
407
408<p>This attribute is part of the type of the function or method, not
409the type of the parameter. It controls only how the argument is
410passed and received.</p>
411
412<p>When passing such an argument, ARC retains the argument prior to
413making the call.</p>
414
415<p>When receiving such an argument, ARC releases the argument at the
416end of the function, subject to the usual optimizations for local
417values.</p>
418
419<div class="rationale"><p>Rationale: this formalizes direct transfers
420of ownership from a caller to a callee. The most common scenario here
421is passing the <tt>self</tt> parameter to <tt>init</tt>, but it is
422useful to generalize. Typically, local optimization will remove any
423extra retains and releases: on the caller side the retain will be
424merged with a +1 source, and on the callee side the release will be
425rolled into the initialization of the parameter.</p></div>
426
427<p>The implicit <tt>self</tt> parameter of a method may be marked as
428consumed by adding <tt>__attribute__((ns_consumes_self))</tt> to the
John McCallbe16b892011-06-18 08:15:19 +0000429method declaration. Methods in the <tt>init</tt>
430<a href="#family">family</a> are treated as if they were implicitly
431marked with this attribute.</p>
John McCall82467022011-06-15 21:21:53 +0000432
John McCallbe16b892011-06-18 08:15:19 +0000433<p>It is undefined behavior if an Objective-C message send to a method
434with <tt>ns_consumed</tt> parameters (other than self) is made with a
435null receiver. It is undefined behavior if the method to which an
436Objective-C message send statically resolves to has a different set
437of <tt>ns_consumed</tt> parameters than the method it dynamically
438resolves to. It is undefined behavior if a block or function call is
439made through a static type with a different set of <tt>ns_consumed</tt>
440parameters than the implementation of the called block or function.</p>
John McCall82467022011-06-15 21:21:53 +0000441
John McCallbe16b892011-06-18 08:15:19 +0000442<div class="rationale"><p>Rationale: consumed parameters with null
443receiver are a guaranteed leak. Mismatches with consumed parameters
444will cause over-retains or over-releases, depending on the direction.
445The rule about function calls is really just an application of the
446existing C/C++ rule about calling functions through an incompatible
447function type, but it's useful to state it explicitly.</p></div>
John McCall82467022011-06-15 21:21:53 +0000448
449</div>
450
John McCallbe16b892011-06-18 08:15:19 +0000451<div id="objects.operands.retained_returns">
John McCall82467022011-06-15 21:21:53 +0000452<h1>Retained return values</h1>
453
454<p>A function or method which returns a retainable object pointer type
455may be marked as returning a retained value, signifying that the
456caller expects to take ownership of a +1 retain count. This is done
457by adding the <tt>ns_returns_retained</tt> attribute to the function or
458method declaration, like so:</p>
459
460<pre>id foo(void) __attribute((ns_returns_retained));
461- (id) foo __attribute((ns_returns_retained));</pre>
462
463<p>This attribute is part of the type of the function or method.</p>
464
465<p>When returning from such a function or method, ARC retains the
466value at the point of evaluation of the return statement, before
467leaving all local scopes.</p>
468
469<p>When receiving a return result from such a function or method, ARC
470releases the value at the end of the full-expression it is contained
471within, subject to the usual optimizations for local values.</p>
472
473<div class="rationale"><p>Rationale: this formalizes direct transfers of
474ownership from a callee to a caller. The most common scenario this
475models is the retained return from <tt>init</tt>, <tt>alloc</tt>,
476<tt>new</tt>, and <tt>copy</tt> methods, but there are other cases in
477the frameworks. After optimization there are typically no extra
478retains and releases required.</p></div>
479
480<p>Methods in
481the <tt>alloc</tt>, <tt>copy</tt>, <tt>init</tt>, <tt>mutableCopy</tt>,
482and <tt>new</tt> <a href="#family">families</a> are implicitly marked
483<tt>__attribute__((ns_returns_retained))</tt>. This may be suppressed
484by explicitly marking the
485method <tt>__attribute__((ns_returns_not_retained))</tt>.</p>
486</div>
487
John McCallbe16b892011-06-18 08:15:19 +0000488<p>It is undefined behavior if the method to which an Objective-C
489message send statically resolves has different retain semantics on its
490result from the method it dynamically resolves to. It is undefined
491behavior if a block or function call is made through a static type
492with different retain semantics on its result from the implementation
493of the called block or function.</p>
494
495<div class="rationale"><p>Rationale: Mismatches with returned results
496will cause over-retains or over-releases, depending on the direction.
497Again, the rule about function calls is really just an application of
498the existing C/C++ rule about calling functions through an
499incompatible function type.</p></div>
500
501
John McCall82467022011-06-15 21:21:53 +0000502<div id="objects.operands.other-returns">
503<h1>Unretained return values</h1>
504
505<p>A method or function which returns a retainable object type but
506does not return a retained value must ensure that the object is
507still valid across the return boundary.</p>
508
509<p>When returning from such a function or method, ARC retains the
510value at the point of evaluation of the return statement, then leaves
511all local scopes, and then balances out the retain while ensuring that
512the value lives across the call boundary. In the worst case, this may
513involve an <tt>autorelease</tt>, but callers must not assume that the
514value is actually in the autorelease pool.</p>
515
516<p>ARC performs no extra mandatory work on the caller side, although
517it may elect to do something to shorten the lifetime of the returned
518value.</p>
519
520<div class="rationale"><p>Rationale: it is common in non-ARC code to not
521return an autoreleased value; therefore the convention does not force
522either path. It is convenient to not be required to do unnecessary
523retains and autoreleases; this permits optimizations such as eliding
524retain/autoreleases when it can be shown that the original pointer
525will still be valid at the point of return.</p></div>
526
527<p>A method or function may be marked
528with <tt>__attribute__((ns_returns_autoreleased))</tt> to indicate
529that it returns a pointer which is guaranteed to be valid at least as
530long as the innermost autorelease pool. There are no additional
531semantics enforced in the definition of such a method; it merely
532enables optimizations in callers.</p>
533</div>
534
535<div id="objects.operands.casts">
536<h1>Bridged casts</h1>
537
538<p>A <span class="term">bridged cast</span> is a C-style cast
539annotated with one of three keywords:</p>
540
541<ul>
542<li><tt>(__bridge T) op</tt> casts the operand to the destination
543type <tt>T</tt>. If <tt>T</tt> is a retainable object pointer type,
544then <tt>op</tt> must have a non-retainable pointer type.
545If <tt>T</tt> is a non-retainable pointer type, then <tt>op</tt> must
546have a retainable object pointer type. Otherwise the cast is
547ill-formed. There is no transfer of ownership, and ARC inserts
548no retain operations.</li>
549
550<li><tt>(__bridge_retained T) op</tt> casts the operand, which must
551have retainable object pointer type, to the destination type, which
552must be a non-retainable pointer type. ARC retains the value, subject
553to the usual optimizations on local values, and the recipient is
554responsible for balancing that +1.</li>
555
556<li><tt>(__bridge_transfer T) op</tt> casts the operand, which must
557have non-retainable pointer type, to the destination type, which must
558be a retainable object pointer type. ARC will release the value at
559the end of the enclosing full-expression, subject to the usual
560optimizations on local values.</li>
561</ul>
562
563<p>These casts are required in order to transfer objects in and out of
564ARC control; see the rationale in the section
565on <a href="#objects.restrictions.conversion">conversion of retainable
566object pointers</a>.</p>
567
568<p>Using a <tt>__bridge_retained</tt> or <tt>__bridge_transfer</tt>
569cast purely to convince ARC to emit an unbalanced retain or release,
570respectively, is poor form.</p>
571
572</div>
573
574</div>
575
576<div id="objects.restrictions">
577<h1>Restrictions</h1>
578
579<div id="objects.restrictions.conversion">
580<h1>Conversion of retainable object pointers</h1>
581
582<p>In general, a program which attempts to implicitly or explicitly
583convert a value of retainable object pointer type to any
584non-retainable type, or vice-versa, is ill-formed. For example, an
Fariborz Jahaniana26b2e52011-07-06 21:58:44 +0000585Objective-C object pointer shall not be converted to <tt>void*</tt>.
David Blaikie0ff64952011-11-24 00:37:54 +0000586As an exception, cast to <tt>intptr_t</tt> is allowed because such
Fariborz Jahaniana26b2e52011-07-06 21:58:44 +0000587casts are not transferring ownership. The <a href="#objects.operands.casts">bridged
John McCall82467022011-06-15 21:21:53 +0000588casts</a> may be used to perform these conversions where
589necessary.</p>
590
591<div class="rationale"><p>Rationale: we cannot ensure the correct
592management of the lifetime of objects if they may be freely passed
593around as unmanaged types. The bridged casts are provided so that the
594programmer may explicitly describe whether the cast transfers control
595into or out of ARC.</p></div>
596</div>
597
598<p>An unbridged cast to a retainable object pointer type of the return
599value of a Objective-C message send which yields a non-retainable
600pointer is treated as a <tt>__bridge_transfer</tt> cast
601if:</p>
602
603<ul>
604<li>the method has the <tt>cf_returns_retained</tt> attribute, or if
605not that,</li>
606<li>the method does not have the <tt>cf_returns_not_retained</tt>
607attribute and</li>
608<li>the method's <a href="#family">selector family</a> would imply
609the <tt>ns_returns_retained</tt> attribute on a method which returned
610a retainable object pointer type.</li>
611</ul>
612
613<p>Otherwise the cast is treated as a <tt>__bridge</tt> cast.</p>
614
615</div>
616
617</div>
618
619<div id="ownership">
620<h1>Ownership qualification</h1>
621
622<p>This section describes the behavior of <em>objects</em> of
623retainable object pointer type; that is, locations in memory which
624store retainable object pointers.</p>
625
626<p>A type is a <span class="term">retainable object owner type</span>
627if it is a retainable object pointer type or an array type whose
628element type is a retainable object owner type.</p>
629
630<p>An <span class="term">ownership qualifier</span> is a type
Douglas Gregor4020cae2011-06-17 23:16:24 +0000631qualifier which applies only to retainable object owner types. An array type is
632ownership-qualified according to its element type, and adding an ownership
633qualifier to an array type so qualifies its element type.</p>
634
635<p>A program is ill-formed if it attempts to apply an ownership qualifier
John McCall82467022011-06-15 21:21:53 +0000636to a type which is already ownership-qualified, even if it is the same
Douglas Gregor4020cae2011-06-17 23:16:24 +0000637qualifier. There is a single exception to this rule: an ownership qualifier
638may be applied to a substituted template type parameter, which overrides the
639ownership qualifier provided by the template argument.</p>
John McCall82467022011-06-15 21:21:53 +0000640
641<p>Except as described under
642the <a href="#ownership.inference">inference rules</a>, a program is
643ill-formed if it attempts to form a pointer or reference type to a
644retainable object owner type which lacks an ownership qualifier.</p>
645
646<div class="rationale"><p>Rationale: these rules, together with the
647inference rules, ensure that all objects and lvalues of retainable
Douglas Gregor4020cae2011-06-17 23:16:24 +0000648object pointer type have an ownership qualifier. The ability to override an ownership qualifier during template substitution is required to counteract the <a href="#ownership.inference.template_arguments">inference of <tt>__strong</tt> for template type arguments</a>. </p></div>
John McCall82467022011-06-15 21:21:53 +0000649
650<p>There are four ownership qualifiers:</p>
651
652<ul>
653<li><tt>__autoreleasing</tt></li>
654<li><tt>__strong</tt></li>
655<li><tt>__unsafe_unretained</tt></li>
656<li><tt>__weak</tt></li>
657</ul>
658
659<p>A type is <span class="term">nontrivially ownership-qualified</span>
660if it is qualified with <tt>__autoreleasing</tt>, <tt>__strong</tt>, or
661<tt>__weak</tt>.</p>
662
663<div id="ownership.spelling">
664<h1>Spelling</h1>
665
666<p>The names of the ownership qualifiers are reserved for the
667implementation. A program may not assume that they are or are not
668implemented with macros, or what those macros expand to.</p>
669
670<p>An ownership qualifier may be written anywhere that any other type
671qualifier may be written.</p>
672
673<p>If an ownership qualifier appears in
674the <i>declaration-specifiers</i>, the following rules apply:</p>
675
676<ul>
677<li>if the type specifier is a retainable object owner type, the
678qualifier applies to that type;</li>
679<li>if the outermost non-array part of the declarator is a pointer or
680block pointer, the qualifier applies to that type;</li>
681<li>otherwise the program is ill-formed.</li>
682</ul>
683
684<p>If an ownership qualifier appears on the declarator name, or on the
685declared object, it is applied to outermost pointer or block-pointer
686type.</p>
687
688<p>If an ownership qualifier appears anywhere else in a declarator, it
689applies to the type there.</p>
690
John McCall4f264952011-07-13 23:15:32 +0000691<div id="ownership.spelling.property">
692<h1>Property declarations</h1>
693
694<p>A property of retainable object pointer type may have ownership.
695If the property's type is ownership-qualified, then the property has
696that ownership. If the property has one of the following modifiers,
697then the property has the corresponding ownership. A property is
698ill-formed if it has conflicting sources of ownership, or if it has
699redundant ownership modifiers, or if it has <tt>__autoreleasing</tt>
700ownership.</p>
701
702<ul>
703<li><tt>assign</tt> implies <tt>__unsafe_unretained</tt> ownership.</li>
704<li><tt>copy</tt> implies <tt>__strong</tt> ownership, as well as the
705 usual behavior of copy semantics on the setter.</li>
706<li><tt>retain</tt> implies <tt>__strong</tt> ownership.</li>
707<li><tt>strong</tt> implies <tt>__strong</tt> ownership.</li>
708<li><tt>unsafe_unretained</tt> implies <tt>__unsafe_unretained</tt>
709 ownership.</li>
710<li><tt>weak</tt> implies <tt>__weak</tt> ownership.</li>
711</ul>
712
713<p>With the exception of <tt>weak</tt>, these modifiers are available
714in non-ARC modes.</p>
715
716<p>A property's specified ownership is preserved in its metadata, but
717otherwise the meaning is purely conventional unless the property is
718synthesized. If a property is synthesized, then the
719<span class="term">associated instance variable</span> is the
720instance variable which is named, possibly implicitly, by the
721<tt>@synthesize</tt> declaration. If the associated instance variable
722already exists, then its ownership qualification must equal the
723ownership of the property; otherwise, the instance variable is created
724with that ownership qualification.</p>
725
726</div> <!-- ownership.spelling.property -->
727
John McCall82467022011-06-15 21:21:53 +0000728</div> <!-- ownership.spelling -->
729
730<div id="ownership.semantics">
731<h1>Semantics</h1>
732
733<p>There are five <span class="term">managed operations</span> which
734may be performed on an object of retainable object pointer type. Each
735qualifier specifies different semantics for each of these operations.
736It is still undefined behavior to access an object outside of its
737lifetime.</p>
738
739<p>A load or store with <q>primitive semantics</q> has the same
740semantics as the respective operation would have on an <tt>void*</tt>
741lvalue with the same alignment and non-ownership qualification.</p>
742
743<p><span class="term">Reading</span> occurs when performing a
Benjamin Kramer665a8dc2012-01-15 15:26:07 +0000744lvalue-to-rvalue conversion on an object lvalue.</p>
John McCall82467022011-06-15 21:21:53 +0000745
746<ul>
747<li>For <tt>__weak</tt> objects, the current pointee is retained and
748then released at the end of the current full-expression. This must
749execute atomically with respect to assignments and to the final
750release of the pointee.</li>
751<li>For all other objects, the lvalue is loaded with primitive
752semantics.</li>
753</ul>
John McCall82467022011-06-15 21:21:53 +0000754
755<p><span class="term">Assignment</span> occurs when evaluating
Benjamin Kramer665a8dc2012-01-15 15:26:07 +0000756an assignment operator. The semantics vary based on the qualification:</p>
John McCall82467022011-06-15 21:21:53 +0000757<ul>
758<li>For <tt>__strong</tt> objects, the new pointee is first retained;
759second, the lvalue is loaded with primitive semantics; third, the new
760pointee is stored into the lvalue with primitive semantics; and
761finally, the old pointee is released. This is not performed
762atomically; external synchronization must be used to make this safe in
763the face of concurrent loads and stores.</li>
764<li>For <tt>__weak</tt> objects, the lvalue is updated to point to the
765new pointee, unless that object is currently undergoing deallocation,
766in which case it the lvalue is updated to a null pointer. This must
767execute atomically with respect to other assignments to the object, to
768reads from the object, and to the final release of the new pointed-to
John McCall2fad7832011-07-07 00:03:42 +0000769value.</li>
John McCall82467022011-06-15 21:21:53 +0000770<li>For <tt>__unsafe_unretained</tt> objects, the new pointee is
771stored into the lvalue using primitive semantics.</li>
772<li>For <tt>__autoreleasing</tt> objects, the new pointee is retained,
773autoreleased, and stored into the lvalue using primitive semantics.</li>
774</ul>
John McCall82467022011-06-15 21:21:53 +0000775
776<p><span class="term">Initialization</span> occurs when an object's
777lifetime begins, which depends on its storage duration.
Benjamin Kramer665a8dc2012-01-15 15:26:07 +0000778Initialization proceeds in two stages:</p>
John McCall82467022011-06-15 21:21:53 +0000779<ol>
780<li>First, a null pointer is stored into the lvalue using primitive
781semantics. This step is skipped if the object
782is <tt>__unsafe_unretained</tt>.</li>
783<li>Second, if the object has an initializer, that expression is
784evaluated and then assigned into the object using the usual assignment
785semantics.</li>
786</ol>
John McCall82467022011-06-15 21:21:53 +0000787
788<p><span class="term">Destruction</span> occurs when an object's
789lifetime ends. In all cases it is semantically equivalent to
790assigning a null pointer to the object, with the proviso that of
791course the object cannot be legally read after the object's lifetime
792ends.</p>
793
794<p><span class="term">Moving</span> occurs in specific situations
795where an lvalue is <q>moved from</q>, meaning that its current pointee
796will be used but the object may be left in a different (but still
797valid) state. This arises with <tt>__block</tt> variables and rvalue
798references in C++. For <tt>__strong</tt> lvalues, moving is equivalent
799to loading the lvalue with primitive semantics, writing a null pointer
800to it with primitive semantics, and then releasing the result of the
801load at the end of the current full-expression. For all other
802lvalues, moving is equivalent to reading the object.</p>
803
804</div> <!-- ownership.semantics -->
805
806<div id="ownership.restrictions">
807<h1>Restrictions</h1>
808
John McCall2fad7832011-07-07 00:03:42 +0000809<div id="ownership.restrictions.weak">
810<h1>Weak-unavailable types</h1>
811
812<p>It is explicitly permitted for Objective-C classes to not
813support <tt>__weak</tt> references. It is undefined behavior to
814perform an operation with weak assignment semantics with a pointer to
815an Objective-C object whose class does not support <tt>__weak</tt>
816references.</p>
817
818<div class="rationale"><p>Rationale: historically, it has been
819possible for a class to provide its own reference-count implementation
820by overriding <tt>retain</tt>, <tt>release</tt>, etc. However, weak
821references to an object require coordination with its class's
822reference-count implementation because, among other things, weak loads
823and stores must be atomic with respect to the final release.
824Therefore, existing custom reference-count implementations will
825generally not support weak references without additional effort. This
826is unavoidable without breaking binary compatibility.</p></div>
827
828<p>A class may indicate that it does not support weak references by
829providing the <tt>objc_arc_weak_unavailable</tt> attribute on the
830class's interface declaration. A retainable object pointer type
831is <span class="term">weak-unavailable</span> if is a pointer to an
832(optionally protocol-qualified) Objective-C class <tt>T</tt>
833where <tt>T</tt> or one of its superclasses has
834the <tt>objc_arc_weak_unavailable</tt> attribute. A program is
835ill-formed if it applies the <tt>__weak</tt> ownership qualifier to a
836weak-unavailable type or if the value operand of a weak assignment
837operation has a weak-unavailable type.</p>
838</div> <!-- ownership.restrictions.weak -->
839
John McCall82467022011-06-15 21:21:53 +0000840<div id="ownership.restrictions.autoreleasing">
John McCall2fad7832011-07-07 00:03:42 +0000841<h1>Storage duration of <tt>__autoreleasing</tt> objects</h1>
John McCall82467022011-06-15 21:21:53 +0000842
843<p>A program is ill-formed if it declares an <tt>__autoreleasing</tt>
844object of non-automatic storage duration.</p>
845
846<div class="rationale"><p>Rationale: autorelease pools are tied to the
847current thread and scope by their nature. While it is possible to
848have temporary objects whose instance variables are filled with
849autoreleased objects, there is no way that ARC can provide any sort of
850safety guarantee there.</p></div>
851
852<p>It is undefined behavior if a non-null pointer is assigned to
853an <tt>__autoreleasing</tt> object while an autorelease pool is in
854scope and then that object is read after the autorelease pool's scope
855is left.</p>
856
857</div>
858
859<div id="ownership.restrictions.conversion.indirect">
860<h1>Conversion of pointers to ownership-qualified types</h1>
861
862<p>A program is ill-formed if an expression of type <tt>T*</tt> is
863converted, explicitly or implicitly, to the type <tt>U*</tt>,
864where <tt>T</tt> and <tt>U</tt> have different ownership
Benjamin Kramer665a8dc2012-01-15 15:26:07 +0000865qualification, unless:</p>
John McCall82467022011-06-15 21:21:53 +0000866<ul>
867<li><tt>T</tt> is qualified with <tt>__strong</tt>,
868 <tt>__autoreleasing</tt>, or <tt>__unsafe_unretained</tt>, and
869 <tt>U</tt> is qualified with both <tt>const</tt> and
870 <tt>__unsafe_unretained</tt>; or</li>
871<li>either <tt>T</tt> or <tt>U</tt> is <tt>cv void</tt>, where
872<tt>cv</tt> is an optional sequence of non-ownership qualifiers; or</li>
873<li>the conversion is requested with a <tt>reinterpret_cast</tt> in
874 Objective-C++; or</li>
875<li>the conversion is a
876well-formed <a href="#ownership.restrictions.pass_by_writeback">pass-by-writeback</a>.</li>
877</ul>
John McCall82467022011-06-15 21:21:53 +0000878
Benjamin Kramer665a8dc2012-01-15 15:26:07 +0000879<p>The analogous rule applies to <tt>T&amp;</tt> and <tt>U&amp;</tt> in
John McCall82467022011-06-15 21:21:53 +0000880Objective-C++.</p>
881
882<div class="rationale"><p>Rationale: these rules provide a reasonable
883level of type-safety for indirect pointers, as long as the underlying
884memory is not deallocated. The conversion to <tt>const
885__unsafe_unretained</tt> is permitted because the semantics of reads
886are equivalent across all these ownership semantics, and that's a very
887useful and common pattern. The interconversion with <tt>void*</tt> is
888useful for allocating memory or otherwise escaping the type system,
889but use it carefully. <tt>reinterpret_cast</tt> is considered to be
890an obvious enough sign of taking responsibility for any
891problems.</p></div>
892
893<p>It is undefined behavior to access an ownership-qualified object
894through an lvalue of a differently-qualified type, except that any
895non-<tt>__weak</tt> object may be read through
896an <tt>__unsafe_unretained</tt> lvalue.</p>
897
898<p>It is undefined behavior if a managed operation is performed on
899a <tt>__strong</tt> or <tt>__weak</tt> object without a guarantee that
900it contains a primitive zero bit-pattern, or if the storage for such
901an object is freed or reused without the object being first assigned a
902null pointer.</p>
903
904<div class="rationale"><p>Rationale: ARC cannot differentiate between
905an assignment operator which is intended to <q>initialize</q> dynamic
906memory and one which is intended to potentially replace a value.
907Therefore the object's pointer must be valid before letting ARC at it.
908Similarly, C and Objective-C do not provide any language hooks for
909destroying objects held in dynamic memory, so it is the programmer's
910responsibility to avoid leaks (<tt>__strong</tt> objects) and
911consistency errors (<tt>__weak</tt> objects).</p>
912
913<p>These requirements are followed automatically in Objective-C++ when
914creating objects of retainable object owner type with <tt>new</tt>
915or <tt>new[]</tt> and destroying them with <tt>delete</tt>,
916<tt>delete[]</tt>, or a pseudo-destructor expression. Note that
917arrays of nontrivially-ownership-qualified type are not ABI compatible
918with non-ARC code because the element type is non-POD: such arrays
919that are <tt>new[]</tt>'d in ARC translation units cannot
920be <tt>delete[]</tt>'d in non-ARC translation units and
921vice-versa.</p></div>
922
923</div>
924
925<div id="ownership.restrictions.pass_by_writeback">
926<h1>Passing to an out parameter by writeback</h1>
927
928<p>If the argument passed to a parameter of type
929<tt>T __autoreleasing *</tt> has type <tt>U oq *</tt>,
930where <tt>oq</tt> is an ownership qualifier, then the argument is a
931candidate for <span class="term">pass-by-writeback</span> if:</p>
932
933<ul>
Benjamin Kramer665a8dc2012-01-15 15:26:07 +0000934<li><tt>oq</tt> is <tt>__strong</tt> or <tt>__weak</tt>, and</li>
John McCall82467022011-06-15 21:21:53 +0000935<li>it would be legal to initialize a <tt>T __strong *</tt> with
936a <tt>U __strong *</tt>.</li>
937</ul>
938
939<p>For purposes of overload resolution, an implicit conversion
940sequence requiring a pass-by-writeback is always worse than an
941implicit conversion sequence not requiring a pass-by-writeback.</p>
942
943<p>The pass-by-writeback is ill-formed if the argument expression does
944not have a legal form:</p>
945
946<ul>
Benjamin Kramer665a8dc2012-01-15 15:26:07 +0000947<li><tt>&amp;var</tt>, where <tt>var</tt> is a scalar variable of
John McCall82467022011-06-15 21:21:53 +0000948automatic storage duration with retainable object pointer type</li>
949<li>a conditional expression where the second and third operands are
950both legal forms</li>
951<li>a cast whose operand is a legal form</li>
952<li>a null pointer constant</li>
953</ul>
954
955<div class="rationale"><p>Rationale: the restriction in the form of
956the argument serves two purposes. First, it makes it impossible to
957pass the address of an array to the argument, which serves to protect
958against an otherwise serious risk of mis-inferring an <q>array</q>
959argument as an out-parameter. Second, it makes it much less likely
960that the user will see confusing aliasing problems due to the
961implementation, below, where their store to the writeback temporary is
962not immediately seen in the original argument variable.</p></div>
963
Benjamin Kramer665a8dc2012-01-15 15:26:07 +0000964<p>A pass-by-writeback is evaluated as follows:</p>
John McCall82467022011-06-15 21:21:53 +0000965<ol>
966<li>The argument is evaluated to yield a pointer <tt>p</tt> of
967 type <tt>U oq *</tt>.</li>
968<li>If <tt>p</tt> is a null pointer, then a null pointer is passed as
969 the argument, and no further work is required for the pass-by-writeback.</li>
970<li>Otherwise, a temporary of type <tt>T __autoreleasing</tt> is
971 created and initialized to a null pointer.</li>
972<li>If the argument is not an Objective-C method parameter marked
973 <tt>out</tt>, then <tt>*p</tt> is read, and the result is written
974 into the temporary with primitive semantics.</li>
975<li>The address of the temporary is passed as the argument to the
976 actual call.</li>
977<li>After the call completes, the temporary is loaded with primitive
978 semantics, and that value is assigned into <tt>*p</tt>.</li>
Benjamin Kramer665a8dc2012-01-15 15:26:07 +0000979</ol>
John McCall82467022011-06-15 21:21:53 +0000980
981<div class="rationale"><p>Rationale: this is all admittedly
982convoluted. In an ideal world, we would see that a local variable is
983being passed to an out-parameter and retroactively modify its type to
984be <tt>__autoreleasing</tt> rather than <tt>__strong</tt>. This would
985be remarkably difficult and not always well-founded under the C type
986system. However, it was judged unacceptably invasive to require
987programmers to write <tt>__autoreleasing</tt> on all the variables
988they intend to use for out-parameters. This was the least bad
989solution.</p></div>
990
991</div>
992
993<div id="ownership.restrictions.records">
994<h1>Ownership-qualified fields of structs and unions</h1>
995
996<p>A program is ill-formed if it declares a member of a C struct or
997union to have a nontrivially ownership-qualified type.</p>
998
999<div class="rationale"><p>Rationale: the resulting type would be
1000non-POD in the C++ sense, but C does not give us very good language
1001tools for managing the lifetime of aggregates, so it is more
1002convenient to simply forbid them. It is still possible to manage this
1003with a <tt>void*</tt> or an <tt>__unsafe_unretained</tt>
1004object.</p></div>
1005
1006<p>This restriction does not apply in Objective-C++. However,
David Blaikie5090e9f2011-10-18 05:49:30 +00001007nontrivally ownership-qualified types are considered non-POD: in C++11
John McCall82467022011-06-15 21:21:53 +00001008terms, they are not trivially default constructible, copy
1009constructible, move constructible, copy assignable, move assignable,
1010or destructible. It is a violation of C++ One Definition Rule to use
1011a class outside of ARC that, under ARC, would have an
1012ownership-qualified member.</p>
1013
1014<div class="rationale"><p>Rationale: unlike in C, we can express all
1015the necessary ARC semantics for ownership-qualified subobjects as
1016suboperations of the (default) special member functions for the class.
1017These functions then become non-trivial. This has the non-obvious
1018repercussion that the class will have a non-trivial copy constructor
1019and non-trivial destructor; if it wouldn't outside of ARC, this means
1020that objects of the type will be passed and returned in an
1021ABI-incompatible manner.</p></div>
1022
1023</div>
1024
1025</div>
1026
1027<div id="ownership.inference">
1028<h1>Ownership inference</h1>
1029
1030<div id="ownership.inference.variables">
1031<h1>Objects</h1>
1032
1033<p>If an object is declared with retainable object owner type, but
1034without an explicit ownership qualifier, its type is implicitly
1035adjusted to have <tt>__strong</tt> qualification.</p>
1036
1037<p>As a special case, if the object's base type is <tt>Class</tt>
1038(possibly protocol-qualified), the type is adjusted to
1039have <tt>__unsafe_unretained</tt> qualification instead.</p>
1040
1041</div>
1042
1043<div id="ownership.inference.indirect_parameters">
1044<h1>Indirect parameters</h1>
1045
1046<p>If a function or method parameter has type <tt>T*</tt>, where
1047<tt>T</tt> is an ownership-unqualified retainable object pointer type,
1048then:</p>
1049
1050<ul>
1051<li>if <tt>T</tt> is <tt>const</tt>-qualified or <tt>Class</tt>, then
1052it is implicitly qualified with <tt>__unsafe_unretained</tt>;</li>
1053<li>otherwise, it is implicitly qualified
1054with <tt>__autoreleasing</tt>.</li>
1055</ul>
John McCall82467022011-06-15 21:21:53 +00001056
1057<div class="rationale"><p>Rationale: <tt>__autoreleasing</tt> exists
1058mostly for this case, the Cocoa convention for out-parameters. Since
1059a pointer to <tt>const</tt> is obviously not an out-parameter, we
1060instead use a type more useful for passing arrays. If the user
1061instead intends to pass in a <em>mutable</em> array, inferring
1062<tt>__autoreleasing</tt> is the wrong thing to do; this directs some
1063of the caution in the following rules about writeback.</p></div>
1064
1065<p>Such a type written anywhere else would be ill-formed by the
1066general rule requiring ownership qualifiers.</p>
1067
1068<p>This rule does not apply in Objective-C++ if a parameter's type is
1069dependent in a template pattern and is only <em>instantiated</em> to
1070a type which would be a pointer to an unqualified retainable object
1071pointer type. Such code is still ill-formed.</p>
1072
1073<div class="rationale"><p>Rationale: the convention is very unlikely
1074to be intentional in template code.</p></div>
1075
1076</div> <!-- ownership.inference.indirect_parameters -->
Douglas Gregore559ca12011-06-17 22:11:49 +00001077
1078<div id="ownership.inference.template_arguments">
1079<h1>Template arguments</h1>
1080
1081<p>If a template argument for a template type parameter is an
1082retainable object owner type that does not have an explicit ownership
1083qualifier, it is adjusted to have <tt>__strong</tt>
Douglas Gregor54fb28a2011-06-17 22:19:27 +00001084qualification. This adjustment occurs regardless of whether the
Douglas Gregore559ca12011-06-17 22:11:49 +00001085template argument was deduced or explicitly specified. </p>
1086
1087<div class="rationale"><p>Rationale: <tt>__strong</tt> is a useful default for containers (e.g., <tt>std::vector&lt;id&gt;</tt>), which would otherwise require explicit qualification. Moreover, unqualified retainable object pointer types are unlikely to be useful within templates, since they generally need to have a qualifier applied to the before being used.</p></div>
1088
1089</div> <!-- ownership.inference.template_arguments -->
John McCall82467022011-06-15 21:21:53 +00001090</div> <!-- ownership.inference -->
1091</div> <!-- ownership -->
1092
Douglas Gregore559ca12011-06-17 22:11:49 +00001093
John McCall82467022011-06-15 21:21:53 +00001094<div id="family">
1095<h1>Method families</h1>
1096
1097<p>An Objective-C method may fall into a <span class="term">method
1098family</span>, which is a conventional set of behaviors ascribed to it
1099by the Cocoa conventions.</p>
1100
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00001101<p>A method is in a certain method family if:</p>
John McCall82467022011-06-15 21:21:53 +00001102<ul>
1103<li>it has a <tt>objc_method_family</tt> attribute placing it in that
1104 family; or if not that,</li>
1105<li>it does not have an <tt>objc_method_family</tt> attribute placing
1106 it in a different or no family, and</li>
1107<li>its selector falls into the corresponding selector family, and</li>
1108<li>its signature obeys the added restrictions of the method family.</li>
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00001109</ul>
John McCall82467022011-06-15 21:21:53 +00001110
1111<p>A selector is in a certain selector family if, ignoring any leading
1112underscores, the first component of the selector either consists
1113entirely of the name of the method family or it begins with that name
1114followed by a character other than a lowercase letter. For
1115example, <tt>_perform:with:</tt> and <tt>performWith:</tt> would fall
1116into the <tt>perform</tt> family (if we recognized one),
1117but <tt>performing:with</tt> would not.</p>
1118
1119<p>The families and their added restrictions are:</p>
1120
1121<ul>
1122<li><tt>alloc</tt> methods must return a retainable object pointer type.</li>
1123<li><tt>copy</tt> methods must return a retainable object pointer type.</li>
1124<li><tt>mutableCopy</tt> methods must return a retainable object pointer type.</li>
1125<li><tt>new</tt> methods must return a retainable object pointer type.</li>
1126<li><tt>init</tt> methods must be instance methods and must return an
1127Objective-C pointer type. Additionally, a program is ill-formed if it
1128declares or contains a call to an <tt>init</tt> method whose return
1129type is neither <tt>id</tt> nor a pointer to a super-class or
John McCallbe16b892011-06-18 08:15:19 +00001130sub-class of the declaring class (if the method was declared on
1131a class) or the static receiver type of the call (if it was declared
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00001132on a protocol).
John McCall82467022011-06-15 21:21:53 +00001133
1134<div class="rationale"><p>Rationale: there are a fair number of existing
1135methods with <tt>init</tt>-like selectors which nonetheless don't
1136follow the <tt>init</tt> conventions. Typically these are either
1137accidental naming collisions or helper methods called during
1138initialization. Because of the peculiar retain/release behavior
1139of <tt>init</tt> methods, it's very important not to treat these
1140methods as <tt>init</tt> methods if they aren't meant to be. It was
1141felt that implicitly defining these methods out of the family based on
1142the exact relationship between the return type and the declaring class
John McCallbe16b892011-06-18 08:15:19 +00001143would be much too subtle and fragile. Therefore we identify a small
John McCall82467022011-06-15 21:21:53 +00001144number of legitimate-seeming return types and call everything else an
1145error. This serves the secondary purpose of encouraging programmers
John McCallbe16b892011-06-18 08:15:19 +00001146not to accidentally give methods names in the <tt>init</tt> family.</p>
1147
1148<p>Note that a method with an <tt>init</tt>-family selector which
1149returns a non-Objective-C type (e.g. <tt>void</tt>) is perfectly
1150well-formed; it simply isn't in the <tt>init</tt> family.</p></div>
John McCall82467022011-06-15 21:21:53 +00001151</li>
1152</ul>
1153
1154<p>A program is ill-formed if a method's declarations,
1155implementations, and overrides do not all have the same method
1156family.</p>
1157
1158<div id="family.attribute">
1159<h1>Explicit method family control</h1>
1160
1161<p>A method may be annotated with the <tt>objc_method_family</tt>
1162attribute to precisely control which method family it belongs to. If
1163a method in an <tt>@implementation</tt> does not have this attribute,
1164but there is a method declared in the corresponding <tt>@interface</tt>
1165that does, then the attribute is copied to the declaration in the
1166<tt>@implementation</tt>. The attribute is available outside of ARC,
1167and may be tested for with the preprocessor query
1168<tt>__has_attribute(objc_method_family)</tt>.</p>
1169
1170<p>The attribute is spelled
1171<tt>__attribute__((objc_method_family(<i>family</i>)))</tt>.
1172If <i>family</i> is <tt>none</tt>, the method has no family, even if
1173it would otherwise be considered to have one based on its selector and
1174type. Otherwise, <i>family</i> must be one
1175of <tt>alloc</tt>, <tt>copy</tt>, <tt>init</tt>,
1176<tt>mutableCopy</tt>, or <tt>new</tt>, in which case the method is
1177considered to belong to the corresponding family regardless of its
1178selector. It is an error if a method that is explicitly added to a
1179family in this way does not meet the requirements of the family other
1180than the selector naming convention.</p>
1181
1182<div class="rationale"><p>Rationale: the rules codified in this document
1183describe the standard conventions of Objective-C. However, as these
1184conventions have not heretofore been enforced by an unforgiving
1185mechanical system, they are only imperfectly kept, especially as they
1186haven't always even been precisely defined. While it is possible to
1187define low-level ownership semantics with attributes like
1188<tt>ns_returns_retained</tt>, this attribute allows the user to
1189communicate semantic intent, which of use both to ARC (which, e.g.,
1190treats calls to <tt>init</tt> specially) and the static analyzer.</p></div>
1191</div>
1192
1193<div id="family.semantics">
1194<h1>Semantics of method families</h1>
1195
1196<p>A method's membership in a method family may imply non-standard
1197semantics for its parameters and return type.</p>
1198
1199<p>Methods in the <tt>alloc</tt>, <tt>copy</tt>, <tt>mutableCopy</tt>,
1200and <tt>new</tt> families &mdash; that is, methods in all the
John McCallbe16b892011-06-18 08:15:19 +00001201currently-defined families except <tt>init</tt> &mdash; implicitly
1202<a href="#objects.operands.retained_returns">return a retained
1203object</a> as if they were annotated with
1204the <tt>ns_returns_retained</tt> attribute. This can be overridden by
1205annotating the method with either of
1206the <tt>ns_returns_autoreleased</tt> or
John McCall82467022011-06-15 21:21:53 +00001207<tt>ns_returns_not_retained</tt> attributes.</p>
1208
Fariborz Jahanianacd4aaf2011-07-06 22:47:46 +00001209<p>Properties also follow same naming rules as methods. This means that
1210those in the <tt>alloc</tt>, <tt>copy</tt>, <tt>mutableCopy</tt>,
1211and <tt>new</tt> families provide access to
1212<a href="#objects.operands.retained_returns">retained objects</a>.
1213This can be overridden by annotating the property with
1214<tt>ns_returns_not_retained</tt> attribute.</p>
1215
John McCall82467022011-06-15 21:21:53 +00001216<div id="family.semantics.init">
1217<h1>Semantics of <tt>init</tt></h1>
John McCallbe16b892011-06-18 08:15:19 +00001218<p>Methods in the <tt>init</tt> family implicitly
1219<a href="#objects.operands.consumed">consume</a> their <tt>self</tt>
1220parameter and <a href="#objects.operands.retained_returns">return a
1221retained object</a>. Neither of these properties can be altered
1222through attributes.</p>
John McCall82467022011-06-15 21:21:53 +00001223
1224<p>A call to an <tt>init</tt> method with a receiver that is either
1225<tt>self</tt> (possibly parenthesized or casted) or <tt>super</tt> is
1226called a <span class="term">delegate init call</span>. It is an error
1227for a delegate init call to be made except from an <tt>init</tt>
1228method, and excluding blocks within such methods.</p>
1229
John McCallbe16b892011-06-18 08:15:19 +00001230<p>As an exception to the <a href="misc.self">usual rule</a>, the
1231variable <tt>self</tt> is mutable in an <tt>init</tt> method and has
1232the usual semantics for a <tt>__strong</tt> variable. However, it is
1233undefined behavior and the program is ill-formed, no diagnostic
1234required, if an <tt>init</tt> method attempts to use the previous
1235value of <tt>self</tt> after the completion of a delegate init call.
1236It is conventional, but not required, for an <tt>init</tt> method to
1237return <tt>self</tt>.</p>
John McCall82467022011-06-15 21:21:53 +00001238
John McCallbe16b892011-06-18 08:15:19 +00001239<p>It is undefined behavior for a program to cause two or more calls
1240to <tt>init</tt> methods on the same object, except that
1241each <tt>init</tt> method invocation may perform at most one delegate
1242init call.</p>
John McCall82467022011-06-15 21:21:53 +00001243
John McCallf3d08a62011-06-18 07:31:30 +00001244</div> <!-- family.semantics.init -->
John McCall82467022011-06-15 21:21:53 +00001245
1246<div id="family.semantics.result_type">
1247<h1>Related result types</h1>
1248
1249<p>Certain methods are candidates to have <span class="term">related
1250result types</span>:</p>
1251<ul>
1252<li>class methods in the <tt>alloc</tt> and <tt>new</tt> method families</li>
1253<li>instance methods in the <tt>init</tt> family</li>
1254<li>the instance method <tt>self</tt></li>
1255<li>outside of ARC, the instance methods <tt>retain</tt> and <tt>autorelease</tt></li>
1256</ul>
1257
1258<p>If the formal result type of such a method is <tt>id</tt> or
1259protocol-qualified <tt>id</tt>, or a type equal to the declaring class
1260or a superclass, then it is said to have a related result type. In
1261this case, when invoked in an explicit message send, it is assumed to
1262return a type related to the type of the receiver:</p>
1263
1264<ul>
1265<li>if it is a class method, and the receiver is a class
1266name <tt>T</tt>, the message send expression has type <tt>T*</tt>;
1267otherwise</li>
1268<li>if it is an instance method, and the receiver has type <tt>T</tt>,
1269the message send expression has type <tt>T</tt>; otherwise</li>
1270<li>the message send expression has the normal result type of the
1271method.</li>
1272</ul>
1273
1274<p>This is a new rule of the Objective-C language and applies outside
1275of ARC.</p>
1276
1277<div class="rationale"><p>Rationale: ARC's automatic code emission is
1278more prone than most code to signature errors, i.e. errors where a
1279call was emitted against one method signature, but the implementing
1280method has an incompatible signature. Having more precise type
1281information helps drastically lower this risks, as well as catching
1282a number of latent bugs.</p></div>
1283
1284</div> <!-- family.semantics.result_type -->
1285</div> <!-- family.semantics -->
1286</div> <!-- family -->
1287
1288<div id="optimization">
1289<h1>Optimization</h1>
1290
1291<p>ARC applies aggressive rules for the optimization of local
1292behavior. These rules are based around a core assumption of
1293<span class="term">local balancing</span>: that other code will
1294perform retains and releases as necessary (and only as necessary) for
1295its own safety, and so the optimizer does not need to consider global
1296properties of the retain and release sequence. For example, if a
1297retain and release immediately bracket a call, the optimizer can
1298delete the retain and release on the assumption that the called
1299function will not do a constant number of unmotivated releases
1300followed by a constant number of <q>balancing</q> retains, such that
1301the local retain/release pair is the only thing preventing the called
1302function from ending up with a dangling reference.</p>
1303
1304<p>The optimizer assumes that when a new value enters local control,
1305e.g. from a load of a non-local object or as the result of a function
1306call, it is instaneously valid. Subsequently, a retain and release of
1307a value are necessary on a computation path only if there is a use of
1308that value before the release and after any operation which might
1309cause a release of the value (including indirectly or non-locally),
1310and only if the value is not demonstrably already retained.</p>
1311
1312<p>The complete optimization rules are quite complicated, but it would
1313still be useful to document them here.</p>
1314
John McCalldc7c5ad2011-07-22 08:53:00 +00001315<div id="optimization.precise">
1316<h1>Precise lifetime semantics</h1>
1317
1318<p>In general, ARC maintains an invariant that a retainable object
1319pointer held in a <tt>__strong</tt> object will be retained for the
1320full formal lifetime of the object. Objects subject to this invariant
1321have <span class="term">precise lifetime semantics</span>.</p>
1322
1323<p>By default, local variables of automatic storage duration do not
1324have precise lifetime semantics. Such objects are simply strong
1325references which hold values of retainable object pointer type, and
1326these values are still fully subject to the optimizations on values
1327under local control.</p>
1328
1329<div class="rationale"><p>Rationale: applying these precise-lifetime
1330semantics strictly would be prohibitive. Many useful optimizations
1331that might theoretically decrease the lifetime of an object would be
1332rendered impossible. Essentially, it promises too much.</p></div>
1333
1334<p>A local variable of retainable object owner type and automatic
1335storage duration may be annotated with the <tt>objc_precise_lifetime</tt>
1336attribute to indicate that it should be considered to be an object
1337with precise lifetime semantics.</p>
1338
1339<div class="rationale"><p>Rationale: nonetheless, it is sometimes
1340useful to be able to force an object to be released at a precise time,
1341even if that object does not appear to be used. This is likely to be
1342uncommon enough that the syntactic weight of explicitly requesting
1343these semantics will not be burdensome, and may even make the code
1344clearer.</p></div>
1345
1346</div> <!-- optimization.precise -->
1347
John McCall82467022011-06-15 21:21:53 +00001348</div>
1349
1350<div id="misc">
1351<h1>Miscellaneous</h1>
1352
John McCallf3d08a62011-06-18 07:31:30 +00001353<div id="misc.special_methods">
1354<h1>Special methods</h1>
1355
1356<div id="misc.special_methods.retain">
1357<h1>Memory management methods</h1>
1358
1359<p>A program is ill-formed if it contains a method definition, message
1360send, or <tt>@selector</tt> expression for any of the following
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00001361selectors:</p>
John McCallf3d08a62011-06-18 07:31:30 +00001362<ul>
1363<li><tt>autorelease</tt></li>
1364<li><tt>release</tt></li>
1365<li><tt>retain</tt></li>
1366<li><tt>retainCount</tt></li>
1367</ul>
John McCallf3d08a62011-06-18 07:31:30 +00001368
1369<div class="rationale"><p>Rationale: <tt>retainCount</tt> is banned
1370because ARC robs it of consistent semantics. The others were banned
1371after weighing three options for how to deal with message sends:</p>
1372
1373<p><b>Honoring</b> them would work out very poorly if a programmer
1374naively or accidentally tried to incorporate code written for manual
1375retain/release code into an ARC program. At best, such code would do
1376twice as much work as necessary; quite frequently, however, ARC and
1377the explicit code would both try to balance the same retain, leading
1378to crashes. The cost is losing the ability to perform <q>unrooted</q>
1379retains, i.e. retains not logically corresponding to a strong
1380reference in the object graph.</p>
1381
1382<p><b>Ignoring</b> them would badly violate user expectations about their
1383code. While it <em>would</em> make it easier to develop code simultaneously
1384for ARC and non-ARC, there is very little reason to do so except for
1385certain library developers. ARC and non-ARC translation units share
1386an execution model and can seamlessly interoperate. Within a
1387translation unit, a developer who faithfully maintains their code in
1388non-ARC mode is suffering all the restrictions of ARC for zero
1389benefit, while a developer who isn't testing the non-ARC mode is
1390likely to be unpleasantly surprised if they try to go back to it.</p>
1391
1392<p><b>Banning</b> them has the disadvantage of making it very awkward
1393to migrate existing code to ARC. The best answer to that, given a
1394number of other changes and restrictions in ARC, is to provide a
1395specialized tool to assist users in that migration.</p>
1396
1397<p>Implementing these methods was banned because they are too integral
1398to the semantics of ARC; many tricks which worked tolerably under
1399manual reference counting will misbehave if ARC performs an ephemeral
1400extra retain or two. If absolutely required, it is still possible to
1401implement them in non-ARC code, for example in a category; the
1402implementations must obey the <a href="#objects.retains">semantics</a>
1403laid out elsewhere in this document.</p>
1404
1405</div>
1406</div> <!-- misc.special_methods.retain -->
1407
1408<div id="misc.special_methods.dealloc">
1409<h1><tt>dealloc</tt></h1>
1410
1411<p>A program is ill-formed if it contains a message send
1412or <tt>@selector</tt> expression for the selector <tt>dealloc</tt>.</p>
1413
1414<div class="rationale"><p>Rationale: there are no legitimate reasons
1415to call <tt>dealloc</tt> directly.</p></div>
1416
1417<p>A class may provide a method definition for an instance method
1418named <tt>dealloc</tt>. This method will be called after the final
1419<tt>release</tt> of the object but before it is deallocated or any of
1420its instance variables are destroyed. The superclass's implementation
1421of <tt>dealloc</tt> will be called automatically when the method
1422returns.</p>
1423
1424<div class="rationale"><p>Rationale: even though ARC destroys instance
1425variables automatically, there are still legitimate reasons to write
1426a <tt>dealloc</tt> method, such as freeing non-retainable resources.
1427Failing to call <tt>[super&nbsp;dealloc]</tt> in such a method is nearly
1428always a bug. Sometimes, the object is simply trying to prevent
1429itself from being destroyed, but <tt>dealloc</tt> is really far too
1430late for the object to be raising such objections. Somewhat more
1431legitimately, an object may have been pool-allocated and should not be
1432deallocated with <tt>free</tt>; for now, this can only be supported
1433with a <tt>dealloc</tt> implementation outside of ARC. Such an
1434implementation must be very careful to do all the other work
1435that <tt>NSObject</tt>'s <tt>dealloc</tt> would, which is outside the
1436scope of this document to describe.</p></div>
1437
1438</div>
1439
1440</div> <!-- misc.special_methods -->
1441
John McCall82467022011-06-15 21:21:53 +00001442<div id="autoreleasepool">
1443<h1><tt>@autoreleasepool</tt></h1>
1444
1445<p>To simplify the use of autorelease pools, and to bring them under
1446the control of the compiler, a new kind of statement is available in
1447Objective-C. It is written <tt>@autoreleasepool</tt> followed by
1448a <i>compound-statement</i>, i.e. by a new scope delimited by curly
1449braces. Upon entry to this block, the current state of the
1450autorelease pool is captured. When the block is exited normally,
1451whether by fallthrough or directed control flow (such
1452as <tt>return</tt> or <tt>break</tt>), the autorelease pool is
1453restored to the saved state, releasing all the objects in it. When
1454the block is exited with an exception, the pool is not drained.</p>
1455
John McCallf3d08a62011-06-18 07:31:30 +00001456<p><tt>@autoreleasepool</tt> may be used in non-ARC translation units,
1457with equivalent semantics.</p>
1458
John McCall82467022011-06-15 21:21:53 +00001459<p>A program is ill-formed if it refers to the
1460<tt>NSAutoreleasePool</tt> class.</p>
1461
1462<div class="rationale"><p>Rationale: autorelease pools are clearly
1463important for the compiler to reason about, but it is far too much to
1464expect the compiler to accurately reason about control dependencies
1465between two calls. It is also very easy to accidentally forget to
1466drain an autorelease pool when using the manual API, and this can
1467significantly inflate the process's high-water-mark. The introduction
1468of a new scope is unfortunate but basically required for sane
1469interaction with the rest of the language. Not draining the pool
1470during an unwind is apparently required by the Objective-C exceptions
1471implementation.</p></div>
1472
1473</div> <!-- autoreleasepool -->
1474
1475<div id="misc.self">
1476<h1><tt>self</tt></h1>
1477
1478<p>The <tt>self</tt> parameter variable of an Objective-C method is
1479never actually retained by the implementation. It is undefined
1480behavior, or at least dangerous, to cause an object to be deallocated
Ted Kremenek2bbcd5c2011-11-14 21:59:25 +00001481during a message send to that object.</p>
1482
1483<p>To make this safe, for Objective-C instance methods <tt>self</tt> is
1484implicitly <tt>const</tt> unless the method is in the <a
1485href="#family.semantics.init"><tt>init</tt> family</a>. Further, <tt>self</tt>
1486is <b>always</b> implicitly <tt>const</tt> within a class method.</p>
John McCall82467022011-06-15 21:21:53 +00001487
1488<div class="rationale"><p>Rationale: the cost of
1489retaining <tt>self</tt> in all methods was found to be prohibitive, as
1490it tends to be live across calls, preventing the optimizer from
1491proving that the retain and release are unnecessary &mdash; for good
1492reason, as it's quite possible in theory to cause an object to be
1493deallocated during its execution without this retain and release.
1494Since it's extremely uncommon to actually do so, even unintentionally,
1495and since there's no natural way for the programmer to remove this
1496retain/release pair otherwise (as there is for other parameters by,
1497say, making the variable <tt>__unsafe_unretained</tt>), we chose to
1498make this optimizing assumption and shift some amount of risk to the
1499user.</p></div>
1500
1501</div> <!-- misc.self -->
1502
1503<div id="misc.enumeration">
1504<h1>Fast enumeration iteration variables</h1>
1505
1506<p>If a variable is declared in the condition of an Objective-C fast
1507enumeration loop, and the variable has no explicit ownership
1508qualifier, then it is qualified with <tt>const __strong</tt> and
1509objects encountered during the enumeration are not actually
1510retained.</p>
1511
1512<div class="rationale"><p>Rationale: this is an optimization made
1513possible because fast enumeration loops promise to keep the objects
1514retained during enumeration, and the collection itself cannot be
1515synchronously modified. It can be overridden by explicitly qualifying
1516the variable with <tt>__strong</tt>, which will make the variable
1517mutable again and cause the loop to retain the objects it
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00001518encounters.</p></div>
John McCall82467022011-06-15 21:21:53 +00001519
1520</div>
1521
1522<div id="misc.blocks">
1523<h1>Blocks</h1>
1524
1525<p>The implicit <tt>const</tt> capture variables created when
1526evaluating a block literal expression have the same ownership
1527semantics as the local variables they capture. The capture is
1528performed by reading from the captured variable and initializing the
1529capture variable with that value; the capture variable is destroyed
1530when the block literal is, i.e. at the end of the enclosing scope.</p>
1531
1532<p>The <a href="#ownership.inference">inference</a> rules apply
1533equally to <tt>__block</tt> variables, which is a shift in semantics
1534from non-ARC, where <tt>__block</tt> variables did not implicitly
1535retain during capture.</p>
1536
1537<p><tt>__block</tt> variables of retainable object owner type are
1538moved off the stack by initializing the heap copy with the result of
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00001539moving from the stack copy.</p>
John McCall82467022011-06-15 21:21:53 +00001540
1541<p>With the exception of retains done as part of initializing
1542a <tt>__strong</tt> parameter variable or reading a <tt>__weak</tt>
1543variable, whenever these semantics call for retaining a value of
1544block-pointer type, it has the effect of a <tt>Block_copy</tt>. The
1545optimizer may remove such copies when it sees that the result is
1546used only as an argument to a call.</p>
1547
1548</div> <!-- misc.blocks -->
1549
1550<div id="misc.exceptions">
1551<h1>Exceptions</h1>
1552
1553<p>By default in Objective C, ARC is not exception-safe for normal
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00001554releases:</p>
John McCall82467022011-06-15 21:21:53 +00001555<ul>
1556<li>It does not end the lifetime of <tt>__strong</tt> variables when
1557their scopes are abnormally terminated by an exception.</li>
1558<li>It does not perform releases which would occur at the end of
1559a full-expression if that full-expression throws an exception.</li>
1560</ul>
1561
1562<p>A program may be compiled with the option
1563<tt>-fobjc-arc-exceptions</tt> in order to enable these, or with the
1564option <tt>-fno-objc-arc-exceptions</tt> to explicitly disable them,
1565with the last such argument <q>winning</q>.</p>
1566
1567<div class="rationale"><p>Rationale: the standard Cocoa convention is
1568that exceptions signal programmer error and are not intended to be
1569recovered from. Making code exceptions-safe by default would impose
1570severe runtime and code size penalties on code that typically does not
1571actually care about exceptions safety. Therefore, ARC-generated code
1572leaks by default on exceptions, which is just fine if the process is
1573going to be immediately terminated anyway. Programs which do care
1574about recovering from exceptions should enable the option.</p></div>
1575
1576<p>In Objective-C++, <tt>-fobjc-arc-exceptions</tt> is enabled by
1577default.</p>
1578
1579<div class="rationale"><p>Rationale: C++ already introduces pervasive
1580exceptions-cleanup code of the sort that ARC introduces. C++
1581programmers who have not already disabled exceptions are much more
1582likely to actual require exception-safety.</p></div>
1583
1584<p>ARC does end the lifetimes of <tt>__weak</tt> objects when an
1585exception terminates their scope unless exceptions are disabled in the
1586compiler.</p>
1587
1588<div class="rationale"><p>Rationale: the consequence of a
1589local <tt>__weak</tt> object not being destroyed is very likely to be
1590corruption of the Objective-C runtime, so we want to be safer here.
1591Of course, potentially massive leaks are about as likely to take down
1592the process as this corruption is if the program does try to recover
1593from exceptions.</p></div>
1594
1595</div> <!-- misc.exceptions -->
1596
John McCalldc7c5ad2011-07-22 08:53:00 +00001597<div id="misc.interior">
1598<h1>Interior pointers</h1>
1599
1600<p>An Objective-C method returning a non-retainable pointer may be
1601annotated with the <tt>objc_returns_inner_pointer</tt> attribute to
1602indicate that it returns a handle to the internal data of an object,
1603and that this reference will be invalidated if the object is
1604destroyed. When such a message is sent to an object, the object's
1605lifetime will be extended until at least the earliest of:</p>
1606
1607<ul>
1608<li>the last use of the returned pointer, or any pointer derived from
1609it, in the calling function or</li>
1610<li>the autorelease pool is restored to a previous state.</li>
1611</ul>
1612
1613<div class="rationale"><p>Rationale: not all memory and resources are
1614managed with reference counts; it is common for objects to manage
1615private resources in their own, private way. Typically these
1616resources are completely encapsulated within the object, but some
1617classes offer their users direct access for efficiency. If ARC is not
1618aware of methods that return such <q>interior</q> pointers, its
1619optimizations can cause the owning object to be reclaimed too soon.
1620This attribute informs ARC that it must tread lightly.</p>
1621
1622<p>The extension rules are somewhat intentionally vague. The
1623autorelease pool limit is there to permit a simple implementation to
1624simply retain and autorelease the receiver. The other limit permits
1625some amount of optimization. The phrase <q>derived from</q> is
1626intended to encompass the results both of pointer transformations,
1627such as casts and arithmetic, and of loading from such derived
1628pointers; furthermore, it applies whether or not such derivations are
1629applied directly in the calling code or by other utility code (for
1630example, the C library routine <tt>strchr</tt>). However, the
1631implementation never need account for uses after a return from the
1632code which calls the method returning an interior pointer.</p></div>
1633
1634<p>As an exception, no extension is required if the receiver is loaded
1635directly from a <tt>__strong</tt> object
1636with <a href="#optimization.precise">precise lifetime semantics</a>.</p>
1637
1638<div class="rationale"><p>Rationale: implicit autoreleases carry the
1639risk of significantly inflating memory use, so it's important to
1640provide users a way of avoiding these autoreleases. Tying this to
1641precise lifetime semantics is ideal, as for local variables this
1642requires a very explicit annotation, which allows ARC to trust the
1643user with good cheer.</p></div>
1644
1645</div> <!-- misc.interior -->
1646
John McCall82467022011-06-15 21:21:53 +00001647</div> <!-- misc -->
John McCall98a48cf2011-06-19 09:36:02 +00001648
1649<div id="runtime">
1650<h1>Runtime support</h1>
1651
John McCall085d09d2011-06-19 10:12:24 +00001652<p>This section describes the interaction between the ARC runtime and
1653the code generated by the ARC compiler. This is not part of the ARC
1654language specification; instead, it is effectively a language-specific
1655ABI supplement, akin to the <q>Itanium</q> generic ABI for C++.</p>
John McCall98a48cf2011-06-19 09:36:02 +00001656
1657<p>Ownership qualification does not alter the storage requirements for
John McCall085d09d2011-06-19 10:12:24 +00001658objects, except that it is undefined behavior if a <tt>__weak</tt>
1659object is inadequately aligned for an object of type <tt>id</tt>. The
1660other qualifiers may be used on explicitly under-aligned memory.</p>
John McCall98a48cf2011-06-19 09:36:02 +00001661
1662<p>The runtime tracks <tt>__weak</tt> objects which holds non-null
John McCall3914a302011-06-19 09:59:33 +00001663values. It is undefined behavior to direct modify a <tt>__weak</tt>
1664object which is being tracked by the runtime except through an
1665<a href="#runtime.objc_storeWeak"><tt>objc_storeWeak</tt></a>,
1666<a href="#runtime.objc_destroyWeak"><tt>objc_destroyWeak</tt></a>,
1667or <a href="#runtime.objc_moveWeak"><tt>objc_moveWeak</tt></a>
John McCall98a48cf2011-06-19 09:36:02 +00001668call.</p>
1669
John McCall3914a302011-06-19 09:59:33 +00001670<p>The runtime must provide a number of new entrypoints which the
1671compiler may emit, which are described in the remainder of this
1672section.</p>
1673
1674<div class="rationale"><p>Rationale: Several of these functions are
1675semantically equivalent to a message send; we emit calls to C
1676functions instead because:</p>
1677<ul>
1678<li>the machine code to do so is significantly smaller,</li>
1679<li>it is much easier to recognize the C functions in the ARC optimizer, and</li>
1680<li>a sufficient sophisticated runtime may be able to avoid the
1681message send in common cases.</li>
1682</ul>
1683
1684<p>Several other of these functions are <q>fused</q> operations which
1685can be described entirely in terms of other operations. We use the
1686fused operations primarily as a code-size optimization, although in
1687some cases there is also a real potential for avoiding redundant
1688operations in the runtime.</p>
1689
1690</div>
1691
John McCall98a48cf2011-06-19 09:36:02 +00001692<div id="runtime.objc_autorelease">
1693<h1><tt>id objc_autorelease(id value);</tt></h1>
1694<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a
1695valid object.</p>
1696<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it
1697adds the object to the innermost autorelease pool exactly as if the
1698object had been sent the <tt>autorelease</tt> message.</p>
1699<p>Always returns <tt>value</tt>.</p>
1700</div> <!-- runtime.objc_autorelease -->
1701
1702<div id="runtime.objc_autoreleasePoolPop">
1703<h1><tt>void objc_autoreleasePoolPop(void *pool);</tt></h1>
1704<p><i>Precondition:</i> <tt>pool</tt> is the result of a previous call to
1705<a href="runtime.objc_autoreleasePoolPush"><tt>objc_autoreleasePoolPush</tt></a>
1706on the current thread, where neither <tt>pool</tt> nor any enclosing
1707pool have previously been popped.</p>
1708<p>Releases all the objects added to the given autorelease pool and
1709any autorelease pools it encloses, then sets the current autorelease
1710pool to the pool directly enclosing <tt>pool</tt>.</p>
1711</div> <!-- runtime.objc_autoreleasePoolPop -->
1712
1713<div id="runtime.objc_autoreleasePoolPush">
1714<h1><tt>void *objc_autoreleasePoolPush(void);</tt></h1>
1715<p>Creates a new autorelease pool that is enclosed by the current
1716pool, makes that the current pool, and returns an opaque <q>handle</q>
1717to it.</p>
1718
1719<div class="rationale"><p>Rationale: while the interface is described
1720as an explicit hierarchy of pools, the rules allow the implementation
1721to just keep a stack of objects, using the stack depth as the opaque
1722pool handle.</p></div>
1723
1724</div> <!-- runtime.objc_autoreleasePoolPush -->
1725
1726<div id="runtime.objc_autoreleaseReturnValue">
1727<h1><tt>id objc_autoreleaseReturnValue(id value);</tt></h1>
1728<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a
1729valid object.</p>
1730<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it
1731makes a best effort to hand off ownership of a retain count on the
1732object to a call
1733to <a href="runtime.objc_retainAutoreleasedReturnValue"><tt>objc_retainAutoreleasedReturnValue</tt></a>
1734for the same object in an enclosing call frame. If this is not
1735possible, the object is autoreleased as above.</p>
1736<p>Always returns <tt>value</tt>.</p>
1737</div> <!-- runtime.objc_autoreleaseReturnValue -->
1738
1739<div id="runtime.objc_copyWeak">
1740<h1><tt>void objc_copyWeak(id *dest, id *src);</tt></h1>
1741<p><i>Precondition:</i> <tt>src</tt> is a valid pointer which either
1742contains a null pointer or has been registered as a <tt>__weak</tt>
1743object. <tt>dest</tt> is a valid pointer which has not been
1744registered as a <tt>__weak</tt> object.</p>
1745<p><tt>dest</tt> is initialized to be equivalent to <tt>src</tt>,
1746potentially registering it with the runtime. Equivalent to the
1747following code:</p>
1748<pre>void objc_copyWeak(id *dest, id *src) {
1749 objc_release(objc_initWeak(dest, objc_loadWeakRetained(src)));
1750}</pre>
1751<p>Must be atomic with respect to calls to <tt>objc_storeWeak</tt>
1752on <tt>src</tt>.</p>
1753</div> <!-- runtime.objc_copyWeak -->
1754
1755<div id="runtime.objc_destroyWeak">
1756<h1><tt>void objc_destroyWeak(id *object);</tt></h1>
1757<p><i>Precondition:</i> <tt>object</tt> is a valid pointer which
1758either contains a null pointer or has been registered as
1759a <tt>__weak</tt> object.</p>
1760<p><tt>object</tt> is unregistered as a weak object, if it ever was.
1761The current value of <tt>object</tt> is left unspecified; otherwise,
1762equivalent to the following code:</p>
1763<pre>void objc_destroyWeak(id *object) {
1764 objc_storeWeak(object, nil);
1765}</pre>
1766<p>Does not need to be atomic with respect to calls
1767to <tt>objc_storeWeak</tt> on <tt>object</tt>.</p>
1768</div> <!-- runtime.objc_destroyWeak -->
1769
1770<div id="runtime.objc_initWeak">
1771<h1><tt>id objc_initWeak(id *object, id value);</tt></h1>
1772<p><i>Precondition:</i> <tt>object</tt> is a valid pointer which has
1773not been registered as a <tt>__weak</tt> object. <tt>value</tt> is
1774null or a pointer to a valid object.</p>
1775<p>If <tt>value</tt> is a null pointer or the object to which it
1776points has begun deallocation, <tt>object</tt> is zero-initialized.
1777Otherwise, <tt>object</tt> is registered as a <tt>__weak</tt> object
1778pointing to <tt>value</tt>. Equivalent to the following code:</p>
1779<pre>id objc_initWeak(id *object, id value) {
1780 *object = nil;
1781 return objc_storeWeak(object, value);
1782}</pre>
1783<p>Returns the value of <tt>object</tt> after the call.</p>
1784<p>Does not need to be atomic with respect to calls
1785to <tt>objc_storeWeak</tt> on <tt>object</tt>.</p>
1786</div> <!-- runtime.objc_initWeak -->
1787
1788<div id="runtime.objc_loadWeak">
1789<h1><tt>id objc_loadWeak(id *object);</tt></h1>
1790<p><i>Precondition:</i> <tt>object</tt> is a valid pointer which
1791either contains a null pointer or has been registered as
1792a <tt>__weak</tt> object.</p>
1793<p>If <tt>object</tt> is registered as a <tt>__weak</tt> object, and
1794the last value stored into <tt>object</tt> has not yet been
1795deallocated or begun deallocation, retains and autoreleases that value
1796and returns it. Otherwise returns null. Equivalent to the following
1797code:</p>
1798<pre>id objc_loadWeak(id *object) {
1799 return objc_autorelease(objc_loadWeakRetained(object));
1800}</pre>
1801<p>Must be atomic with respect to calls to <tt>objc_storeWeak</tt>
1802on <tt>object</tt>.</p>
1803<div class="rationale">Rationale: loading weak references would be
1804inherently prone to race conditions without the retain.</div>
1805</div> <!-- runtime.objc_loadWeak -->
1806
1807<div id="runtime.objc_loadWeakRetained">
1808<h1><tt>id objc_loadWeakRetained(id *object);</tt></h1>
1809<p><i>Precondition:</i> <tt>object</tt> is a valid pointer which
1810either contains a null pointer or has been registered as
1811a <tt>__weak</tt> object.</p>
1812<p>If <tt>object</tt> is registered as a <tt>__weak</tt> object, and
1813the last value stored into <tt>object</tt> has not yet been
1814deallocated or begun deallocation, retains that value and returns it.
1815Otherwise returns null.</p>
1816<p>Must be atomic with respect to calls to <tt>objc_storeWeak</tt>
1817on <tt>object</tt>.</p>
1818</div> <!-- runtime.objc_loadWeakRetained -->
1819
1820<div id="runtime.objc_moveWeak">
1821<h1><tt>void objc_moveWeak(id *dest, id *src);</tt></h1>
1822<p><i>Precondition:</i> <tt>src</tt> is a valid pointer which either
1823contains a null pointer or has been registered as a <tt>__weak</tt>
1824object. <tt>dest</tt> is a valid pointer which has not been
1825registered as a <tt>__weak</tt> object.</p>
1826<p><tt>dest</tt> is initialized to be equivalent to <tt>src</tt>,
1827potentially registering it with the runtime. <tt>src</tt> may then be
1828left in its original state, in which case this call is equivalent
1829to <a href="#runtime.objc_copyWeak"><tt>objc_copyWeak</tt></a>, or it
1830may be left as null.</p>
1831<p>Must be atomic with respect to calls to <tt>objc_storeWeak</tt>
1832on <tt>src</tt>.</p>
1833</div> <!-- runtime.objc_moveWeak -->
1834
John McCall085d09d2011-06-19 10:12:24 +00001835<div id="runtime.objc_release">
1836<h1><tt>void objc_release(id value);</tt></h1>
1837<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a
1838valid object.</p>
1839<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it
1840performs a release operation exactly as if the object had been sent
1841the <tt>release</tt> message.</p>
1842</div> <!-- runtime.objc_release -->
1843
John McCall98a48cf2011-06-19 09:36:02 +00001844<div id="runtime.objc_retain">
1845<h1><tt>id objc_retain(id value);</tt></h1>
1846<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a
1847valid object.</p>
1848<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it
1849performs a retain operation exactly as if the object had been sent
1850the <tt>retain</tt> message.</p>
1851<p>Always returns <tt>value</tt>.</p>
1852</div> <!-- runtime.objc_retain -->
1853
1854<div id="runtime.objc_retainAutorelease">
1855<h1><tt>id objc_retainAutorelease(id value);</tt></h1>
1856<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a
1857valid object.</p>
1858<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it
1859performs a retain operation followed by an autorelease operation.
1860Equivalent to the following code:</p>
1861<pre>id objc_retainAutorelease(id value) {
1862 return objc_autorelease(objc_retain(value));
1863}</pre>
1864<p>Always returns <tt>value</tt>.</p>
1865</div> <!-- runtime.objc_retainAutorelease -->
1866
1867<div id="runtime.objc_retainAutoreleaseReturnValue">
1868<h1><tt>id objc_retainAutoreleaseReturnValue(id value);</tt></h1>
1869<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a
1870valid object.</p>
1871<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it
1872performs a retain operation followed by the operation described in
1873<a href="#runtime.objc_autoreleaseReturnValue"><tt>objc_autoreleaseReturnValue</tt></a>.
1874Equivalent to the following code:</p>
1875<pre>id objc_retainAutoreleaseReturnValue(id value) {
1876 return objc_autoreleaseReturnValue(objc_retain(value));
1877}</pre>
1878<p>Always returns <tt>value</tt>.</p>
1879</div> <!-- runtime.objc_retainAutoreleaseReturnValue -->
1880
1881<div id="runtime.objc_retainAutoreleasedReturnValue">
1882<h1><tt>id objc_retainAutoreleasedReturnValue(id value);</tt></h1>
1883<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a
1884valid object.</p>
1885<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it
1886attempts to accept a hand off of a retain count from a call to
1887<a href="#runtime.objc_autoreleaseReturnValue"><tt>objc_autoreleaseReturnValue</tt></a>
1888on <tt>value</tt> in a recently-called function or something it
1889calls. If that fails, it performs a retain operation exactly
1890like <a href="#runtime.objc_retain"><tt>objc_retain</tt></a>.</p>
1891<p>Always returns <tt>value</tt>.</p>
1892</div> <!-- runtime.objc_retainAutoreleasedReturnValue -->
1893
1894<div id="runtime.objc_retainBlock">
1895<h1><tt>id objc_retainBlock(id value);</tt></h1>
1896<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a
1897valid block object.</p>
1898<p>If <tt>value</tt> is null, this call has no effect. Otherwise, if
1899the block pointed to by <tt>value</tt> is still on the stack, it is
1900copied to the heap and the address of the copy is returned. Otherwise
1901a retain operation is performed on the block exactly as if it had been
1902sent the <tt>retain</tt> message.</p>
1903</div> <!-- runtime.objc_retainBlock -->
1904
John McCall98a48cf2011-06-19 09:36:02 +00001905<div id="runtime.objc_storeStrong">
1906<h1><tt>id objc_storeStrong(id *object, id value);</tt></h1>
1907<p><i>Precondition:</i> <tt>object</tt> is a valid pointer to
1908a <tt>__strong</tt> object which is adequately aligned for a
1909pointer. <tt>value</tt> is null or a pointer to a valid object.</p>
1910<p>Performs the complete sequence for assigning to a <tt>__strong</tt>
1911object of non-block type. Equivalent to the following code:</p>
1912<pre>id objc_storeStrong(id *object, id value) {
1913 value = [value retain];
1914 id oldValue = *object;
1915 *object = value;
1916 [oldValue release];
1917 return value;
1918}</pre>
1919<p>Always returns <tt>value</tt>.</p>
1920</div> <!-- runtime.objc_storeStrong -->
1921
1922<div id="runtime.objc_storeWeak">
1923<h1><tt>id objc_storeWeak(id *object, id value);</tt></h1>
1924<p><i>Precondition:</i> <tt>object</tt> is a valid pointer which
1925either contains a null pointer or has been registered as
1926a <tt>__weak</tt> object. <tt>value</tt> is null or a pointer to a
1927valid object.</p>
1928<p>If <tt>value</tt> is a null pointer or the object to which it
1929points has begun deallocation, <tt>object</tt> is assigned null
1930and unregistered as a <tt>__weak</tt> object. Otherwise,
1931<tt>object</tt> is registered as a <tt>__weak</tt> object or has its
1932registration updated to point to <tt>value</tt>.</p>
1933<p>Returns the value of <tt>object</tt> after the call.</p>
1934</div> <!-- runtime.objc_storeWeak -->
1935
1936</div> <!-- runtime -->
John McCall82467022011-06-15 21:21:53 +00001937</div> <!-- root -->
1938</body>
1939</html>