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