blob: b5b17b7273a2d973fe9919229efde68396107bcc [file] [log] [blame]
John McCall82467022011-06-15 21:21:53 +00001<html>
2<head>
3<title>Objective-C Automatic Reference Counting (ARC)</title>
4<link type="text/css" rel="stylesheet" href="../menu.css" />
5<link type="text/css" rel="stylesheet" href="../content.css" />
6<style type="text/css">
7/* Collapse the items in the ToC to the left. */
8div#toc ul {
9 padding-left: 0
10}
11
12/* Rationales appear in italic. */
13div.rationale {
14 font-style: italic
15}
16
17div h1 { font-size: 2em; margin: .67em 0 }
18div div h1 { font-size: 1.5em; margin: .75em 0 }
19div div div h1 { font-size: 1.17em; margin: .83em 0 }
20div div div div h1 { margin: 1.12em 0 }
21
22span.term { font-style: italic; font-weight: bold }
23</style>
24
25<script lang="javascript">
26/// A little script to recursively build a table of contents.
27function buildTOC(div, toc, ancestry) {
28 var children = div.childNodes;
29 var len = children.length;
30
31 var childNumber = 0;
32
33 var list = null;
34 for (var i = 0; i < len; ++i) {
35 var child = children[i];
36 if (child.nodeName != "DIV") continue;
37 if (child.getAttribute("class") == "rationale") continue;
38 if (child.id == "toc") continue;
39
40 // Okay, we're actually going to build a list node.
41 if (list === null) list = document.createElement("ul");
42
43 var childAncestry = ancestry + ++childNumber + ".";
44
45 var headerNode = child.childNodes[1];
46 var title = headerNode.innerHTML;
47 headerNode.insertBefore(document.createTextNode(childAncestry + " "),
48 headerNode.firstChild);
49
50 var item = document.createElement("li");
51 item.appendChild(document.createTextNode(childAncestry + " "));
52
53 var anchor = document.createElement("a");
54 anchor.href = "#" + child.id;
55 anchor.innerHTML = title;
56 item.appendChild(anchor);
57
58 buildTOC(child, item, childAncestry);
59
60 list.appendChild(item);
61 }
62 if (list) toc.appendChild(list);
63}
64
65function onLoad() {
66 var toc = document.getElementById("toc");
67 var content = document.getElementById("content");
68 buildTOC(content, toc, "");
69}
70window.onload = onLoad;
71
72</script>
73</head>
74<body>
75
76<!--#include virtual="../menu.html.incl"-->
77
78<div id="content">
79<h1>Automatic Reference Counting</h1>
80
81<div id="toc">
82</div>
83
84<div id="meta">
85<h1>About this document</h1>
86
87<div id="meta.purpose">
88<h1>Purpose</h1>
89
90<p>The first and primary purpose of this document is to serve as a
91complete technical specification of Automatic Reference Counting.
92Given a core Objective-C compiler and runtime, it should be possible
93to write a compiler and runtime which implements these new
94semantics.</p>
95
96<p>The secondary purpose is to act as a rationale for why ARC was
97designed in this way. This should remain tightly focused on the
98technical design and should not stray into marketing speculation.</p>
99
100</div> <!-- meta.purpose -->
101
102<div id="meta.background">
103<h1>Background</h1>
104
105<p>This document assumes a basic familiarity with C.</p>
106
107<p><span class="term">Blocks</span> are a C language extension for
108creating anonymous functions. Users interact with and transfer block
109objects using <span class="term">block pointers</span>, which are
110represented like a normal pointer. A block may capture values from
111local variables; when this occurs, memory must be dynamically
112allocated. The initial allocation is done on the stack, but the
113runtime provides a <tt>Block_copy</tt> function which, given a block
114pointer, either copies the underlying block object to the heap,
115setting its reference count to 1 and returning the new block pointer,
116or (if the block object is already on the heap) increases its
117reference count by 1. The paired function is <tt>Block_release</tt>,
118which decreases the reference count by 1 and destroys the object if
119the count reaches zero and is on the heap.</p>
120
121<p>Objective-C is a set of language extensions, significant enough to
122be considered a different language. It is a strict superset of C.
123The extensions can also be imposed on C++, producing a language called
124Objective-C++. The primary feature is a single-inheritance object
125system; we briefly describe the modern dialect.</p>
126
127<p>Objective-C defines a new type kind, collectively called
128the <span class="term">object pointer types</span>. This kind has two
129notable builtin members, <tt>id</tt> and <tt>Class</tt>; <tt>id</tt>
130is the final supertype of all object pointers. The validity of
131conversions between object pointer types is not checked at runtime.
132Users may define <span class="term">classes</span>; each class is a
133type, and the pointer to that type is an object pointer type. A class
134may have a superclass; its pointer type is a subtype of its
135superclass's pointer type. A class has a set
136of <span class="term">ivars</span>, fields which appear on all
137instances of that class. For every class <i>T</i> there's an
138associated metaclass; it has no fields, its superclass is the
139metaclass of <i>T</i>'s superclass, and its metaclass is a global
140class. Every class has a global object whose class is the
141class's metaclass; metaclasses have no associated type, so pointers to
142this object have type <tt>Class</tt>.</p>
143
144<p>A class declaration (<tt>@interface</tt>) declares a set
145of <span class="term">methods</span>. A method has a return type, a
146list of argument types, and a <span class="term">selector</span>: a
147name like <tt>foo:bar:baz:</tt>, where the number of colons
148corresponds to the number of formal arguments. A method may be an
149instance method, in which case it can be invoked on objects of the
150class, or a class method, in which case it can be invoked on objects
151of the metaclass. A method may be invoked by providing an object
152(called the <span class="term">receiver</span>) and a list of formal
153arguments interspersed with the selector, like so:</p>
154
155<pre>[receiver foo: fooArg bar: barArg baz: bazArg]</pre>
156
157<p>This looks in the dynamic class of the receiver for a method with
158this name, then in that class's superclass, etc., until it finds
159something it can execute. The receiver <q>expression</q> may also be
160the name of a class, in which case the actual receiver is the class
161object for that class, or (within method definitions) it may
162be <tt>super</tt>, in which case the lookup algorithm starts with the
163static superclass instead of the dynamic class. The actual methods
164dynamically found in a class are not those declared in the
165<tt>@interface</tt>, but those defined in a separate
166<tt>@implementation</tt> declaration; however, when compiling a
167call, typechecking is done based on the methods declared in the
168<tt>@interface</tt>.</p>
169
170<p>Method declarations may also be grouped into
171<span class="term">protocols</span>, which are not inherently
172associated with any class, but which classes may claim to follow.
173Object pointer types may be qualified with additional protocols that
174the object is known to support.</p>
175
176<p><span class="term">Class extensions</span> are collections of ivars
177and methods, designed to allow a class's <tt>@interface</tt> to be
178split across multiple files; however, there is still a primary
179implementation file which must see the <tt>@interface</tt>s of all
180class extensions.
181<span class="term">Categories</span> allow methods (but not ivars) to
182be declared <i>post hoc</i> on an arbitrary class; the methods in the
183category's <tt>@implementation</tt> will be dynamically added to that
184class's method tables which the category is loaded at runtime,
185replacing those methods in case of a collision.</p>
186
187<p>In the standard environment, objects are allocated on the heap, and
188their lifetime is manually managed using a reference count. This is
189done using two instance methods which all classes are expected to
190implement: <tt>retain</tt> increases the object's reference count by
1911, whereas <tt>release</tt> decreases it by 1 and calls the instance
192method <tt>dealloc</tt> if the count reaches 0. To simplify certain
193operations, there is also an <span class="term">autorelease
194pool</span>, a thread-local list of objects to call <tt>release</tt>
195on later; an object can be added to this pool by
196calling <tt>autorelease</tt> on it.</p>
197
198<p>Block pointers may be converted to type <tt>id</tt>; block objects
199are laid out in a way that makes them compatible with Objective-C
200objects. There is a builtin class that all block objects are
201considered to be objects of; this class implements <tt>retain</tt> by
202adjusting the reference count, not by calling <tt>Block_copy</tt>.</p>
203
204</div> <!-- meta.background -->
205
206</div> <!-- meta -->
207
208<div id="general">
209<h1>General</h1>
210
211<p>Automatic Reference Counting implements automatic memory management
212for Objective-C objects and blocks, freeing the programmer from the
213need explicitly insert retains and releases. It does not provide a
214cycle collector; users must explicitly manage lifetime instead.</p>
215
216<p>ARC may be explicitly enabled with the compiler
217flag <tt>-fobjc-arc</tt>. It may also be explicitly disabled with the
218compiler flag <tt>-fno-objc-arc</tt>. The last of these two flags
219appearing on the compile line <q>wins</q>.</p>
220
221<p>If ARC is enabled, <tt>__has_feature(objc_arc)</tt> will expand to
2221 in the preprocessor. For more information about <tt>__has_feature</tt>,
223see the <a href="LanguageExtensions.html#__has_feature_extension">language
224extensions</a> document.</p>
225
226</div>
227
228<div id="objects">
229<h1>Retainable object pointers</h1>
230
231<p>This section describes retainable object pointers, their basic
232operations, and the restrictions imposed on their use under ARC. Note
233in particular that it covers the rules for pointer <em>values</em>
234(patterns of bits indicating the location of a pointed-to object), not
235pointer
236<em>objects</em> (locations in memory which store pointer values).
237The rules for objects are covered in the next section.</p>
238
239<p>A <span class="term">retainable object pointer</span>
240(or <q>retainable pointer</q>) is a value of
241a <span class="term">retainable object pointer type</span>
242(<q>retainable type</q>). There are three kinds of retainable object
243pointer types:</p>
244<ul>
245<li>block pointers (formed by applying the caret (<tt>^</tt>)
246declarator sigil to a function type)</li>
247<li>Objective-C object pointers (<tt>id</tt>, <tt>Class</tt>, <tt>NSFoo*</tt>, etc.)</li>
248<li>typedefs marked with <tt>__attribute__((NSObject))</tt></li>
249</ul>
250
251<p>Other pointer types, such as <tt>int*</tt> and <tt>CFStringRef</tt>,
252are not subject to ARC's semantics and restrictions.</p>
253
254<div class="rationale">
255
256<p>Rationale: We are not at liberty to require
257all code to be recompiled with ARC; therefore, ARC must interoperate
258with Objective-C code which manages retains and releases manually. In
259general, there are three requirements in order for a
260compiler-supported reference-count system to provide reliable
261interoperation:</p>
262
263<ul>
264<li>The type system must reliably identify which objects are to be
265managed. An <tt>int*</tt> might be a pointer to a <tt>malloc</tt>'ed
266array, or it might be a interior pointer to such an array, or it might
267point to some field or local variable. In contrast, values of the
268retainable object pointer types are never interior.</li>
269<li>The type system must reliably indicate how to
270manage objects of a type. This usually means that the type must imply
271a procedure for incrementing and decrementing retain counts.
272Supporting single-ownership objects requires a lot more explicit
273mediation in the language.</li>
274<li>There must be reliable conventions for whether and
275when <q>ownership</q> is passed between caller and callee, for both
276arguments and return values. Objective-C methods follow such a
277convention very reliably, at least for system libraries on Mac OS X,
278and functions always pass objects at +0. The C-based APIs for Core
279Foundation objects, on the other hand, have much more varied transfer
280semantics.</li>
281</ul>
282</div> <!-- rationale -->
283
284<p>The use of <tt>__attribute__((NSObject))</tt> typedefs is not
285recommended. If it's absolutely necessary to use this attribute, be
286very explicit about using the typedef, and do not assume that it will
287be preserved by language features like <tt>__typeof</tt> and C++
288template argument substitution.</p>
289
290<div class="rationale"><p>Rationale: any compiler operation which
291incidentally strips type <q>sugar</q> from a type will yield a type
292without the attribute, which may result in unexpected
293behavior.</p></div>
294
295<div id="objects.retains">
296<h1>Retain count semantics</h1>
297
298<p>A retainable object pointer is either a <span class="term">null
299pointer</span> or a pointer to a valid object. Furthermore, if it has
300block pointer type and is not <tt>null</tt> then it must actually be a
301pointer to a block object, and if it has <tt>Class</tt> type (possibly
302protocol-qualified) then it must actually be a pointer to a class
303object. Otherwise ARC does not enforce the Objective-C type system as
304long as the implementing methods follow the signature of the static
305type. It is undefined behavior if ARC is exposed to an invalid
306pointer.</p>
307
308<p>For ARC's purposes, a valid object is one with <q>well-behaved</q>
309retaining operations. Specifically, the object must be laid out such
310that the Objective-C message send machinery can successfully send it
311the following messages:</p>
312
313<ul>
314<li><tt>retain</tt>, taking no arguments and returning a pointer to
315the object.</li>
316<li><tt>release</tt>, taking no arguments and returning <tt>void</tt>.</li>
317<li><tt>autorelease</tt>, taking no arguments and returning a pointer
318to the object.</li>
319</ul>
320
321<p>The behavior of these methods is constrained in the following ways.
322The term <span class="term">high-level semantics</span> is an
323intentionally vague term; the intent is that programmers must
324implement these methods in a way such that the compiler, modifying
325code in ways it deems safe according to these constraints, will not
326violate their requirements. For example, if the user puts logging
327statements in <tt>retain</tt>, they should not be surprised if those
328statements are executed more or less often depending on optimization
329settings. These constraints are not exhaustive of the optimization
330opportunities: values held in local variables are subject to
331additional restrictions, described later in this document.</p>
332
333<p>It is undefined behavior if a computation history featuring a send
334of <tt>retain</tt> followed by a send of <tt>release</tt> to the same
335object, with no intervening <tt>release</tt> on that object, is not
336equivalent under the high-level semantics to a computation
337history in which these sends are removed. Note that this implies that
338these methods may not raise exceptions.</p>
339
340<p>It is undefined behavior if a computation history features any use
341whatsoever of an object following the completion of a send
342of <tt>release</tt> that is not preceded by a send of <tt>retain</tt>
343to the same object.</p>
344
345<p>The behavior of <tt>autorelease</tt> must be equivalent to sending
346<tt>release</tt> when one of the autorelease pools currently in scope
347is popped. It may not throw an exception.</p>
348
349<p>When the semantics call for performing one of these operations on a
350retainable object pointer, if that pointer is <tt>null</tt> then the
351effect is a no-op.</p>
352
353<p>All of the semantics described in this document are subject to
354additional <a href="#optimization">optimization rules</a> which permit
355the removal or optimization of operations based on local knowledge of
356data flow. The semantics describe the high-level behaviors that the
357compiler implements, not an exact sequence of operations that a
358program will be compiled into.</p>
359
360</div> <!-- objects.retains -->
361
362<div id="objects.operands">
363<h1>Retainable object pointers as operands and arguments</h1>
364
365<p>In general, ARC does not perform retain or release operations when
366simply using a retainable object pointer as an operand within an
367expression. This includes:</p>
368<ul>
369<li>loading a retainable pointer from an object with non-weak
370<a href="#ownership">ownership</a>,</li>
371<li>passing a retainable pointer as an argument to a function or
372method, and</li>
373<li>receiving a retainable pointer as the result of a function or
374method call.</li>
375</ul>
376
377<div class="rationale"><p>Rationale: while this might seem
378uncontroversial, it is actually unsafe when multiple expressions are
379evaluated in <q>parallel</q>, as with binary operators and calls,
380because (for example) one expression might load from an object while
381another writes to it. However, C and C++ already call this undefined
382behavior because the evaluations are unsequenced, and ARC simply
383exploits that here to avoid needing to retain arguments across a large
384number of calls.</p></div>
385
386<p>The remainder of this section describes exceptions to these rules,
387how those exceptions are detected, and what those exceptions imply
388semantically.</p>
389
390<div id="objects.operands.consumed">
391<h1>Consumed parameters</h1>
392
393<p>A function or method parameter of retainable object pointer type
394may be marked as <span class="term">consumed</span>, signifying that
395the callee expects to take ownership of a +1 retain count. This is
396done by adding the <tt>ns_consumed</tt> attribute to the parameter
397declaration, like so:</p>
398
399<pre>void foo(__attribute((ns_consumed)) id x);
400- (void) foo: (id) __attribute((ns_consumed)) x;</pre>
401
402<p>This attribute is part of the type of the function or method, not
403the type of the parameter. It controls only how the argument is
404passed and received.</p>
405
406<p>When passing such an argument, ARC retains the argument prior to
407making the call.</p>
408
409<p>When receiving such an argument, ARC releases the argument at the
410end of the function, subject to the usual optimizations for local
411values.</p>
412
413<div class="rationale"><p>Rationale: this formalizes direct transfers
414of ownership from a caller to a callee. The most common scenario here
415is passing the <tt>self</tt> parameter to <tt>init</tt>, but it is
416useful to generalize. Typically, local optimization will remove any
417extra retains and releases: on the caller side the retain will be
418merged with a +1 source, and on the callee side the release will be
419rolled into the initialization of the parameter.</p></div>
420
421<p>The implicit <tt>self</tt> parameter of a method may be marked as
422consumed by adding <tt>__attribute__((ns_consumes_self))</tt> to the
423method declaration. Methods in
424the <tt>init</tt> <a href="#family">family</a> are implicitly
425marked <tt>__attribute__((ns_consumes_self))</tt>.</p>
426
427<p>It is undefined behavior if an Objective-C message send of a method
428with <tt>ns_consumed</tt> parameters (other than self) is made to a
429null pointer.</p>
430
431<div class="rationale"><p>Rationale: in fact, it's probably a
432guaranteed leak.</p></div>
433
434</div>
435
436<div id="objects.operands.retained-returns">
437<h1>Retained return values</h1>
438
439<p>A function or method which returns a retainable object pointer type
440may be marked as returning a retained value, signifying that the
441caller expects to take ownership of a +1 retain count. This is done
442by adding the <tt>ns_returns_retained</tt> attribute to the function or
443method declaration, like so:</p>
444
445<pre>id foo(void) __attribute((ns_returns_retained));
446- (id) foo __attribute((ns_returns_retained));</pre>
447
448<p>This attribute is part of the type of the function or method.</p>
449
450<p>When returning from such a function or method, ARC retains the
451value at the point of evaluation of the return statement, before
452leaving all local scopes.</p>
453
454<p>When receiving a return result from such a function or method, ARC
455releases the value at the end of the full-expression it is contained
456within, subject to the usual optimizations for local values.</p>
457
458<div class="rationale"><p>Rationale: this formalizes direct transfers of
459ownership from a callee to a caller. The most common scenario this
460models is the retained return from <tt>init</tt>, <tt>alloc</tt>,
461<tt>new</tt>, and <tt>copy</tt> methods, but there are other cases in
462the frameworks. After optimization there are typically no extra
463retains and releases required.</p></div>
464
465<p>Methods in
466the <tt>alloc</tt>, <tt>copy</tt>, <tt>init</tt>, <tt>mutableCopy</tt>,
467and <tt>new</tt> <a href="#family">families</a> are implicitly marked
468<tt>__attribute__((ns_returns_retained))</tt>. This may be suppressed
469by explicitly marking the
470method <tt>__attribute__((ns_returns_not_retained))</tt>.</p>
471</div>
472
473<div id="objects.operands.other-returns">
474<h1>Unretained return values</h1>
475
476<p>A method or function which returns a retainable object type but
477does not return a retained value must ensure that the object is
478still valid across the return boundary.</p>
479
480<p>When returning from such a function or method, ARC retains the
481value at the point of evaluation of the return statement, then leaves
482all local scopes, and then balances out the retain while ensuring that
483the value lives across the call boundary. In the worst case, this may
484involve an <tt>autorelease</tt>, but callers must not assume that the
485value is actually in the autorelease pool.</p>
486
487<p>ARC performs no extra mandatory work on the caller side, although
488it may elect to do something to shorten the lifetime of the returned
489value.</p>
490
491<div class="rationale"><p>Rationale: it is common in non-ARC code to not
492return an autoreleased value; therefore the convention does not force
493either path. It is convenient to not be required to do unnecessary
494retains and autoreleases; this permits optimizations such as eliding
495retain/autoreleases when it can be shown that the original pointer
496will still be valid at the point of return.</p></div>
497
498<p>A method or function may be marked
499with <tt>__attribute__((ns_returns_autoreleased))</tt> to indicate
500that it returns a pointer which is guaranteed to be valid at least as
501long as the innermost autorelease pool. There are no additional
502semantics enforced in the definition of such a method; it merely
503enables optimizations in callers.</p>
504</div>
505
506<div id="objects.operands.casts">
507<h1>Bridged casts</h1>
508
509<p>A <span class="term">bridged cast</span> is a C-style cast
510annotated with one of three keywords:</p>
511
512<ul>
513<li><tt>(__bridge T) op</tt> casts the operand to the destination
514type <tt>T</tt>. If <tt>T</tt> is a retainable object pointer type,
515then <tt>op</tt> must have a non-retainable pointer type.
516If <tt>T</tt> is a non-retainable pointer type, then <tt>op</tt> must
517have a retainable object pointer type. Otherwise the cast is
518ill-formed. There is no transfer of ownership, and ARC inserts
519no retain operations.</li>
520
521<li><tt>(__bridge_retained T) op</tt> casts the operand, which must
522have retainable object pointer type, to the destination type, which
523must be a non-retainable pointer type. ARC retains the value, subject
524to the usual optimizations on local values, and the recipient is
525responsible for balancing that +1.</li>
526
527<li><tt>(__bridge_transfer T) op</tt> casts the operand, which must
528have non-retainable pointer type, to the destination type, which must
529be a retainable object pointer type. ARC will release the value at
530the end of the enclosing full-expression, subject to the usual
531optimizations on local values.</li>
532</ul>
533
534<p>These casts are required in order to transfer objects in and out of
535ARC control; see the rationale in the section
536on <a href="#objects.restrictions.conversion">conversion of retainable
537object pointers</a>.</p>
538
539<p>Using a <tt>__bridge_retained</tt> or <tt>__bridge_transfer</tt>
540cast purely to convince ARC to emit an unbalanced retain or release,
541respectively, is poor form.</p>
542
543</div>
544
545</div>
546
547<div id="objects.restrictions">
548<h1>Restrictions</h1>
549
550<div id="objects.restrictions.conversion">
551<h1>Conversion of retainable object pointers</h1>
552
553<p>In general, a program which attempts to implicitly or explicitly
554convert a value of retainable object pointer type to any
555non-retainable type, or vice-versa, is ill-formed. For example, an
556Objective-C object pointer shall not be converted to <tt>intptr_t</tt>
557or <tt>void*</tt>. The <a href="#objects.operands.casts">bridged
558casts</a> may be used to perform these conversions where
559necessary.</p>
560
561<div class="rationale"><p>Rationale: we cannot ensure the correct
562management of the lifetime of objects if they may be freely passed
563around as unmanaged types. The bridged casts are provided so that the
564programmer may explicitly describe whether the cast transfers control
565into or out of ARC.</p></div>
566</div>
567
568<p>An unbridged cast to a retainable object pointer type of the return
569value of a Objective-C message send which yields a non-retainable
570pointer is treated as a <tt>__bridge_transfer</tt> cast
571if:</p>
572
573<ul>
574<li>the method has the <tt>cf_returns_retained</tt> attribute, or if
575not that,</li>
576<li>the method does not have the <tt>cf_returns_not_retained</tt>
577attribute and</li>
578<li>the method's <a href="#family">selector family</a> would imply
579the <tt>ns_returns_retained</tt> attribute on a method which returned
580a retainable object pointer type.</li>
581</ul>
582
583<p>Otherwise the cast is treated as a <tt>__bridge</tt> cast.</p>
584
585</div>
586
587</div>
588
589<div id="ownership">
590<h1>Ownership qualification</h1>
591
592<p>This section describes the behavior of <em>objects</em> of
593retainable object pointer type; that is, locations in memory which
594store retainable object pointers.</p>
595
596<p>A type is a <span class="term">retainable object owner type</span>
597if it is a retainable object pointer type or an array type whose
598element type is a retainable object owner type.</p>
599
600<p>An <span class="term">ownership qualifier</span> is a type
601qualifier which applies only to retainable object owner types. A
602program is ill-formed if it attempts to apply an ownership qualifier
603to a type which is already ownership-qualified, even if it is the same
604qualifier. An array type is ownership-qualified according to its
605element type, and adding an ownership qualifier to an array type so
606qualifies its element type.</p>
607
608<p>Except as described under
609the <a href="#ownership.inference">inference rules</a>, a program is
610ill-formed if it attempts to form a pointer or reference type to a
611retainable object owner type which lacks an ownership qualifier.</p>
612
613<div class="rationale"><p>Rationale: these rules, together with the
614inference rules, ensure that all objects and lvalues of retainable
615object pointer type have an ownership qualifier.</p></div>
616
617<p>There are four ownership qualifiers:</p>
618
619<ul>
620<li><tt>__autoreleasing</tt></li>
621<li><tt>__strong</tt></li>
622<li><tt>__unsafe_unretained</tt></li>
623<li><tt>__weak</tt></li>
624</ul>
625
626<p>A type is <span class="term">nontrivially ownership-qualified</span>
627if it is qualified with <tt>__autoreleasing</tt>, <tt>__strong</tt>, or
628<tt>__weak</tt>.</p>
629
630<div id="ownership.spelling">
631<h1>Spelling</h1>
632
633<p>The names of the ownership qualifiers are reserved for the
634implementation. A program may not assume that they are or are not
635implemented with macros, or what those macros expand to.</p>
636
637<p>An ownership qualifier may be written anywhere that any other type
638qualifier may be written.</p>
639
640<p>If an ownership qualifier appears in
641the <i>declaration-specifiers</i>, the following rules apply:</p>
642
643<ul>
644<li>if the type specifier is a retainable object owner type, the
645qualifier applies to that type;</li>
646<li>if the outermost non-array part of the declarator is a pointer or
647block pointer, the qualifier applies to that type;</li>
648<li>otherwise the program is ill-formed.</li>
649</ul>
650
651<p>If an ownership qualifier appears on the declarator name, or on the
652declared object, it is applied to outermost pointer or block-pointer
653type.</p>
654
655<p>If an ownership qualifier appears anywhere else in a declarator, it
656applies to the type there.</p>
657
658</div> <!-- ownership.spelling -->
659
660<div id="ownership.semantics">
661<h1>Semantics</h1>
662
663<p>There are five <span class="term">managed operations</span> which
664may be performed on an object of retainable object pointer type. Each
665qualifier specifies different semantics for each of these operations.
666It is still undefined behavior to access an object outside of its
667lifetime.</p>
668
669<p>A load or store with <q>primitive semantics</q> has the same
670semantics as the respective operation would have on an <tt>void*</tt>
671lvalue with the same alignment and non-ownership qualification.</p>
672
673<p><span class="term">Reading</span> occurs when performing a
674lvalue-to-rvalue conversion on an object lvalue.
675
676<ul>
677<li>For <tt>__weak</tt> objects, the current pointee is retained and
678then released at the end of the current full-expression. This must
679execute atomically with respect to assignments and to the final
680release of the pointee.</li>
681<li>For all other objects, the lvalue is loaded with primitive
682semantics.</li>
683</ul>
684</p>
685
686<p><span class="term">Assignment</span> occurs when evaluating
687an assignment operator. The semantics vary based on the qualification:
688<ul>
689<li>For <tt>__strong</tt> objects, the new pointee is first retained;
690second, the lvalue is loaded with primitive semantics; third, the new
691pointee is stored into the lvalue with primitive semantics; and
692finally, the old pointee is released. This is not performed
693atomically; external synchronization must be used to make this safe in
694the face of concurrent loads and stores.</li>
695<li>For <tt>__weak</tt> objects, the lvalue is updated to point to the
696new pointee, unless that object is currently undergoing deallocation,
697in which case it the lvalue is updated to a null pointer. This must
698execute atomically with respect to other assignments to the object, to
699reads from the object, and to the final release of the new pointed-to
700value.</li>
701<li>For <tt>__unsafe_unretained</tt> objects, the new pointee is
702stored into the lvalue using primitive semantics.</li>
703<li>For <tt>__autoreleasing</tt> objects, the new pointee is retained,
704autoreleased, and stored into the lvalue using primitive semantics.</li>
705</ul>
706</p>
707
708<p><span class="term">Initialization</span> occurs when an object's
709lifetime begins, which depends on its storage duration.
710Initialization proceeds in two stages:
711<ol>
712<li>First, a null pointer is stored into the lvalue using primitive
713semantics. This step is skipped if the object
714is <tt>__unsafe_unretained</tt>.</li>
715<li>Second, if the object has an initializer, that expression is
716evaluated and then assigned into the object using the usual assignment
717semantics.</li>
718</ol>
719</p>
720
721<p><span class="term">Destruction</span> occurs when an object's
722lifetime ends. In all cases it is semantically equivalent to
723assigning a null pointer to the object, with the proviso that of
724course the object cannot be legally read after the object's lifetime
725ends.</p>
726
727<p><span class="term">Moving</span> occurs in specific situations
728where an lvalue is <q>moved from</q>, meaning that its current pointee
729will be used but the object may be left in a different (but still
730valid) state. This arises with <tt>__block</tt> variables and rvalue
731references in C++. For <tt>__strong</tt> lvalues, moving is equivalent
732to loading the lvalue with primitive semantics, writing a null pointer
733to it with primitive semantics, and then releasing the result of the
734load at the end of the current full-expression. For all other
735lvalues, moving is equivalent to reading the object.</p>
736
737</div> <!-- ownership.semantics -->
738
739<div id="ownership.restrictions">
740<h1>Restrictions</h1>
741
742<div id="ownership.restrictions.autoreleasing">
743<h1>Storage duration of<tt> __autoreleasing</tt> objects</h1>
744
745<p>A program is ill-formed if it declares an <tt>__autoreleasing</tt>
746object of non-automatic storage duration.</p>
747
748<div class="rationale"><p>Rationale: autorelease pools are tied to the
749current thread and scope by their nature. While it is possible to
750have temporary objects whose instance variables are filled with
751autoreleased objects, there is no way that ARC can provide any sort of
752safety guarantee there.</p></div>
753
754<p>It is undefined behavior if a non-null pointer is assigned to
755an <tt>__autoreleasing</tt> object while an autorelease pool is in
756scope and then that object is read after the autorelease pool's scope
757is left.</p>
758
759</div>
760
761<div id="ownership.restrictions.conversion.indirect">
762<h1>Conversion of pointers to ownership-qualified types</h1>
763
764<p>A program is ill-formed if an expression of type <tt>T*</tt> is
765converted, explicitly or implicitly, to the type <tt>U*</tt>,
766where <tt>T</tt> and <tt>U</tt> have different ownership
767qualification, unless:
768<ul>
769<li><tt>T</tt> is qualified with <tt>__strong</tt>,
770 <tt>__autoreleasing</tt>, or <tt>__unsafe_unretained</tt>, and
771 <tt>U</tt> is qualified with both <tt>const</tt> and
772 <tt>__unsafe_unretained</tt>; or</li>
773<li>either <tt>T</tt> or <tt>U</tt> is <tt>cv void</tt>, where
774<tt>cv</tt> is an optional sequence of non-ownership qualifiers; or</li>
775<li>the conversion is requested with a <tt>reinterpret_cast</tt> in
776 Objective-C++; or</li>
777<li>the conversion is a
778well-formed <a href="#ownership.restrictions.pass_by_writeback">pass-by-writeback</a>.</li>
779</ul>
780</p>
781
782<p>The analogous rule applies to <tt>T&</tt> and <tt>U&</tt> in
783Objective-C++.</p>
784
785<div class="rationale"><p>Rationale: these rules provide a reasonable
786level of type-safety for indirect pointers, as long as the underlying
787memory is not deallocated. The conversion to <tt>const
788__unsafe_unretained</tt> is permitted because the semantics of reads
789are equivalent across all these ownership semantics, and that's a very
790useful and common pattern. The interconversion with <tt>void*</tt> is
791useful for allocating memory or otherwise escaping the type system,
792but use it carefully. <tt>reinterpret_cast</tt> is considered to be
793an obvious enough sign of taking responsibility for any
794problems.</p></div>
795
796<p>It is undefined behavior to access an ownership-qualified object
797through an lvalue of a differently-qualified type, except that any
798non-<tt>__weak</tt> object may be read through
799an <tt>__unsafe_unretained</tt> lvalue.</p>
800
801<p>It is undefined behavior if a managed operation is performed on
802a <tt>__strong</tt> or <tt>__weak</tt> object without a guarantee that
803it contains a primitive zero bit-pattern, or if the storage for such
804an object is freed or reused without the object being first assigned a
805null pointer.</p>
806
807<div class="rationale"><p>Rationale: ARC cannot differentiate between
808an assignment operator which is intended to <q>initialize</q> dynamic
809memory and one which is intended to potentially replace a value.
810Therefore the object's pointer must be valid before letting ARC at it.
811Similarly, C and Objective-C do not provide any language hooks for
812destroying objects held in dynamic memory, so it is the programmer's
813responsibility to avoid leaks (<tt>__strong</tt> objects) and
814consistency errors (<tt>__weak</tt> objects).</p>
815
816<p>These requirements are followed automatically in Objective-C++ when
817creating objects of retainable object owner type with <tt>new</tt>
818or <tt>new[]</tt> and destroying them with <tt>delete</tt>,
819<tt>delete[]</tt>, or a pseudo-destructor expression. Note that
820arrays of nontrivially-ownership-qualified type are not ABI compatible
821with non-ARC code because the element type is non-POD: such arrays
822that are <tt>new[]</tt>'d in ARC translation units cannot
823be <tt>delete[]</tt>'d in non-ARC translation units and
824vice-versa.</p></div>
825
826</div>
827
828<div id="ownership.restrictions.pass_by_writeback">
829<h1>Passing to an out parameter by writeback</h1>
830
831<p>If the argument passed to a parameter of type
832<tt>T __autoreleasing *</tt> has type <tt>U oq *</tt>,
833where <tt>oq</tt> is an ownership qualifier, then the argument is a
834candidate for <span class="term">pass-by-writeback</span> if:</p>
835
836<ul>
837<li><tt>oq</tt> is <tt>__strong</tt> or <tt>__weak</tt>, and
838<li>it would be legal to initialize a <tt>T __strong *</tt> with
839a <tt>U __strong *</tt>.</li>
840</ul>
841
842<p>For purposes of overload resolution, an implicit conversion
843sequence requiring a pass-by-writeback is always worse than an
844implicit conversion sequence not requiring a pass-by-writeback.</p>
845
846<p>The pass-by-writeback is ill-formed if the argument expression does
847not have a legal form:</p>
848
849<ul>
850<li><tt>&var</tt>, where <tt>var</tt> is a scalar variable of
851automatic storage duration with retainable object pointer type</li>
852<li>a conditional expression where the second and third operands are
853both legal forms</li>
854<li>a cast whose operand is a legal form</li>
855<li>a null pointer constant</li>
856</ul>
857
858<div class="rationale"><p>Rationale: the restriction in the form of
859the argument serves two purposes. First, it makes it impossible to
860pass the address of an array to the argument, which serves to protect
861against an otherwise serious risk of mis-inferring an <q>array</q>
862argument as an out-parameter. Second, it makes it much less likely
863that the user will see confusing aliasing problems due to the
864implementation, below, where their store to the writeback temporary is
865not immediately seen in the original argument variable.</p></div>
866
867<p>A pass-by-writeback is evaluated as follows:
868<ol>
869<li>The argument is evaluated to yield a pointer <tt>p</tt> of
870 type <tt>U oq *</tt>.</li>
871<li>If <tt>p</tt> is a null pointer, then a null pointer is passed as
872 the argument, and no further work is required for the pass-by-writeback.</li>
873<li>Otherwise, a temporary of type <tt>T __autoreleasing</tt> is
874 created and initialized to a null pointer.</li>
875<li>If the argument is not an Objective-C method parameter marked
876 <tt>out</tt>, then <tt>*p</tt> is read, and the result is written
877 into the temporary with primitive semantics.</li>
878<li>The address of the temporary is passed as the argument to the
879 actual call.</li>
880<li>After the call completes, the temporary is loaded with primitive
881 semantics, and that value is assigned into <tt>*p</tt>.</li>
882</ol></p>
883
884<div class="rationale"><p>Rationale: this is all admittedly
885convoluted. In an ideal world, we would see that a local variable is
886being passed to an out-parameter and retroactively modify its type to
887be <tt>__autoreleasing</tt> rather than <tt>__strong</tt>. This would
888be remarkably difficult and not always well-founded under the C type
889system. However, it was judged unacceptably invasive to require
890programmers to write <tt>__autoreleasing</tt> on all the variables
891they intend to use for out-parameters. This was the least bad
892solution.</p></div>
893
894</div>
895
896<div id="ownership.restrictions.records">
897<h1>Ownership-qualified fields of structs and unions</h1>
898
899<p>A program is ill-formed if it declares a member of a C struct or
900union to have a nontrivially ownership-qualified type.</p>
901
902<div class="rationale"><p>Rationale: the resulting type would be
903non-POD in the C++ sense, but C does not give us very good language
904tools for managing the lifetime of aggregates, so it is more
905convenient to simply forbid them. It is still possible to manage this
906with a <tt>void*</tt> or an <tt>__unsafe_unretained</tt>
907object.</p></div>
908
909<p>This restriction does not apply in Objective-C++. However,
910nontrivally ownership-qualified types are considered non-POD: in C++0x
911terms, they are not trivially default constructible, copy
912constructible, move constructible, copy assignable, move assignable,
913or destructible. It is a violation of C++ One Definition Rule to use
914a class outside of ARC that, under ARC, would have an
915ownership-qualified member.</p>
916
917<div class="rationale"><p>Rationale: unlike in C, we can express all
918the necessary ARC semantics for ownership-qualified subobjects as
919suboperations of the (default) special member functions for the class.
920These functions then become non-trivial. This has the non-obvious
921repercussion that the class will have a non-trivial copy constructor
922and non-trivial destructor; if it wouldn't outside of ARC, this means
923that objects of the type will be passed and returned in an
924ABI-incompatible manner.</p></div>
925
926</div>
927
928</div>
929
930<div id="ownership.inference">
931<h1>Ownership inference</h1>
932
933<div id="ownership.inference.variables">
934<h1>Objects</h1>
935
936<p>If an object is declared with retainable object owner type, but
937without an explicit ownership qualifier, its type is implicitly
938adjusted to have <tt>__strong</tt> qualification.</p>
939
940<p>As a special case, if the object's base type is <tt>Class</tt>
941(possibly protocol-qualified), the type is adjusted to
942have <tt>__unsafe_unretained</tt> qualification instead.</p>
943
944</div>
945
946<div id="ownership.inference.indirect_parameters">
947<h1>Indirect parameters</h1>
948
949<p>If a function or method parameter has type <tt>T*</tt>, where
950<tt>T</tt> is an ownership-unqualified retainable object pointer type,
951then:</p>
952
953<ul>
954<li>if <tt>T</tt> is <tt>const</tt>-qualified or <tt>Class</tt>, then
955it is implicitly qualified with <tt>__unsafe_unretained</tt>;</li>
956<li>otherwise, it is implicitly qualified
957with <tt>__autoreleasing</tt>.</li>
958</ul>
959</p>
960
961<div class="rationale"><p>Rationale: <tt>__autoreleasing</tt> exists
962mostly for this case, the Cocoa convention for out-parameters. Since
963a pointer to <tt>const</tt> is obviously not an out-parameter, we
964instead use a type more useful for passing arrays. If the user
965instead intends to pass in a <em>mutable</em> array, inferring
966<tt>__autoreleasing</tt> is the wrong thing to do; this directs some
967of the caution in the following rules about writeback.</p></div>
968
969<p>Such a type written anywhere else would be ill-formed by the
970general rule requiring ownership qualifiers.</p>
971
972<p>This rule does not apply in Objective-C++ if a parameter's type is
973dependent in a template pattern and is only <em>instantiated</em> to
974a type which would be a pointer to an unqualified retainable object
975pointer type. Such code is still ill-formed.</p>
976
977<div class="rationale"><p>Rationale: the convention is very unlikely
978to be intentional in template code.</p></div>
979
980</div> <!-- ownership.inference.indirect_parameters -->
Douglas Gregore559ca12011-06-17 22:11:49 +0000981
982<div id="ownership.inference.template_arguments">
983<h1>Template arguments</h1>
984
985<p>If a template argument for a template type parameter is an
986retainable object owner type that does not have an explicit ownership
987qualifier, it is adjusted to have <tt>__strong</tt>
Douglas Gregor54fb28a2011-06-17 22:19:27 +0000988qualification. This adjustment occurs regardless of whether the
Douglas Gregore559ca12011-06-17 22:11:49 +0000989template argument was deduced or explicitly specified. </p>
990
991<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>
992
993</div> <!-- ownership.inference.template_arguments -->
John McCall82467022011-06-15 21:21:53 +0000994</div> <!-- ownership.inference -->
995</div> <!-- ownership -->
996
Douglas Gregore559ca12011-06-17 22:11:49 +0000997
John McCall82467022011-06-15 21:21:53 +0000998<div id="family">
999<h1>Method families</h1>
1000
1001<p>An Objective-C method may fall into a <span class="term">method
1002family</span>, which is a conventional set of behaviors ascribed to it
1003by the Cocoa conventions.</p>
1004
1005<p>A method is in a certain method family if:
1006<ul>
1007<li>it has a <tt>objc_method_family</tt> attribute placing it in that
1008 family; or if not that,</li>
1009<li>it does not have an <tt>objc_method_family</tt> attribute placing
1010 it in a different or no family, and</li>
1011<li>its selector falls into the corresponding selector family, and</li>
1012<li>its signature obeys the added restrictions of the method family.</li>
1013</ul></p>
1014
1015<p>A selector is in a certain selector family if, ignoring any leading
1016underscores, the first component of the selector either consists
1017entirely of the name of the method family or it begins with that name
1018followed by a character other than a lowercase letter. For
1019example, <tt>_perform:with:</tt> and <tt>performWith:</tt> would fall
1020into the <tt>perform</tt> family (if we recognized one),
1021but <tt>performing:with</tt> would not.</p>
1022
1023<p>The families and their added restrictions are:</p>
1024
1025<ul>
1026<li><tt>alloc</tt> methods must return a retainable object pointer type.</li>
1027<li><tt>copy</tt> methods must return a retainable object pointer type.</li>
1028<li><tt>mutableCopy</tt> methods must return a retainable object pointer type.</li>
1029<li><tt>new</tt> methods must return a retainable object pointer type.</li>
1030<li><tt>init</tt> methods must be instance methods and must return an
1031Objective-C pointer type. Additionally, a program is ill-formed if it
1032declares or contains a call to an <tt>init</tt> method whose return
1033type is neither <tt>id</tt> nor a pointer to a super-class or
1034sub-class of either the declaring class, if the method was declared on
1035a class, or the static receiver type of the call, if it was declared
1036on a protocol.</p>
1037
1038<div class="rationale"><p>Rationale: there are a fair number of existing
1039methods with <tt>init</tt>-like selectors which nonetheless don't
1040follow the <tt>init</tt> conventions. Typically these are either
1041accidental naming collisions or helper methods called during
1042initialization. Because of the peculiar retain/release behavior
1043of <tt>init</tt> methods, it's very important not to treat these
1044methods as <tt>init</tt> methods if they aren't meant to be. It was
1045felt that implicitly defining these methods out of the family based on
1046the exact relationship between the return type and the declaring class
1047would much too subtle and fragile. Therefore we identify a small
1048number of legitimate-seeming return types and call everything else an
1049error. This serves the secondary purpose of encouraging programmers
1050not to accidentally give methods names in the <tt>init</tt> family.</p></div>
1051</li>
1052</ul>
1053
1054<p>A program is ill-formed if a method's declarations,
1055implementations, and overrides do not all have the same method
1056family.</p>
1057
1058<div id="family.attribute">
1059<h1>Explicit method family control</h1>
1060
1061<p>A method may be annotated with the <tt>objc_method_family</tt>
1062attribute to precisely control which method family it belongs to. If
1063a method in an <tt>@implementation</tt> does not have this attribute,
1064but there is a method declared in the corresponding <tt>@interface</tt>
1065that does, then the attribute is copied to the declaration in the
1066<tt>@implementation</tt>. The attribute is available outside of ARC,
1067and may be tested for with the preprocessor query
1068<tt>__has_attribute(objc_method_family)</tt>.</p>
1069
1070<p>The attribute is spelled
1071<tt>__attribute__((objc_method_family(<i>family</i>)))</tt>.
1072If <i>family</i> is <tt>none</tt>, the method has no family, even if
1073it would otherwise be considered to have one based on its selector and
1074type. Otherwise, <i>family</i> must be one
1075of <tt>alloc</tt>, <tt>copy</tt>, <tt>init</tt>,
1076<tt>mutableCopy</tt>, or <tt>new</tt>, in which case the method is
1077considered to belong to the corresponding family regardless of its
1078selector. It is an error if a method that is explicitly added to a
1079family in this way does not meet the requirements of the family other
1080than the selector naming convention.</p>
1081
1082<div class="rationale"><p>Rationale: the rules codified in this document
1083describe the standard conventions of Objective-C. However, as these
1084conventions have not heretofore been enforced by an unforgiving
1085mechanical system, they are only imperfectly kept, especially as they
1086haven't always even been precisely defined. While it is possible to
1087define low-level ownership semantics with attributes like
1088<tt>ns_returns_retained</tt>, this attribute allows the user to
1089communicate semantic intent, which of use both to ARC (which, e.g.,
1090treats calls to <tt>init</tt> specially) and the static analyzer.</p></div>
1091</div>
1092
1093<div id="family.semantics">
1094<h1>Semantics of method families</h1>
1095
1096<p>A method's membership in a method family may imply non-standard
1097semantics for its parameters and return type.</p>
1098
1099<p>Methods in the <tt>alloc</tt>, <tt>copy</tt>, <tt>mutableCopy</tt>,
1100and <tt>new</tt> families &mdash; that is, methods in all the
1101currently-defined families except <tt>init</tt> &mdash; transfer
1102ownership of a +1 retain count on their return value to the calling
1103function, as if they were implicitly annotated with
1104the <tt>ns_returns_retained</tt> attribute. However, this is not true
1105if the method has either of the <tt>ns_returns_autoreleased</tt> or
1106<tt>ns_returns_not_retained</tt> attributes.</p>
1107
1108<div id="family.semantics.init">
1109<h1>Semantics of <tt>init</tt></h1>
1110
1111<p>Methods in the <tt>init</tt> family must be transferred ownership
1112of a +1 retain count on their <tt>self</tt> parameter, exactly as if
1113the method had the <tt>ns_consumes_self</tt> attribute, and must
1114transfer ownership of a +1 retain count on their return value, exactly
1115as if they method had the <tt>ns_returns_retained</tt> attribute.
1116Neither of these may be altered through attributes.</p>
1117
1118<p>A call to an <tt>init</tt> method with a receiver that is either
1119<tt>self</tt> (possibly parenthesized or casted) or <tt>super</tt> is
1120called a <span class="term">delegate init call</span>. It is an error
1121for a delegate init call to be made except from an <tt>init</tt>
1122method, and excluding blocks within such methods.</p>
1123
1124<p>The variable <tt>self</tt> is mutable in an <tt>init</tt> method
1125and is implicitly qualified as <tt>__strong</tt>. However, a program
1126is ill-formed, no diagnostic required, if it alters <tt>self</tt>
1127except to assign it the immediate result of a delegate init call. It
1128is an error to use the previous value of <tt>self</tt> after the
1129completion of a delegate init call.</p>
1130
1131<p>A program is ill-formed, no diagnostic required, if it causes two
1132or more calls to <tt>init</tt> methods on the same object, except that
1133each <tt>init</tt> method invocation may perform at most one
1134delegate init call.</p>
1135
1136</div> <!-- family.semantics.delegate-init -->
1137
1138<div id="family.semantics.result_type">
1139<h1>Related result types</h1>
1140
1141<p>Certain methods are candidates to have <span class="term">related
1142result types</span>:</p>
1143<ul>
1144<li>class methods in the <tt>alloc</tt> and <tt>new</tt> method families</li>
1145<li>instance methods in the <tt>init</tt> family</li>
1146<li>the instance method <tt>self</tt></li>
1147<li>outside of ARC, the instance methods <tt>retain</tt> and <tt>autorelease</tt></li>
1148</ul>
1149
1150<p>If the formal result type of such a method is <tt>id</tt> or
1151protocol-qualified <tt>id</tt>, or a type equal to the declaring class
1152or a superclass, then it is said to have a related result type. In
1153this case, when invoked in an explicit message send, it is assumed to
1154return a type related to the type of the receiver:</p>
1155
1156<ul>
1157<li>if it is a class method, and the receiver is a class
1158name <tt>T</tt>, the message send expression has type <tt>T*</tt>;
1159otherwise</li>
1160<li>if it is an instance method, and the receiver has type <tt>T</tt>,
1161the message send expression has type <tt>T</tt>; otherwise</li>
1162<li>the message send expression has the normal result type of the
1163method.</li>
1164</ul>
1165
1166<p>This is a new rule of the Objective-C language and applies outside
1167of ARC.</p>
1168
1169<div class="rationale"><p>Rationale: ARC's automatic code emission is
1170more prone than most code to signature errors, i.e. errors where a
1171call was emitted against one method signature, but the implementing
1172method has an incompatible signature. Having more precise type
1173information helps drastically lower this risks, as well as catching
1174a number of latent bugs.</p></div>
1175
1176</div> <!-- family.semantics.result_type -->
1177</div> <!-- family.semantics -->
1178</div> <!-- family -->
1179
1180<div id="optimization">
1181<h1>Optimization</h1>
1182
1183<p>ARC applies aggressive rules for the optimization of local
1184behavior. These rules are based around a core assumption of
1185<span class="term">local balancing</span>: that other code will
1186perform retains and releases as necessary (and only as necessary) for
1187its own safety, and so the optimizer does not need to consider global
1188properties of the retain and release sequence. For example, if a
1189retain and release immediately bracket a call, the optimizer can
1190delete the retain and release on the assumption that the called
1191function will not do a constant number of unmotivated releases
1192followed by a constant number of <q>balancing</q> retains, such that
1193the local retain/release pair is the only thing preventing the called
1194function from ending up with a dangling reference.</p>
1195
1196<p>The optimizer assumes that when a new value enters local control,
1197e.g. from a load of a non-local object or as the result of a function
1198call, it is instaneously valid. Subsequently, a retain and release of
1199a value are necessary on a computation path only if there is a use of
1200that value before the release and after any operation which might
1201cause a release of the value (including indirectly or non-locally),
1202and only if the value is not demonstrably already retained.</p>
1203
1204<p>The complete optimization rules are quite complicated, but it would
1205still be useful to document them here.</p>
1206
1207</div>
1208
1209<div id="misc">
1210<h1>Miscellaneous</h1>
1211
1212<div id="autoreleasepool">
1213<h1><tt>@autoreleasepool</tt></h1>
1214
1215<p>To simplify the use of autorelease pools, and to bring them under
1216the control of the compiler, a new kind of statement is available in
1217Objective-C. It is written <tt>@autoreleasepool</tt> followed by
1218a <i>compound-statement</i>, i.e. by a new scope delimited by curly
1219braces. Upon entry to this block, the current state of the
1220autorelease pool is captured. When the block is exited normally,
1221whether by fallthrough or directed control flow (such
1222as <tt>return</tt> or <tt>break</tt>), the autorelease pool is
1223restored to the saved state, releasing all the objects in it. When
1224the block is exited with an exception, the pool is not drained.</p>
1225
1226<p>A program is ill-formed if it refers to the
1227<tt>NSAutoreleasePool</tt> class.</p>
1228
1229<div class="rationale"><p>Rationale: autorelease pools are clearly
1230important for the compiler to reason about, but it is far too much to
1231expect the compiler to accurately reason about control dependencies
1232between two calls. It is also very easy to accidentally forget to
1233drain an autorelease pool when using the manual API, and this can
1234significantly inflate the process's high-water-mark. The introduction
1235of a new scope is unfortunate but basically required for sane
1236interaction with the rest of the language. Not draining the pool
1237during an unwind is apparently required by the Objective-C exceptions
1238implementation.</p></div>
1239
1240</div> <!-- autoreleasepool -->
1241
1242<div id="misc.self">
1243<h1><tt>self</tt></h1>
1244
1245<p>The <tt>self</tt> parameter variable of an Objective-C method is
1246never actually retained by the implementation. It is undefined
1247behavior, or at least dangerous, to cause an object to be deallocated
1248during a message send to that object. To make this
1249safe, <tt>self</tt> is implicitly <tt>const</tt> unless the method is
1250in the <a href="#family.semantics.init"><tt>init</tt> family</a>.</p>
1251
1252<div class="rationale"><p>Rationale: the cost of
1253retaining <tt>self</tt> in all methods was found to be prohibitive, as
1254it tends to be live across calls, preventing the optimizer from
1255proving that the retain and release are unnecessary &mdash; for good
1256reason, as it's quite possible in theory to cause an object to be
1257deallocated during its execution without this retain and release.
1258Since it's extremely uncommon to actually do so, even unintentionally,
1259and since there's no natural way for the programmer to remove this
1260retain/release pair otherwise (as there is for other parameters by,
1261say, making the variable <tt>__unsafe_unretained</tt>), we chose to
1262make this optimizing assumption and shift some amount of risk to the
1263user.</p></div>
1264
1265</div> <!-- misc.self -->
1266
1267<div id="misc.enumeration">
1268<h1>Fast enumeration iteration variables</h1>
1269
1270<p>If a variable is declared in the condition of an Objective-C fast
1271enumeration loop, and the variable has no explicit ownership
1272qualifier, then it is qualified with <tt>const __strong</tt> and
1273objects encountered during the enumeration are not actually
1274retained.</p>
1275
1276<div class="rationale"><p>Rationale: this is an optimization made
1277possible because fast enumeration loops promise to keep the objects
1278retained during enumeration, and the collection itself cannot be
1279synchronously modified. It can be overridden by explicitly qualifying
1280the variable with <tt>__strong</tt>, which will make the variable
1281mutable again and cause the loop to retain the objects it
1282encounters.</div>
1283
1284</div>
1285
1286<div id="misc.blocks">
1287<h1>Blocks</h1>
1288
1289<p>The implicit <tt>const</tt> capture variables created when
1290evaluating a block literal expression have the same ownership
1291semantics as the local variables they capture. The capture is
1292performed by reading from the captured variable and initializing the
1293capture variable with that value; the capture variable is destroyed
1294when the block literal is, i.e. at the end of the enclosing scope.</p>
1295
1296<p>The <a href="#ownership.inference">inference</a> rules apply
1297equally to <tt>__block</tt> variables, which is a shift in semantics
1298from non-ARC, where <tt>__block</tt> variables did not implicitly
1299retain during capture.</p>
1300
1301<p><tt>__block</tt> variables of retainable object owner type are
1302moved off the stack by initializing the heap copy with the result of
1303moving from the stack copy.</tt></p>
1304
1305<p>With the exception of retains done as part of initializing
1306a <tt>__strong</tt> parameter variable or reading a <tt>__weak</tt>
1307variable, whenever these semantics call for retaining a value of
1308block-pointer type, it has the effect of a <tt>Block_copy</tt>. The
1309optimizer may remove such copies when it sees that the result is
1310used only as an argument to a call.</p>
1311
1312</div> <!-- misc.blocks -->
1313
1314<div id="misc.exceptions">
1315<h1>Exceptions</h1>
1316
1317<p>By default in Objective C, ARC is not exception-safe for normal
1318releases:
1319<ul>
1320<li>It does not end the lifetime of <tt>__strong</tt> variables when
1321their scopes are abnormally terminated by an exception.</li>
1322<li>It does not perform releases which would occur at the end of
1323a full-expression if that full-expression throws an exception.</li>
1324</ul>
1325
1326<p>A program may be compiled with the option
1327<tt>-fobjc-arc-exceptions</tt> in order to enable these, or with the
1328option <tt>-fno-objc-arc-exceptions</tt> to explicitly disable them,
1329with the last such argument <q>winning</q>.</p>
1330
1331<div class="rationale"><p>Rationale: the standard Cocoa convention is
1332that exceptions signal programmer error and are not intended to be
1333recovered from. Making code exceptions-safe by default would impose
1334severe runtime and code size penalties on code that typically does not
1335actually care about exceptions safety. Therefore, ARC-generated code
1336leaks by default on exceptions, which is just fine if the process is
1337going to be immediately terminated anyway. Programs which do care
1338about recovering from exceptions should enable the option.</p></div>
1339
1340<p>In Objective-C++, <tt>-fobjc-arc-exceptions</tt> is enabled by
1341default.</p>
1342
1343<div class="rationale"><p>Rationale: C++ already introduces pervasive
1344exceptions-cleanup code of the sort that ARC introduces. C++
1345programmers who have not already disabled exceptions are much more
1346likely to actual require exception-safety.</p></div>
1347
1348<p>ARC does end the lifetimes of <tt>__weak</tt> objects when an
1349exception terminates their scope unless exceptions are disabled in the
1350compiler.</p>
1351
1352<div class="rationale"><p>Rationale: the consequence of a
1353local <tt>__weak</tt> object not being destroyed is very likely to be
1354corruption of the Objective-C runtime, so we want to be safer here.
1355Of course, potentially massive leaks are about as likely to take down
1356the process as this corruption is if the program does try to recover
1357from exceptions.</p></div>
1358
1359</div> <!-- misc.exceptions -->
1360
1361</div> <!-- misc -->
1362</div> <!-- root -->
1363</body>
1364</html>