This repository was archived by the owner on Nov 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathAutomaticReferenceCounting.html
2226 lines (1851 loc) · 98 KB
/
AutomaticReferenceCounting.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Objective-C Automatic Reference Counting (ARC)</title>
<link type="text/css" rel="stylesheet" href="../menu.css">
<link type="text/css" rel="stylesheet" href="../content.css">
<style type="text/css">
/* Collapse the items in the ToC to the left. */
div#toc ul {
padding-left: 0
}
/* Rationales appear in italic. */
div.rationale {
font-style: italic
}
div.rationale em {
font-style: normal
}
/* Revisions are also italicized. */
span.revision {
font-style: italic
}
span.whenRevised {
font-weight: bold;
font-style: normal
}
div h1 { font-size: 2em; margin: .67em 0 }
div div h1 { font-size: 1.5em; margin: .75em 0 }
div div div h1 { font-size: 1.17em; margin: .83em 0 }
div div div div h1 { margin: 1.12em 0 }
span.term { font-style: italic; font-weight: bold }
</style>
<script type="text/javascript">
/// A little script to recursively build a table of contents.
function buildTOC(div, toc, ancestry) {
var children = div.childNodes;
var len = children.length;
var childNumber = 0;
var list = null;
for (var i = 0; i < len; ++i) {
var child = children[i];
if (child.nodeName != "DIV") continue;
if (child.getAttribute("class") == "rationale") continue;
if (child.id == "toc") continue;
// Okay, we're actually going to build a list node.
if (list === null) list = document.createElement("ul");
var childAncestry = ancestry + ++childNumber + ".";
var headerNode = child.childNodes[1];
var title = headerNode.innerHTML;
headerNode.insertBefore(document.createTextNode(childAncestry + " "),
headerNode.firstChild);
var item = document.createElement("li");
item.appendChild(document.createTextNode(childAncestry + " "));
var anchor = document.createElement("a");
anchor.href = "#" + child.id;
anchor.innerHTML = title;
item.appendChild(anchor);
buildTOC(child, item, childAncestry);
list.appendChild(item);
}
if (list) toc.appendChild(list);
}
function onLoad() {
var toc = document.getElementById("toc");
var content = document.getElementById("content");
buildTOC(content, toc, "");
}
window.onload = onLoad;
</script>
</head>
<body>
<!--#include virtual="../menu.html.incl"-->
<div id="content">
<h1>Automatic Reference Counting</h1>
<div id="toc">
</div>
<div id="meta">
<h1>About this document</h1>
<div id="meta.purpose">
<h1>Purpose</h1>
<p>The first and primary purpose of this document is to serve as a
complete technical specification of Automatic Reference Counting.
Given a core Objective-C compiler and runtime, it should be possible
to write a compiler and runtime which implements these new
semantics.</p>
<p>The secondary purpose is to act as a rationale for why ARC was
designed in this way. This should remain tightly focused on the
technical design and should not stray into marketing speculation.</p>
</div> <!-- meta.purpose -->
<div id="meta.background">
<h1>Background</h1>
<p>This document assumes a basic familiarity with C.</p>
<p><span class="term">Blocks</span> are a C language extension for
creating anonymous functions. Users interact with and transfer block
objects using <span class="term">block pointers</span>, which are
represented like a normal pointer. A block may capture values from
local variables; when this occurs, memory must be dynamically
allocated. The initial allocation is done on the stack, but the
runtime provides a <tt>Block_copy</tt> function which, given a block
pointer, either copies the underlying block object to the heap,
setting its reference count to 1 and returning the new block pointer,
or (if the block object is already on the heap) increases its
reference count by 1. The paired function is <tt>Block_release</tt>,
which decreases the reference count by 1 and destroys the object if
the count reaches zero and is on the heap.</p>
<p>Objective-C is a set of language extensions, significant enough to
be considered a different language. It is a strict superset of C.
The extensions can also be imposed on C++, producing a language called
Objective-C++. The primary feature is a single-inheritance object
system; we briefly describe the modern dialect.</p>
<p>Objective-C defines a new type kind, collectively called
the <span class="term">object pointer types</span>. This kind has two
notable builtin members, <tt>id</tt> and <tt>Class</tt>; <tt>id</tt>
is the final supertype of all object pointers. The validity of
conversions between object pointer types is not checked at runtime.
Users may define <span class="term">classes</span>; each class is a
type, and the pointer to that type is an object pointer type. A class
may have a superclass; its pointer type is a subtype of its
superclass's pointer type. A class has a set
of <span class="term">ivars</span>, fields which appear on all
instances of that class. For every class <i>T</i> there's an
associated metaclass; it has no fields, its superclass is the
metaclass of <i>T</i>'s superclass, and its metaclass is a global
class. Every class has a global object whose class is the
class's metaclass; metaclasses have no associated type, so pointers to
this object have type <tt>Class</tt>.</p>
<p>A class declaration (<tt>@interface</tt>) declares a set
of <span class="term">methods</span>. A method has a return type, a
list of argument types, and a <span class="term">selector</span>: a
name like <tt>foo:bar:baz:</tt>, where the number of colons
corresponds to the number of formal arguments. A method may be an
instance method, in which case it can be invoked on objects of the
class, or a class method, in which case it can be invoked on objects
of the metaclass. A method may be invoked by providing an object
(called the <span class="term">receiver</span>) and a list of formal
arguments interspersed with the selector, like so:</p>
<pre>[receiver foo: fooArg bar: barArg baz: bazArg]</pre>
<p>This looks in the dynamic class of the receiver for a method with
this name, then in that class's superclass, etc., until it finds
something it can execute. The receiver <q>expression</q> may also be
the name of a class, in which case the actual receiver is the class
object for that class, or (within method definitions) it may
be <tt>super</tt>, in which case the lookup algorithm starts with the
static superclass instead of the dynamic class. The actual methods
dynamically found in a class are not those declared in the
<tt>@interface</tt>, but those defined in a separate
<tt>@implementation</tt> declaration; however, when compiling a
call, typechecking is done based on the methods declared in the
<tt>@interface</tt>.</p>
<p>Method declarations may also be grouped into
<span class="term">protocols</span>, which are not inherently
associated with any class, but which classes may claim to follow.
Object pointer types may be qualified with additional protocols that
the object is known to support.</p>
<p><span class="term">Class extensions</span> are collections of ivars
and methods, designed to allow a class's <tt>@interface</tt> to be
split across multiple files; however, there is still a primary
implementation file which must see the <tt>@interface</tt>s of all
class extensions.
<span class="term">Categories</span> allow methods (but not ivars) to
be declared <i>post hoc</i> on an arbitrary class; the methods in the
category's <tt>@implementation</tt> will be dynamically added to that
class's method tables which the category is loaded at runtime,
replacing those methods in case of a collision.</p>
<p>In the standard environment, objects are allocated on the heap, and
their lifetime is manually managed using a reference count. This is
done using two instance methods which all classes are expected to
implement: <tt>retain</tt> increases the object's reference count by
1, whereas <tt>release</tt> decreases it by 1 and calls the instance
method <tt>dealloc</tt> if the count reaches 0. To simplify certain
operations, there is also an <span class="term">autorelease
pool</span>, a thread-local list of objects to call <tt>release</tt>
on later; an object can be added to this pool by
calling <tt>autorelease</tt> on it.</p>
<p>Block pointers may be converted to type <tt>id</tt>; block objects
are laid out in a way that makes them compatible with Objective-C
objects. There is a builtin class that all block objects are
considered to be objects of; this class implements <tt>retain</tt> by
adjusting the reference count, not by calling <tt>Block_copy</tt>.</p>
</div> <!-- meta.background -->
<div id="meta.evolution">
<h1>Evolution</h1>
<p>ARC is under continual evolution, and this document must be updated
as the language progresses.</p>
<p>If a change increases the expressiveness of the language, for
example by lifting a restriction or by adding new syntax, the change
will be annotated with a revision marker, like so:</p>
<blockquote>
ARC applies to Objective-C pointer types, block pointer types, and
<span class="revision"><span class="whenRevised">[beginning Apple
8.0, LLVM 3.8]</span> BPTRs declared within <code>extern
"BCPL"</code> blocks</span>.
</blockquote>
<p>For now, it is sensible to version this document by the releases of
its sole implementation (and its host project), clang.
<q>LLVM X.Y</q> refers to an open-source release of clang from the
LLVM project. <q>Apple X.Y</q> refers to an Apple-provided release of
the Apple LLVM Compiler. Other organizations that prepare their own,
separately-versioned clang releases and wish to maintain similar
information in this document should send requests to cfe-dev.</p>
<p>If a change decreases the expressiveness of the language, for
example by imposing a new restriction, this should be taken as an
oversight in the original specification and something to be avoided
in all versions. Such changes are generally to be avoided.</p>
</div> <!-- meta.evolution -->
</div> <!-- meta -->
<div id="general">
<h1>General</h1>
<p>Automatic Reference Counting implements automatic memory management
for Objective-C objects and blocks, freeing the programmer from the
need to explicitly insert retains and releases. It does not provide a
cycle collector; users must explicitly manage the lifetime of their
objects, breaking cycles manually or with weak or unsafe
references.</p>
<p>ARC may be explicitly enabled with the compiler
flag <tt>-fobjc-arc</tt>. It may also be explicitly disabled with the
compiler flag <tt>-fno-objc-arc</tt>. The last of these two flags
appearing on the compile line <q>wins</q>.</p>
<p>If ARC is enabled, <tt>__has_feature(objc_arc)</tt> will expand to
1 in the preprocessor. For more information about <tt>__has_feature</tt>,
see the <a href="LanguageExtensions.html#__has_feature_extension">language
extensions</a> document.</p>
</div> <!-- general -->
<div id="objects">
<h1>Retainable object pointers</h1>
<p>This section describes retainable object pointers, their basic
operations, and the restrictions imposed on their use under ARC. Note
in particular that it covers the rules for pointer <em>values</em>
(patterns of bits indicating the location of a pointed-to object), not
pointer
<em>objects</em> (locations in memory which store pointer values).
The rules for objects are covered in the next section.</p>
<p>A <span class="term">retainable object pointer</span>
(or <q>retainable pointer</q>) is a value of
a <span class="term">retainable object pointer type</span>
(<q>retainable type</q>). There are three kinds of retainable object
pointer types:</p>
<ul>
<li>block pointers (formed by applying the caret (<tt>^</tt>)
declarator sigil to a function type)</li>
<li>Objective-C object pointers (<tt>id</tt>, <tt>Class</tt>, <tt>NSFoo*</tt>, etc.)</li>
<li>typedefs marked with <tt>__attribute__((NSObject))</tt></li>
</ul>
<p>Other pointer types, such as <tt>int*</tt> and <tt>CFStringRef</tt>,
are not subject to ARC's semantics and restrictions.</p>
<div class="rationale">
<p>Rationale: We are not at liberty to require
all code to be recompiled with ARC; therefore, ARC must interoperate
with Objective-C code which manages retains and releases manually. In
general, there are three requirements in order for a
compiler-supported reference-count system to provide reliable
interoperation:</p>
<ul>
<li>The type system must reliably identify which objects are to be
managed. An <tt>int*</tt> might be a pointer to a <tt>malloc</tt>'ed
array, or it might be an interior pointer to such an array, or it might
point to some field or local variable. In contrast, values of the
retainable object pointer types are never interior.</li>
<li>The type system must reliably indicate how to
manage objects of a type. This usually means that the type must imply
a procedure for incrementing and decrementing retain counts.
Supporting single-ownership objects requires a lot more explicit
mediation in the language.</li>
<li>There must be reliable conventions for whether and
when <q>ownership</q> is passed between caller and callee, for both
arguments and return values. Objective-C methods follow such a
convention very reliably, at least for system libraries on Mac OS X,
and functions always pass objects at +0. The C-based APIs for Core
Foundation objects, on the other hand, have much more varied transfer
semantics.</li>
</ul>
</div> <!-- rationale -->
<p>The use of <tt>__attribute__((NSObject))</tt> typedefs is not
recommended. If it's absolutely necessary to use this attribute, be
very explicit about using the typedef, and do not assume that it will
be preserved by language features like <tt>__typeof</tt> and C++
template argument substitution.</p>
<div class="rationale"><p>Rationale: any compiler operation which
incidentally strips type <q>sugar</q> from a type will yield a type
without the attribute, which may result in unexpected
behavior.</p></div>
<div id="objects.retains">
<h1>Retain count semantics</h1>
<p>A retainable object pointer is either a <span class="term">null
pointer</span> or a pointer to a valid object. Furthermore, if it has
block pointer type and is not <tt>null</tt> then it must actually be a
pointer to a block object, and if it has <tt>Class</tt> type (possibly
protocol-qualified) then it must actually be a pointer to a class
object. Otherwise ARC does not enforce the Objective-C type system as
long as the implementing methods follow the signature of the static
type. It is undefined behavior if ARC is exposed to an invalid
pointer.</p>
<p>For ARC's purposes, a valid object is one with <q>well-behaved</q>
retaining operations. Specifically, the object must be laid out such
that the Objective-C message send machinery can successfully send it
the following messages:</p>
<ul>
<li><tt>retain</tt>, taking no arguments and returning a pointer to
the object.</li>
<li><tt>release</tt>, taking no arguments and returning <tt>void</tt>.</li>
<li><tt>autorelease</tt>, taking no arguments and returning a pointer
to the object.</li>
</ul>
<p>The behavior of these methods is constrained in the following ways.
The term <span class="term">high-level semantics</span> is an
intentionally vague term; the intent is that programmers must
implement these methods in a way such that the compiler, modifying
code in ways it deems safe according to these constraints, will not
violate their requirements. For example, if the user puts logging
statements in <tt>retain</tt>, they should not be surprised if those
statements are executed more or less often depending on optimization
settings. These constraints are not exhaustive of the optimization
opportunities: values held in local variables are subject to
additional restrictions, described later in this document.</p>
<p>It is undefined behavior if a computation history featuring a send
of <tt>retain</tt> followed by a send of <tt>release</tt> to the same
object, with no intervening <tt>release</tt> on that object, is not
equivalent under the high-level semantics to a computation
history in which these sends are removed. Note that this implies that
these methods may not raise exceptions.</p>
<p>It is undefined behavior if a computation history features any use
whatsoever of an object following the completion of a send
of <tt>release</tt> that is not preceded by a send of <tt>retain</tt>
to the same object.</p>
<p>The behavior of <tt>autorelease</tt> must be equivalent to sending
<tt>release</tt> when one of the autorelease pools currently in scope
is popped. It may not throw an exception.</p>
<p>When the semantics call for performing one of these operations on a
retainable object pointer, if that pointer is <tt>null</tt> then the
effect is a no-op.</p>
<p>All of the semantics described in this document are subject to
additional <a href="#optimization">optimization rules</a> which permit
the removal or optimization of operations based on local knowledge of
data flow. The semantics describe the high-level behaviors that the
compiler implements, not an exact sequence of operations that a
program will be compiled into.</p>
</div> <!-- objects.retains -->
<div id="objects.operands">
<h1>Retainable object pointers as operands and arguments</h1>
<p>In general, ARC does not perform retain or release operations when
simply using a retainable object pointer as an operand within an
expression. This includes:</p>
<ul>
<li>loading a retainable pointer from an object with non-weak
<a href="#ownership">ownership</a>,</li>
<li>passing a retainable pointer as an argument to a function or
method, and</li>
<li>receiving a retainable pointer as the result of a function or
method call.</li>
</ul>
<div class="rationale"><p>Rationale: while this might seem
uncontroversial, it is actually unsafe when multiple expressions are
evaluated in <q>parallel</q>, as with binary operators and calls,
because (for example) one expression might load from an object while
another writes to it. However, C and C++ already call this undefined
behavior because the evaluations are unsequenced, and ARC simply
exploits that here to avoid needing to retain arguments across a large
number of calls.</p></div>
<p>The remainder of this section describes exceptions to these rules,
how those exceptions are detected, and what those exceptions imply
semantically.</p>
<div id="objects.operands.consumed">
<h1>Consumed parameters</h1>
<p>A function or method parameter of retainable object pointer type
may be marked as <span class="term">consumed</span>, signifying that
the callee expects to take ownership of a +1 retain count. This is
done by adding the <tt>ns_consumed</tt> attribute to the parameter
declaration, like so:</p>
<pre>void foo(__attribute((ns_consumed)) id x);
- (void) foo: (id) __attribute((ns_consumed)) x;</pre>
<p>This attribute is part of the type of the function or method, not
the type of the parameter. It controls only how the argument is
passed and received.</p>
<p>When passing such an argument, ARC retains the argument prior to
making the call.</p>
<p>When receiving such an argument, ARC releases the argument at the
end of the function, subject to the usual optimizations for local
values.</p>
<div class="rationale"><p>Rationale: this formalizes direct transfers
of ownership from a caller to a callee. The most common scenario here
is passing the <tt>self</tt> parameter to <tt>init</tt>, but it is
useful to generalize. Typically, local optimization will remove any
extra retains and releases: on the caller side the retain will be
merged with a +1 source, and on the callee side the release will be
rolled into the initialization of the parameter.</p></div>
<p>The implicit <tt>self</tt> parameter of a method may be marked as
consumed by adding <tt>__attribute__((ns_consumes_self))</tt> to the
method declaration. Methods in the <tt>init</tt>
<a href="#family">family</a> are treated as if they were implicitly
marked with this attribute.</p>
<p>It is undefined behavior if an Objective-C message send to a method
with <tt>ns_consumed</tt> parameters (other than self) is made with a
null receiver. It is undefined behavior if the method to which an
Objective-C message send statically resolves to has a different set
of <tt>ns_consumed</tt> parameters than the method it dynamically
resolves to. It is undefined behavior if a block or function call is
made through a static type with a different set of <tt>ns_consumed</tt>
parameters than the implementation of the called block or function.</p>
<div class="rationale"><p>Rationale: consumed parameters with null
receiver are a guaranteed leak. Mismatches with consumed parameters
will cause over-retains or over-releases, depending on the direction.
The rule about function calls is really just an application of the
existing C/C++ rule about calling functions through an incompatible
function type, but it's useful to state it explicitly.</p></div>
</div> <!-- objects.operands.consumed -->
<div id="objects.operands.retained-returns">
<h1>Retained return values</h1>
<p>A function or method which returns a retainable object pointer type
may be marked as returning a retained value, signifying that the
caller expects to take ownership of a +1 retain count. This is done
by adding the <tt>ns_returns_retained</tt> attribute to the function or
method declaration, like so:</p>
<pre>id foo(void) __attribute((ns_returns_retained));
- (id) foo __attribute((ns_returns_retained));</pre>
<p>This attribute is part of the type of the function or method.</p>
<p>When returning from such a function or method, ARC retains the
value at the point of evaluation of the return statement, before
leaving all local scopes.</p>
<p>When receiving a return result from such a function or method, ARC
releases the value at the end of the full-expression it is contained
within, subject to the usual optimizations for local values.</p>
<div class="rationale"><p>Rationale: this formalizes direct transfers of
ownership from a callee to a caller. The most common scenario this
models is the retained return from <tt>init</tt>, <tt>alloc</tt>,
<tt>new</tt>, and <tt>copy</tt> methods, but there are other cases in
the frameworks. After optimization there are typically no extra
retains and releases required.</p></div>
<p>Methods in
the <tt>alloc</tt>, <tt>copy</tt>, <tt>init</tt>, <tt>mutableCopy</tt>,
and <tt>new</tt> <a href="#family">families</a> are implicitly marked
<tt>__attribute__((ns_returns_retained))</tt>. This may be suppressed
by explicitly marking the
method <tt>__attribute__((ns_returns_not_retained))</tt>.</p>
<p>It is undefined behavior if the method to which an Objective-C
message send statically resolves has different retain semantics on its
result from the method it dynamically resolves to. It is undefined
behavior if a block or function call is made through a static type
with different retain semantics on its result from the implementation
of the called block or function.</p>
<div class="rationale"><p>Rationale: Mismatches with returned results
will cause over-retains or over-releases, depending on the direction.
Again, the rule about function calls is really just an application of
the existing C/C++ rule about calling functions through an
incompatible function type.</p></div>
</div> <!-- objects.operands.retained-returns -->
<div id="objects.operands.other-returns">
<h1>Unretained return values</h1>
<p>A method or function which returns a retainable object type but
does not return a retained value must ensure that the object is
still valid across the return boundary.</p>
<p>When returning from such a function or method, ARC retains the
value at the point of evaluation of the return statement, then leaves
all local scopes, and then balances out the retain while ensuring that
the value lives across the call boundary. In the worst case, this may
involve an <tt>autorelease</tt>, but callers must not assume that the
value is actually in the autorelease pool.</p>
<p>ARC performs no extra mandatory work on the caller side, although
it may elect to do something to shorten the lifetime of the returned
value.</p>
<div class="rationale"><p>Rationale: it is common in non-ARC code to not
return an autoreleased value; therefore the convention does not force
either path. It is convenient to not be required to do unnecessary
retains and autoreleases; this permits optimizations such as eliding
retain/autoreleases when it can be shown that the original pointer
will still be valid at the point of return.</p></div>
<p>A method or function may be marked
with <tt>__attribute__((ns_returns_autoreleased))</tt> to indicate
that it returns a pointer which is guaranteed to be valid at least as
long as the innermost autorelease pool. There are no additional
semantics enforced in the definition of such a method; it merely
enables optimizations in callers.</p>
</div> <!-- objects.operands.other-returns -->
<div id="objects.operands.casts">
<h1>Bridged casts</h1>
<p>A <span class="term">bridged cast</span> is a C-style cast
annotated with one of three keywords:</p>
<ul>
<li><tt>(__bridge T) op</tt> casts the operand to the destination
type <tt>T</tt>. If <tt>T</tt> is a retainable object pointer type,
then <tt>op</tt> must have a non-retainable pointer type.
If <tt>T</tt> is a non-retainable pointer type, then <tt>op</tt> must
have a retainable object pointer type. Otherwise the cast is
ill-formed. There is no transfer of ownership, and ARC inserts
no retain operations.</li>
<li><tt>(__bridge_retained T) op</tt> casts the operand, which must
have retainable object pointer type, to the destination type, which
must be a non-retainable pointer type. ARC retains the value, subject
to the usual optimizations on local values, and the recipient is
responsible for balancing that +1.</li>
<li><tt>(__bridge_transfer T) op</tt> casts the operand, which must
have non-retainable pointer type, to the destination type, which must
be a retainable object pointer type. ARC will release the value at
the end of the enclosing full-expression, subject to the usual
optimizations on local values.</li>
</ul>
<p>These casts are required in order to transfer objects in and out of
ARC control; see the rationale in the section
on <a href="#objects.restrictions.conversion">conversion of retainable
object pointers</a>.</p>
<p>Using a <tt>__bridge_retained</tt> or <tt>__bridge_transfer</tt>
cast purely to convince ARC to emit an unbalanced retain or release,
respectively, is poor form.</p>
</div> <!-- objects.operands.casts -->
</div> <!-- objects.operands -->
<div id="objects.restrictions">
<h1>Restrictions</h1>
<div id="objects.restrictions.conversion">
<h1>Conversion of retainable object pointers</h1>
<p>In general, a program which attempts to implicitly or explicitly
convert a value of retainable object pointer type to any
non-retainable type, or vice-versa, is ill-formed. For example, an
Objective-C object pointer shall not be converted to <tt>void*</tt>.
As an exception, cast to <tt>intptr_t</tt> is allowed because such
casts are not transferring ownership. The <a href="#objects.operands.casts">bridged
casts</a> may be used to perform these conversions where
necessary.</p>
<div class="rationale"><p>Rationale: we cannot ensure the correct
management of the lifetime of objects if they may be freely passed
around as unmanaged types. The bridged casts are provided so that the
programmer may explicitly describe whether the cast transfers control
into or out of ARC.</p></div>
<p>However, the following exceptions apply.</p>
</div> <!-- objects.restrictions.conversion -->
<div id="objects.restrictions.conversion-exception-known">
<h1>Conversion to retainable object pointer type of
expressions with known semantics</h1>
<p><span class="revision"><span class="whenRevised">[beginning Apple
4.0, LLVM 3.1]</span> These exceptions have been greatly expanded;
they previously applied only to a much-reduced subset which is
difficult to categorize but which included null pointers, message
sends (under the given rules), and the various global constants.</span></p>
<p>An unbridged conversion to a retainable object pointer type from a
type other than a retainable object pointer type is ill-formed, as
discussed above, unless the operand of the cast has a syntactic form
which is known retained, known unretained, or known
retain-agnostic.</p>
<p>An expression is <span class="term">known retain-agnostic</span> if
it is:</p>
<ul>
<li>an Objective-C string literal,</li>
<li>a load from a <tt>const</tt> system global variable of
<a href="#misc.c-retainable">C retainable pointer type</a>, or</li>
<li>a null pointer constant.</li>
</ul>
<p>An expression is <span class="term">known unretained</span> if it
is an rvalue of <a href="#misc.c-retainable">C retainable
pointer type</a> and it is:</p>
<ul>
<li>a direct call to a function, and either that function has the
<tt>cf_returns_not_retained</tt> attribute or it is an
<a href="#misc.c-retainable.audit">audited</a> function that does not
have the <tt>cf_returns_retained</tt> attribute and does not follow
the create/copy naming convention,</li>
<li>a message send, and the declared method either has
the <tt>cf_returns_not_retained</tt> attribute or it has neither
the <tt>cf_returns_retained</tt> attribute nor a
<a href="#family">selector family</a> that implies a retained
result.</li>
</ul>
<p>An expression is <span class="term">known retained</span> if it is
an rvalue of <a href="#misc.c-retainable">C retainable pointer type</a>
and it is:</p>
<ul>
<li>a message send, and the declared method either has the
<tt>cf_returns_retained</tt> attribute, or it does not have
the <tt>cf_returns_not_retained</tt> attribute but it does have a
<a href="#family">selector family</a> that implies a retained
result.</li>
</ul>
<p>Furthermore:</p>
<ul>
<li>a comma expression is classified according to its right-hand side,</li>
<li>a statement expression is classified according to its result
expression, if it has one,</li>
<li>an lvalue-to-rvalue conversion applied to an Objective-C property
lvalue is classified according to the underlying message send, and</li>
<li>a conditional operator is classified according to its second and
third operands, if they agree in classification, or else the other
if one is known retain-agnostic.</li>
</ul>
<p>If the cast operand is known retained, the conversion is treated as
a <tt>__bridge_transfer</tt> cast. If the cast operand is known
unretained or known retain-agnostic, the conversion is treated as
a <tt>__bridge</tt> cast.</p>
<div class="rationale"><p>Rationale: Bridging casts are annoying.
Absent the ability to completely automate the management of CF
objects, however, we are left with relatively poor attempts to reduce
the need for a glut of explicit bridges. Hence these rules.</p>
<p>We've so far consciously refrained from implicitly turning retained
CF results from function calls into <tt>__bridge_transfer</tt> casts.
The worry is that some code patterns — for example, creating a
CF value, assigning it to an ObjC-typed local, and then
calling <tt>CFRelease</tt> when done — are a bit too likely to
be accidentally accepted, leading to mysterious behavior.</p></div>
</div> <!-- objects.restrictions.conversion-exception-known -->
<div id="objects.restrictions.conversion-exception-contextual">
<h1>Conversion from retainable object pointer type in certain contexts</h1>
<p><span class="revision"><span class="whenRevised">[beginning Apple
4.0, LLVM 3.1]</span></span></p>
<p>If an expression of retainable object pointer type is explicitly
cast to a <a href="#misc.c-retainable">C retainable pointer type</a>,
the program is ill-formed as discussed above unless the result is
immediately used:</p>
<ul>
<li>to initialize a parameter in an Objective-C message send where the
parameter is not marked with the <tt>cf_consumed</tt> attribute, or</li>
<li>to initialize a parameter in a direct call to
an <a href="#misc.c-retainable.audit">audited</a> function where the
parameter is not marked with the <tt>cf_consumed</tt> attribute.</li>
</ul>
<div class="rationale"><p>Rationale: Consumed parameters are left out
because ARC would naturally balance them with a retain, which was
judged too treacherous. This is in part because several of the most
common consuming functions are in the <tt>Release</tt> family, and it
would be quite unfortunate for explicit releases to be silently
balanced out in this way.</p></div>
</div> <!-- objects.restrictions.conversion-exception-contextual -->
</div> <!-- objects.restrictions -->
</div> <!-- objects -->
<div id="ownership">
<h1>Ownership qualification</h1>
<p>This section describes the behavior of <em>objects</em> of
retainable object pointer type; that is, locations in memory which
store retainable object pointers.</p>
<p>A type is a <span class="term">retainable object owner type</span>
if it is a retainable object pointer type or an array type whose
element type is a retainable object owner type.</p>
<p>An <span class="term">ownership qualifier</span> is a type
qualifier which applies only to retainable object owner types. An array type is
ownership-qualified according to its element type, and adding an ownership
qualifier to an array type so qualifies its element type.</p>
<p>A program is ill-formed if it attempts to apply an ownership qualifier
to a type which is already ownership-qualified, even if it is the same
qualifier. There is a single exception to this rule: an ownership qualifier
may be applied to a substituted template type parameter, which overrides the
ownership qualifier provided by the template argument.</p>
<p>Except as described under
the <a href="#ownership.inference">inference rules</a>, a program is
ill-formed if it attempts to form a pointer or reference type to a
retainable object owner type which lacks an ownership qualifier.</p>
<div class="rationale"><p>Rationale: these rules, together with the
inference rules, ensure that all objects and lvalues of retainable
object pointer type have an ownership qualifier. The ability to override an ownership qualifier during template substitution is required to counteract the <a href="#ownership.inference.template_arguments">inference of <tt>__strong</tt> for template type arguments</a>. </p></div>
<p>There are four ownership qualifiers:</p>
<ul>
<li><tt>__autoreleasing</tt></li>
<li><tt>__strong</tt></li>
<li><tt>__unsafe_unretained</tt></li>
<li><tt>__weak</tt></li>
</ul>
<p>A type is <span class="term">nontrivially ownership-qualified</span>
if it is qualified with <tt>__autoreleasing</tt>, <tt>__strong</tt>, or
<tt>__weak</tt>.</p>
<div id="ownership.spelling">
<h1>Spelling</h1>
<p>The names of the ownership qualifiers are reserved for the
implementation. A program may not assume that they are or are not
implemented with macros, or what those macros expand to.</p>
<p>An ownership qualifier may be written anywhere that any other type
qualifier may be written.</p>
<p>If an ownership qualifier appears in
the <i>declaration-specifiers</i>, the following rules apply:</p>
<ul>
<li>if the type specifier is a retainable object owner type, the
qualifier applies to that type;</li>
<li>if the outermost non-array part of the declarator is a pointer or
block pointer, the qualifier applies to that type;</li>
<li>otherwise the program is ill-formed.</li>
</ul>
<p>If an ownership qualifier appears on the declarator name, or on the
declared object, it is applied to outermost pointer or block-pointer
type.</p>
<p>If an ownership qualifier appears anywhere else in a declarator, it
applies to the type there.</p>
<div id="ownership.spelling.property">
<h1>Property declarations</h1>
<p>A property of retainable object pointer type may have ownership.
If the property's type is ownership-qualified, then the property has
that ownership. If the property has one of the following modifiers,
then the property has the corresponding ownership. A property is
ill-formed if it has conflicting sources of ownership, or if it has
redundant ownership modifiers, or if it has <tt>__autoreleasing</tt>
ownership.</p>
<ul>
<li><tt>assign</tt> implies <tt>__unsafe_unretained</tt> ownership.</li>
<li><tt>copy</tt> implies <tt>__strong</tt> ownership, as well as the
usual behavior of copy semantics on the setter.</li>
<li><tt>retain</tt> implies <tt>__strong</tt> ownership.</li>
<li><tt>strong</tt> implies <tt>__strong</tt> ownership.</li>
<li><tt>unsafe_unretained</tt> implies <tt>__unsafe_unretained</tt>
ownership.</li>
<li><tt>weak</tt> implies <tt>__weak</tt> ownership.</li>
</ul>
<p>With the exception of <tt>weak</tt>, these modifiers are available
in non-ARC modes.</p>
<p>A property's specified ownership is preserved in its metadata, but
otherwise the meaning is purely conventional unless the property is
synthesized. If a property is synthesized, then the
<span class="term">associated instance variable</span> is the
instance variable which is named, possibly implicitly, by the
<tt>@synthesize</tt> declaration. If the associated instance variable
already exists, then its ownership qualification must equal the
ownership of the property; otherwise, the instance variable is created
with that ownership qualification.</p>
<p>A property of retainable object pointer type which is synthesized
without a source of ownership has the ownership of its associated
instance variable, if it already exists; otherwise,
<span class="revision"><span class="whenRevised">[beginning Apple 3.1,
LLVM 3.1]</span> its ownership is implicitly <tt>strong</tt></span>.
Prior to this revision, it was ill-formed to synthesize such a
property.</p>
<div class="rationale"><p>Rationale: using <tt>strong</tt> by default
is safe and consistent with the generic ARC rule about
<a href="#ownership.inference.variables">inferring ownership</a>. It
is, unfortunately, inconsistent with the non-ARC rule which states
that such properties are implicitly <tt>assign</tt>. However, that
rule is clearly untenable in ARC, since it leads to default-unsafe
code. The main merit to banning the properties is to avoid confusion
with non-ARC practice, which did not ultimately strike us as
sufficient to justify requiring extra syntax and (more importantly)
forcing novices to understand ownership rules just to declare a
property when the default is so reasonable. Changing the rule away
from non-ARC practice was acceptable because we had conservatively
banned the synthesis in order to give ourselves exactly this
leeway.</p></div>
<p>Applying <tt>__attribute__((NSObject))</tt> to a property not of
retainable object pointer type has the same behavior it does outside
of ARC: it requires the property type to be some sort of pointer and
permits the use of modifiers other than <tt>assign</tt>. These
modifiers only affect the synthesized getter and setter; direct
accesses to the ivar (even if synthesized) still have primitive
semantics, and the value in the ivar will not be automatically
released during deallocation.</p>
</div> <!-- ownership.spelling.property -->
</div> <!-- ownership.spelling -->
<div id="ownership.semantics">
<h1>Semantics</h1>
<p>There are five <span class="term">managed operations</span> which
may be performed on an object of retainable object pointer type. Each
qualifier specifies different semantics for each of these operations.
It is still undefined behavior to access an object outside of its
lifetime.</p>
<p>A load or store with <q>primitive semantics</q> has the same
semantics as the respective operation would have on an <tt>void*</tt>
lvalue with the same alignment and non-ownership qualification.</p>
<p><span class="term">Reading</span> occurs when performing a
lvalue-to-rvalue conversion on an object lvalue.</p>
<ul>
<li>For <tt>__weak</tt> objects, the current pointee is retained and
then released at the end of the current full-expression. This must
execute atomically with respect to assignments and to the final
release of the pointee.</li>
<li>For all other objects, the lvalue is loaded with primitive
semantics.</li>
</ul>
<p><span class="term">Assignment</span> occurs when evaluating
an assignment operator. The semantics vary based on the qualification:</p>
<ul>
<li>For <tt>__strong</tt> objects, the new pointee is first retained;
second, the lvalue is loaded with primitive semantics; third, the new
pointee is stored into the lvalue with primitive semantics; and
finally, the old pointee is released. This is not performed
atomically; external synchronization must be used to make this safe in
the face of concurrent loads and stores.</li>
<li>For <tt>__weak</tt> objects, the lvalue is updated to point to the
new pointee, unless the new pointee is an object currently undergoing
deallocation, in which case the lvalue is updated to a null pointer.
This must execute atomically with respect to other assignments to the
object, to reads from the object, and to the final release of the new
pointee.</li>
<li>For <tt>__unsafe_unretained</tt> objects, the new pointee is
stored into the lvalue using primitive semantics.</li>
<li>For <tt>__autoreleasing</tt> objects, the new pointee is retained,
autoreleased, and stored into the lvalue using primitive semantics.</li>
</ul>
<p><span class="term">Initialization</span> occurs when an object's
lifetime begins, which depends on its storage duration.
Initialization proceeds in two stages:</p>
<ol>
<li>First, a null pointer is stored into the lvalue using primitive
semantics. This step is skipped if the object
is <tt>__unsafe_unretained</tt>.</li>
<li>Second, if the object has an initializer, that expression is
evaluated and then assigned into the object using the usual assignment
semantics.</li>
</ol>
<p><span class="term">Destruction</span> occurs when an object's
lifetime ends. In all cases it is semantically equivalent to
assigning a null pointer to the object, with the proviso that of
course the object cannot be legally read after the object's lifetime
ends.</p>
<p><span class="term">Moving</span> occurs in specific situations
where an lvalue is <q>moved from</q>, meaning that its current pointee
will be used but the object may be left in a different (but still
valid) state. This arises with <tt>__block</tt> variables and rvalue
references in C++. For <tt>__strong</tt> lvalues, moving is equivalent
to loading the lvalue with primitive semantics, writing a null pointer
to it with primitive semantics, and then releasing the result of the
load at the end of the current full-expression. For all other
lvalues, moving is equivalent to reading the object.</p>
</div> <!-- ownership.semantics -->
<div id="ownership.restrictions">
<h1>Restrictions</h1>
<div id="ownership.restrictions.weak">
<h1>Weak-unavailable types</h1>
<p>It is explicitly permitted for Objective-C classes to not
support <tt>__weak</tt> references. It is undefined behavior to
perform an operation with weak assignment semantics with a pointer to
an Objective-C object whose class does not support <tt>__weak</tt>
references.</p>
<div class="rationale"><p>Rationale: historically, it has been
possible for a class to provide its own reference-count implementation
by overriding <tt>retain</tt>, <tt>release</tt>, etc. However, weak
references to an object require coordination with its class's
reference-count implementation because, among other things, weak loads
and stores must be atomic with respect to the final release.
Therefore, existing custom reference-count implementations will
generally not support weak references without additional effort. This
is unavoidable without breaking binary compatibility.</p></div>