1 //===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for Objective-C expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/ExprObjC.h"
18 #include "clang/AST/StmtVisitor.h"
19 #include "clang/AST/TypeLoc.h"
20 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
21 #include "clang/Edit/Commit.h"
22 #include "clang/Edit/Rewriters.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "clang/Sema/Initialization.h"
25 #include "clang/Sema/Lookup.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/ScopeInfo.h"
28 #include "llvm/ADT/SmallString.h"
29 
30 using namespace clang;
31 using namespace sema;
32 using llvm::makeArrayRef;
33 
34 ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
35                                         Expr **strings,
36                                         unsigned NumStrings) {
37   StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
38 
39   // Most ObjC strings are formed out of a single piece.  However, we *can*
40   // have strings formed out of multiple @ strings with multiple pptokens in
41   // each one, e.g. @"foo" "bar" @"baz" "qux"   which need to be turned into one
42   // StringLiteral for ObjCStringLiteral to hold onto.
43   StringLiteral *S = Strings[0];
44 
45   // If we have a multi-part string, merge it all together.
46   if (NumStrings != 1) {
47     // Concatenate objc strings.
48     SmallString<128> StrBuf;
49     SmallVector<SourceLocation, 8> StrLocs;
50 
51     for (unsigned i = 0; i != NumStrings; ++i) {
52       S = Strings[i];
53 
54       // ObjC strings can't be wide or UTF.
55       if (!S->isAscii()) {
56         Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
57           << S->getSourceRange();
58         return true;
59       }
60 
61       // Append the string.
62       StrBuf += S->getString();
63 
64       // Get the locations of the string tokens.
65       StrLocs.append(S->tokloc_begin(), S->tokloc_end());
66     }
67 
68     // Create the aggregate string with the appropriate content and location
69     // information.
70     const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
71     assert(CAT && "String literal not of constant array type!");
72     QualType StrTy = Context.getConstantArrayType(
73         CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1),
74         CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
75     S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii,
76                               /*Pascal=*/false, StrTy, &StrLocs[0],
77                               StrLocs.size());
78   }
79 
80   return BuildObjCStringLiteral(AtLocs[0], S);
81 }
82 
83 ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
84   // Verify that this composite string is acceptable for ObjC strings.
85   if (CheckObjCString(S))
86     return true;
87 
88   // Initialize the constant string interface lazily. This assumes
89   // the NSString interface is seen in this translation unit. Note: We
90   // don't use NSConstantString, since the runtime team considers this
91   // interface private (even though it appears in the header files).
92   QualType Ty = Context.getObjCConstantStringInterface();
93   if (!Ty.isNull()) {
94     Ty = Context.getObjCObjectPointerType(Ty);
95   } else if (getLangOpts().NoConstantCFStrings) {
96     IdentifierInfo *NSIdent=0;
97     std::string StringClass(getLangOpts().ObjCConstantStringClass);
98 
99     if (StringClass.empty())
100       NSIdent = &Context.Idents.get("NSConstantString");
101     else
102       NSIdent = &Context.Idents.get(StringClass);
103 
104     NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
105                                      LookupOrdinaryName);
106     if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
107       Context.setObjCConstantStringInterface(StrIF);
108       Ty = Context.getObjCConstantStringInterface();
109       Ty = Context.getObjCObjectPointerType(Ty);
110     } else {
111       // If there is no NSConstantString interface defined then treat this
112       // as error and recover from it.
113       Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
114         << S->getSourceRange();
115       Ty = Context.getObjCIdType();
116     }
117   } else {
118     IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
119     NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
120                                      LookupOrdinaryName);
121     if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
122       Context.setObjCConstantStringInterface(StrIF);
123       Ty = Context.getObjCConstantStringInterface();
124       Ty = Context.getObjCObjectPointerType(Ty);
125     } else {
126       // If there is no NSString interface defined, implicitly declare
127       // a @class NSString; and use that instead. This is to make sure
128       // type of an NSString literal is represented correctly, instead of
129       // being an 'id' type.
130       Ty = Context.getObjCNSStringType();
131       if (Ty.isNull()) {
132         ObjCInterfaceDecl *NSStringIDecl =
133           ObjCInterfaceDecl::Create (Context,
134                                      Context.getTranslationUnitDecl(),
135                                      SourceLocation(), NSIdent,
136                                      0, SourceLocation());
137         Ty = Context.getObjCInterfaceType(NSStringIDecl);
138         Context.setObjCNSStringType(Ty);
139       }
140       Ty = Context.getObjCObjectPointerType(Ty);
141     }
142   }
143 
144   return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
145 }
146 
147 /// \brief Emits an error if the given method does not exist, or if the return
148 /// type is not an Objective-C object.
149 static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
150                                  const ObjCInterfaceDecl *Class,
151                                  Selector Sel, const ObjCMethodDecl *Method) {
152   if (!Method) {
153     // FIXME: Is there a better way to avoid quotes than using getName()?
154     S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
155     return false;
156   }
157 
158   // Make sure the return type is reasonable.
159   QualType ReturnType = Method->getReturnType();
160   if (!ReturnType->isObjCObjectPointerType()) {
161     S.Diag(Loc, diag::err_objc_literal_method_sig)
162       << Sel;
163     S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
164       << ReturnType;
165     return false;
166   }
167 
168   return true;
169 }
170 
171 /// \brief Retrieve the NSNumber factory method that should be used to create
172 /// an Objective-C literal for the given type.
173 static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
174                                                 QualType NumberType,
175                                                 bool isLiteral = false,
176                                                 SourceRange R = SourceRange()) {
177   Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
178       S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
179 
180   if (!Kind) {
181     if (isLiteral) {
182       S.Diag(Loc, diag::err_invalid_nsnumber_type)
183         << NumberType << R;
184     }
185     return 0;
186   }
187 
188   // If we already looked up this method, we're done.
189   if (S.NSNumberLiteralMethods[*Kind])
190     return S.NSNumberLiteralMethods[*Kind];
191 
192   Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
193                                                         /*Instance=*/false);
194 
195   ASTContext &CX = S.Context;
196 
197   // Look up the NSNumber class, if we haven't done so already. It's cached
198   // in the Sema instance.
199   if (!S.NSNumberDecl) {
200     IdentifierInfo *NSNumberId =
201       S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber);
202     NamedDecl *IF = S.LookupSingleName(S.TUScope, NSNumberId,
203                                        Loc, Sema::LookupOrdinaryName);
204     S.NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
205     if (!S.NSNumberDecl) {
206       if (S.getLangOpts().DebuggerObjCLiteral) {
207         // Create a stub definition of NSNumber.
208         S.NSNumberDecl = ObjCInterfaceDecl::Create(CX,
209                                                    CX.getTranslationUnitDecl(),
210                                                    SourceLocation(), NSNumberId,
211                                                    0, SourceLocation());
212       } else {
213         // Otherwise, require a declaration of NSNumber.
214         S.Diag(Loc, diag::err_undeclared_nsnumber);
215         return 0;
216       }
217     } else if (!S.NSNumberDecl->hasDefinition()) {
218       S.Diag(Loc, diag::err_undeclared_nsnumber);
219       return 0;
220     }
221 
222     // generate the pointer to NSNumber type.
223     QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
224     S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
225   }
226 
227   // Look for the appropriate method within NSNumber.
228   ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
229   if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
230     // create a stub definition this NSNumber factory method.
231     TypeSourceInfo *ReturnTInfo = 0;
232     Method =
233         ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
234                                S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
235                                /*isInstance=*/false, /*isVariadic=*/false,
236                                /*isPropertyAccessor=*/false,
237                                /*isImplicitlyDeclared=*/true,
238                                /*isDefined=*/false, ObjCMethodDecl::Required,
239                                /*HasRelatedResultType=*/false);
240     ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
241                                              SourceLocation(), SourceLocation(),
242                                              &CX.Idents.get("value"),
243                                              NumberType, /*TInfo=*/0, SC_None,
244                                              0);
245     Method->setMethodParams(S.Context, value, None);
246   }
247 
248   if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
249     return 0;
250 
251   // Note: if the parameter type is out-of-line, we'll catch it later in the
252   // implicit conversion.
253 
254   S.NSNumberLiteralMethods[*Kind] = Method;
255   return Method;
256 }
257 
258 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
259 /// numeric literal expression. Type of the expression will be "NSNumber *".
260 ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
261   // Determine the type of the literal.
262   QualType NumberType = Number->getType();
263   if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
264     // In C, character literals have type 'int'. That's not the type we want
265     // to use to determine the Objective-c literal kind.
266     switch (Char->getKind()) {
267     case CharacterLiteral::Ascii:
268       NumberType = Context.CharTy;
269       break;
270 
271     case CharacterLiteral::Wide:
272       NumberType = Context.getWideCharType();
273       break;
274 
275     case CharacterLiteral::UTF16:
276       NumberType = Context.Char16Ty;
277       break;
278 
279     case CharacterLiteral::UTF32:
280       NumberType = Context.Char32Ty;
281       break;
282     }
283   }
284 
285   // Look for the appropriate method within NSNumber.
286   // Construct the literal.
287   SourceRange NR(Number->getSourceRange());
288   ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
289                                                     true, NR);
290   if (!Method)
291     return ExprError();
292 
293   // Convert the number to the type that the parameter expects.
294   ParmVarDecl *ParamDecl = Method->param_begin()[0];
295   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
296                                                                     ParamDecl);
297   ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
298                                                          SourceLocation(),
299                                                          Owned(Number));
300   if (ConvertedNumber.isInvalid())
301     return ExprError();
302   Number = ConvertedNumber.get();
303 
304   // Use the effective source range of the literal, including the leading '@'.
305   return MaybeBindToTemporary(
306            new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
307                                        SourceRange(AtLoc, NR.getEnd())));
308 }
309 
310 ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
311                                       SourceLocation ValueLoc,
312                                       bool Value) {
313   ExprResult Inner;
314   if (getLangOpts().CPlusPlus) {
315     Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
316   } else {
317     // C doesn't actually have a way to represent literal values of type
318     // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
319     Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
320     Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
321                               CK_IntegralToBoolean);
322   }
323 
324   return BuildObjCNumericLiteral(AtLoc, Inner.get());
325 }
326 
327 /// \brief Check that the given expression is a valid element of an Objective-C
328 /// collection literal.
329 static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
330                                                     QualType T,
331                                                     bool ArrayLiteral = false) {
332   // If the expression is type-dependent, there's nothing for us to do.
333   if (Element->isTypeDependent())
334     return Element;
335 
336   ExprResult Result = S.CheckPlaceholderExpr(Element);
337   if (Result.isInvalid())
338     return ExprError();
339   Element = Result.get();
340 
341   // In C++, check for an implicit conversion to an Objective-C object pointer
342   // type.
343   if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
344     InitializedEntity Entity
345       = InitializedEntity::InitializeParameter(S.Context, T,
346                                                /*Consumed=*/false);
347     InitializationKind Kind
348       = InitializationKind::CreateCopy(Element->getLocStart(),
349                                        SourceLocation());
350     InitializationSequence Seq(S, Entity, Kind, Element);
351     if (!Seq.Failed())
352       return Seq.Perform(S, Entity, Kind, Element);
353   }
354 
355   Expr *OrigElement = Element;
356 
357   // Perform lvalue-to-rvalue conversion.
358   Result = S.DefaultLvalueConversion(Element);
359   if (Result.isInvalid())
360     return ExprError();
361   Element = Result.get();
362 
363   // Make sure that we have an Objective-C pointer type or block.
364   if (!Element->getType()->isObjCObjectPointerType() &&
365       !Element->getType()->isBlockPointerType()) {
366     bool Recovered = false;
367 
368     // If this is potentially an Objective-C numeric literal, add the '@'.
369     if (isa<IntegerLiteral>(OrigElement) ||
370         isa<CharacterLiteral>(OrigElement) ||
371         isa<FloatingLiteral>(OrigElement) ||
372         isa<ObjCBoolLiteralExpr>(OrigElement) ||
373         isa<CXXBoolLiteralExpr>(OrigElement)) {
374       if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
375         int Which = isa<CharacterLiteral>(OrigElement) ? 1
376                   : (isa<CXXBoolLiteralExpr>(OrigElement) ||
377                      isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
378                   : 3;
379 
380         S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
381           << Which << OrigElement->getSourceRange()
382           << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
383 
384         Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
385                                            OrigElement);
386         if (Result.isInvalid())
387           return ExprError();
388 
389         Element = Result.get();
390         Recovered = true;
391       }
392     }
393     // If this is potentially an Objective-C string literal, add the '@'.
394     else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
395       if (String->isAscii()) {
396         S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
397           << 0 << OrigElement->getSourceRange()
398           << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
399 
400         Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
401         if (Result.isInvalid())
402           return ExprError();
403 
404         Element = Result.get();
405         Recovered = true;
406       }
407     }
408 
409     if (!Recovered) {
410       S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
411         << Element->getType();
412       return ExprError();
413     }
414   }
415   if (ArrayLiteral)
416     if (ObjCStringLiteral *getString =
417           dyn_cast<ObjCStringLiteral>(OrigElement)) {
418       if (StringLiteral *SL = getString->getString()) {
419         unsigned numConcat = SL->getNumConcatenated();
420         if (numConcat > 1) {
421           // Only warn if the concatenated string doesn't come from a macro.
422           bool hasMacro = false;
423           for (unsigned i = 0; i < numConcat ; ++i)
424             if (SL->getStrTokenLoc(i).isMacroID()) {
425               hasMacro = true;
426               break;
427             }
428           if (!hasMacro)
429             S.Diag(Element->getLocStart(),
430                    diag::warn_concatenated_nsarray_literal)
431               << Element->getType();
432         }
433       }
434     }
435 
436   // Make sure that the element has the type that the container factory
437   // function expects.
438   return S.PerformCopyInitialization(
439            InitializedEntity::InitializeParameter(S.Context, T,
440                                                   /*Consumed=*/false),
441            Element->getLocStart(), Element);
442 }
443 
444 ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
445   if (ValueExpr->isTypeDependent()) {
446     ObjCBoxedExpr *BoxedExpr =
447       new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, NULL, SR);
448     return Owned(BoxedExpr);
449   }
450   ObjCMethodDecl *BoxingMethod = NULL;
451   QualType BoxedType;
452   // Convert the expression to an RValue, so we can check for pointer types...
453   ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
454   if (RValue.isInvalid()) {
455     return ExprError();
456   }
457   ValueExpr = RValue.get();
458   QualType ValueType(ValueExpr->getType());
459   if (const PointerType *PT = ValueType->getAs<PointerType>()) {
460     QualType PointeeType = PT->getPointeeType();
461     if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
462 
463       if (!NSStringDecl) {
464         IdentifierInfo *NSStringId =
465           NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
466         NamedDecl *Decl = LookupSingleName(TUScope, NSStringId,
467                                            SR.getBegin(), LookupOrdinaryName);
468         NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl);
469         if (!NSStringDecl) {
470           if (getLangOpts().DebuggerObjCLiteral) {
471             // Support boxed expressions in the debugger w/o NSString declaration.
472             DeclContext *TU = Context.getTranslationUnitDecl();
473             NSStringDecl = ObjCInterfaceDecl::Create(Context, TU,
474                                                      SourceLocation(),
475                                                      NSStringId,
476                                                      0, SourceLocation());
477           } else {
478             Diag(SR.getBegin(), diag::err_undeclared_nsstring);
479             return ExprError();
480           }
481         } else if (!NSStringDecl->hasDefinition()) {
482           Diag(SR.getBegin(), diag::err_undeclared_nsstring);
483           return ExprError();
484         }
485         assert(NSStringDecl && "NSStringDecl should not be NULL");
486         QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
487         NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
488       }
489 
490       if (!StringWithUTF8StringMethod) {
491         IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
492         Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
493 
494         // Look for the appropriate method within NSString.
495         BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
496         if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
497           // Debugger needs to work even if NSString hasn't been defined.
498           TypeSourceInfo *ReturnTInfo = 0;
499           ObjCMethodDecl *M = ObjCMethodDecl::Create(
500               Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
501               NSStringPointer, ReturnTInfo, NSStringDecl,
502               /*isInstance=*/false, /*isVariadic=*/false,
503               /*isPropertyAccessor=*/false,
504               /*isImplicitlyDeclared=*/true,
505               /*isDefined=*/false, ObjCMethodDecl::Required,
506               /*HasRelatedResultType=*/false);
507           QualType ConstCharType = Context.CharTy.withConst();
508           ParmVarDecl *value =
509             ParmVarDecl::Create(Context, M,
510                                 SourceLocation(), SourceLocation(),
511                                 &Context.Idents.get("value"),
512                                 Context.getPointerType(ConstCharType),
513                                 /*TInfo=*/0,
514                                 SC_None, 0);
515           M->setMethodParams(Context, value, None);
516           BoxingMethod = M;
517         }
518 
519         if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl,
520                                   stringWithUTF8String, BoxingMethod))
521            return ExprError();
522 
523         StringWithUTF8StringMethod = BoxingMethod;
524       }
525 
526       BoxingMethod = StringWithUTF8StringMethod;
527       BoxedType = NSStringPointer;
528     }
529   } else if (ValueType->isBuiltinType()) {
530     // The other types we support are numeric, char and BOOL/bool. We could also
531     // provide limited support for structure types, such as NSRange, NSRect, and
532     // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
533     // for more details.
534 
535     // Check for a top-level character literal.
536     if (const CharacterLiteral *Char =
537         dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
538       // In C, character literals have type 'int'. That's not the type we want
539       // to use to determine the Objective-c literal kind.
540       switch (Char->getKind()) {
541       case CharacterLiteral::Ascii:
542         ValueType = Context.CharTy;
543         break;
544 
545       case CharacterLiteral::Wide:
546         ValueType = Context.getWideCharType();
547         break;
548 
549       case CharacterLiteral::UTF16:
550         ValueType = Context.Char16Ty;
551         break;
552 
553       case CharacterLiteral::UTF32:
554         ValueType = Context.Char32Ty;
555         break;
556       }
557     }
558 
559     // FIXME:  Do I need to do anything special with BoolTy expressions?
560 
561     // Look for the appropriate method within NSNumber.
562     BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType);
563     BoxedType = NSNumberPointer;
564 
565   } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
566     if (!ET->getDecl()->isComplete()) {
567       Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type)
568         << ValueType << ValueExpr->getSourceRange();
569       return ExprError();
570     }
571 
572     BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(),
573                                             ET->getDecl()->getIntegerType());
574     BoxedType = NSNumberPointer;
575   }
576 
577   if (!BoxingMethod) {
578     Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type)
579       << ValueType << ValueExpr->getSourceRange();
580     return ExprError();
581   }
582 
583   // Convert the expression to the type that the parameter requires.
584   ParmVarDecl *ParamDecl = BoxingMethod->param_begin()[0];
585   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
586                                                                     ParamDecl);
587   ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity,
588                                                             SourceLocation(),
589                                                             Owned(ValueExpr));
590   if (ConvertedValueExpr.isInvalid())
591     return ExprError();
592   ValueExpr = ConvertedValueExpr.get();
593 
594   ObjCBoxedExpr *BoxedExpr =
595     new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
596                                       BoxingMethod, SR);
597   return MaybeBindToTemporary(BoxedExpr);
598 }
599 
600 /// Build an ObjC subscript pseudo-object expression, given that
601 /// that's supported by the runtime.
602 ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
603                                         Expr *IndexExpr,
604                                         ObjCMethodDecl *getterMethod,
605                                         ObjCMethodDecl *setterMethod) {
606   assert(!LangOpts.isSubscriptPointerArithmetic());
607 
608   // We can't get dependent types here; our callers should have
609   // filtered them out.
610   assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
611          "base or index cannot have dependent type here");
612 
613   // Filter out placeholders in the index.  In theory, overloads could
614   // be preserved here, although that might not actually work correctly.
615   ExprResult Result = CheckPlaceholderExpr(IndexExpr);
616   if (Result.isInvalid())
617     return ExprError();
618   IndexExpr = Result.get();
619 
620   // Perform lvalue-to-rvalue conversion on the base.
621   Result = DefaultLvalueConversion(BaseExpr);
622   if (Result.isInvalid())
623     return ExprError();
624   BaseExpr = Result.get();
625 
626   // Build the pseudo-object expression.
627   return Owned(ObjCSubscriptRefExpr::Create(Context,
628                                             BaseExpr,
629                                             IndexExpr,
630                                             Context.PseudoObjectTy,
631                                             getterMethod,
632                                             setterMethod, RB));
633 
634 }
635 
636 ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
637   // Look up the NSArray class, if we haven't done so already.
638   if (!NSArrayDecl) {
639     NamedDecl *IF = LookupSingleName(TUScope,
640                                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
641                                  SR.getBegin(),
642                                  LookupOrdinaryName);
643     NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
644     if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
645       NSArrayDecl =  ObjCInterfaceDecl::Create (Context,
646                             Context.getTranslationUnitDecl(),
647                             SourceLocation(),
648                             NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
649                             0, SourceLocation());
650 
651     if (!NSArrayDecl) {
652       Diag(SR.getBegin(), diag::err_undeclared_nsarray);
653       return ExprError();
654     }
655   }
656 
657   // Find the arrayWithObjects:count: method, if we haven't done so already.
658   QualType IdT = Context.getObjCIdType();
659   if (!ArrayWithObjectsMethod) {
660     Selector
661       Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
662     ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
663     if (!Method && getLangOpts().DebuggerObjCLiteral) {
664       TypeSourceInfo *ReturnTInfo = 0;
665       Method = ObjCMethodDecl::Create(
666           Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
667           Context.getTranslationUnitDecl(), false /*Instance*/,
668           false /*isVariadic*/,
669           /*isPropertyAccessor=*/false,
670           /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
671           ObjCMethodDecl::Required, false);
672       SmallVector<ParmVarDecl *, 2> Params;
673       ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
674                                                  SourceLocation(),
675                                                  SourceLocation(),
676                                                  &Context.Idents.get("objects"),
677                                                  Context.getPointerType(IdT),
678                                                  /*TInfo=*/0, SC_None, 0);
679       Params.push_back(objects);
680       ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
681                                              SourceLocation(),
682                                              SourceLocation(),
683                                              &Context.Idents.get("cnt"),
684                                              Context.UnsignedLongTy,
685                                              /*TInfo=*/0, SC_None, 0);
686       Params.push_back(cnt);
687       Method->setMethodParams(Context, Params, None);
688     }
689 
690     if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method))
691       return ExprError();
692 
693     // Dig out the type that all elements should be converted to.
694     QualType T = Method->param_begin()[0]->getType();
695     const PointerType *PtrT = T->getAs<PointerType>();
696     if (!PtrT ||
697         !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
698       Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
699         << Sel;
700       Diag(Method->param_begin()[0]->getLocation(),
701            diag::note_objc_literal_method_param)
702         << 0 << T
703         << Context.getPointerType(IdT.withConst());
704       return ExprError();
705     }
706 
707     // Check that the 'count' parameter is integral.
708     if (!Method->param_begin()[1]->getType()->isIntegerType()) {
709       Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
710         << Sel;
711       Diag(Method->param_begin()[1]->getLocation(),
712            diag::note_objc_literal_method_param)
713         << 1
714         << Method->param_begin()[1]->getType()
715         << "integral";
716       return ExprError();
717     }
718 
719     // We've found a good +arrayWithObjects:count: method. Save it!
720     ArrayWithObjectsMethod = Method;
721   }
722 
723   QualType ObjectsType = ArrayWithObjectsMethod->param_begin()[0]->getType();
724   QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
725 
726   // Check that each of the elements provided is valid in a collection literal,
727   // performing conversions as necessary.
728   Expr **ElementsBuffer = Elements.data();
729   for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
730     ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
731                                                              ElementsBuffer[I],
732                                                              RequiredType, true);
733     if (Converted.isInvalid())
734       return ExprError();
735 
736     ElementsBuffer[I] = Converted.get();
737   }
738 
739   QualType Ty
740     = Context.getObjCObjectPointerType(
741                                     Context.getObjCInterfaceType(NSArrayDecl));
742 
743   return MaybeBindToTemporary(
744            ObjCArrayLiteral::Create(Context, Elements, Ty,
745                                     ArrayWithObjectsMethod, SR));
746 }
747 
748 ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
749                                             ObjCDictionaryElement *Elements,
750                                             unsigned NumElements) {
751   // Look up the NSDictionary class, if we haven't done so already.
752   if (!NSDictionaryDecl) {
753     NamedDecl *IF = LookupSingleName(TUScope,
754                             NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
755                             SR.getBegin(), LookupOrdinaryName);
756     NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
757     if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
758       NSDictionaryDecl =  ObjCInterfaceDecl::Create (Context,
759                             Context.getTranslationUnitDecl(),
760                             SourceLocation(),
761                             NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
762                             0, SourceLocation());
763 
764     if (!NSDictionaryDecl) {
765       Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
766       return ExprError();
767     }
768   }
769 
770   // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
771   // so already.
772   QualType IdT = Context.getObjCIdType();
773   if (!DictionaryWithObjectsMethod) {
774     Selector Sel = NSAPIObj->getNSDictionarySelector(
775                                NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
776     ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
777     if (!Method && getLangOpts().DebuggerObjCLiteral) {
778       Method = ObjCMethodDecl::Create(Context,
779                            SourceLocation(), SourceLocation(), Sel,
780                            IdT,
781                            0 /*TypeSourceInfo */,
782                            Context.getTranslationUnitDecl(),
783                            false /*Instance*/, false/*isVariadic*/,
784                            /*isPropertyAccessor=*/false,
785                            /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
786                            ObjCMethodDecl::Required,
787                            false);
788       SmallVector<ParmVarDecl *, 3> Params;
789       ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
790                                                  SourceLocation(),
791                                                  SourceLocation(),
792                                                  &Context.Idents.get("objects"),
793                                                  Context.getPointerType(IdT),
794                                                  /*TInfo=*/0, SC_None, 0);
795       Params.push_back(objects);
796       ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
797                                               SourceLocation(),
798                                               SourceLocation(),
799                                               &Context.Idents.get("keys"),
800                                               Context.getPointerType(IdT),
801                                               /*TInfo=*/0, SC_None, 0);
802       Params.push_back(keys);
803       ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
804                                              SourceLocation(),
805                                              SourceLocation(),
806                                              &Context.Idents.get("cnt"),
807                                              Context.UnsignedLongTy,
808                                              /*TInfo=*/0, SC_None, 0);
809       Params.push_back(cnt);
810       Method->setMethodParams(Context, Params, None);
811     }
812 
813     if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
814                               Method))
815        return ExprError();
816 
817     // Dig out the type that all values should be converted to.
818     QualType ValueT = Method->param_begin()[0]->getType();
819     const PointerType *PtrValue = ValueT->getAs<PointerType>();
820     if (!PtrValue ||
821         !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
822       Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
823         << Sel;
824       Diag(Method->param_begin()[0]->getLocation(),
825            diag::note_objc_literal_method_param)
826         << 0 << ValueT
827         << Context.getPointerType(IdT.withConst());
828       return ExprError();
829     }
830 
831     // Dig out the type that all keys should be converted to.
832     QualType KeyT = Method->param_begin()[1]->getType();
833     const PointerType *PtrKey = KeyT->getAs<PointerType>();
834     if (!PtrKey ||
835         !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
836                                         IdT)) {
837       bool err = true;
838       if (PtrKey) {
839         if (QIDNSCopying.isNull()) {
840           // key argument of selector is id<NSCopying>?
841           if (ObjCProtocolDecl *NSCopyingPDecl =
842               LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
843             ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
844             QIDNSCopying =
845               Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
846                                         (ObjCProtocolDecl**) PQ,1);
847             QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
848           }
849         }
850         if (!QIDNSCopying.isNull())
851           err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
852                                                 QIDNSCopying);
853       }
854 
855       if (err) {
856         Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
857           << Sel;
858         Diag(Method->param_begin()[1]->getLocation(),
859              diag::note_objc_literal_method_param)
860           << 1 << KeyT
861           << Context.getPointerType(IdT.withConst());
862         return ExprError();
863       }
864     }
865 
866     // Check that the 'count' parameter is integral.
867     QualType CountType = Method->param_begin()[2]->getType();
868     if (!CountType->isIntegerType()) {
869       Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
870         << Sel;
871       Diag(Method->param_begin()[2]->getLocation(),
872            diag::note_objc_literal_method_param)
873         << 2 << CountType
874         << "integral";
875       return ExprError();
876     }
877 
878     // We've found a good +dictionaryWithObjects:keys:count: method; save it!
879     DictionaryWithObjectsMethod = Method;
880   }
881 
882   QualType ValuesT = DictionaryWithObjectsMethod->param_begin()[0]->getType();
883   QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
884   QualType KeysT = DictionaryWithObjectsMethod->param_begin()[1]->getType();
885   QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
886 
887   // Check that each of the keys and values provided is valid in a collection
888   // literal, performing conversions as necessary.
889   bool HasPackExpansions = false;
890   for (unsigned I = 0, N = NumElements; I != N; ++I) {
891     // Check the key.
892     ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
893                                                        KeyT);
894     if (Key.isInvalid())
895       return ExprError();
896 
897     // Check the value.
898     ExprResult Value
899       = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
900     if (Value.isInvalid())
901       return ExprError();
902 
903     Elements[I].Key = Key.get();
904     Elements[I].Value = Value.get();
905 
906     if (Elements[I].EllipsisLoc.isInvalid())
907       continue;
908 
909     if (!Elements[I].Key->containsUnexpandedParameterPack() &&
910         !Elements[I].Value->containsUnexpandedParameterPack()) {
911       Diag(Elements[I].EllipsisLoc,
912            diag::err_pack_expansion_without_parameter_packs)
913         << SourceRange(Elements[I].Key->getLocStart(),
914                        Elements[I].Value->getLocEnd());
915       return ExprError();
916     }
917 
918     HasPackExpansions = true;
919   }
920 
921 
922   QualType Ty
923     = Context.getObjCObjectPointerType(
924                                 Context.getObjCInterfaceType(NSDictionaryDecl));
925   return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
926       Context, makeArrayRef(Elements, NumElements), HasPackExpansions, Ty,
927       DictionaryWithObjectsMethod, SR));
928 }
929 
930 ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
931                                       TypeSourceInfo *EncodedTypeInfo,
932                                       SourceLocation RParenLoc) {
933   QualType EncodedType = EncodedTypeInfo->getType();
934   QualType StrTy;
935   if (EncodedType->isDependentType())
936     StrTy = Context.DependentTy;
937   else {
938     if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
939         !EncodedType->isVoidType()) // void is handled too.
940       if (RequireCompleteType(AtLoc, EncodedType,
941                               diag::err_incomplete_type_objc_at_encode,
942                               EncodedTypeInfo->getTypeLoc()))
943         return ExprError();
944 
945     std::string Str;
946     Context.getObjCEncodingForType(EncodedType, Str);
947 
948     // The type of @encode is the same as the type of the corresponding string,
949     // which is an array type.
950     StrTy = Context.CharTy;
951     // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
952     if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
953       StrTy.addConst();
954     StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
955                                          ArrayType::Normal, 0);
956   }
957 
958   return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
959 }
960 
961 ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
962                                            SourceLocation EncodeLoc,
963                                            SourceLocation LParenLoc,
964                                            ParsedType ty,
965                                            SourceLocation RParenLoc) {
966   // FIXME: Preserve type source info ?
967   TypeSourceInfo *TInfo;
968   QualType EncodedType = GetTypeFromParser(ty, &TInfo);
969   if (!TInfo)
970     TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
971                                              PP.getLocForEndOfToken(LParenLoc));
972 
973   return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
974 }
975 
976 static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
977                                                SourceLocation AtLoc,
978                                                ObjCMethodDecl *Method,
979                                                ObjCMethodList &MethList) {
980   ObjCMethodList *M = &MethList;
981   bool Warned = false;
982   for (M = M->getNext(); M; M=M->getNext()) {
983     ObjCMethodDecl *MatchingMethodDecl = M->Method;
984     if (MatchingMethodDecl == Method ||
985         isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
986         MatchingMethodDecl->getSelector() != Method->getSelector())
987       continue;
988     if (!S.MatchTwoMethodDeclarations(Method,
989                                       MatchingMethodDecl, Sema::MMS_loose)) {
990       if (!Warned) {
991         Warned = true;
992         S.Diag(AtLoc, diag::warning_multiple_selectors)
993           << Method->getSelector();
994         S.Diag(Method->getLocation(), diag::note_method_declared_at)
995           << Method->getDeclName();
996       }
997       S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
998         << MatchingMethodDecl->getDeclName();
999     }
1000   }
1001   return Warned;
1002 }
1003 
1004 static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
1005                                         ObjCMethodDecl *Method) {
1006   if (S.Diags.getDiagnosticLevel(diag::warning_multiple_selectors,
1007                                  SourceLocation())
1008         == DiagnosticsEngine::Ignored)
1009     return;
1010   bool Warned = false;
1011   for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1012        e = S.MethodPool.end(); b != e; b++) {
1013     // first, instance methods
1014     ObjCMethodList &InstMethList = b->second.first;
1015     if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc,
1016                                                       Method, InstMethList))
1017       Warned = true;
1018 
1019     // second, class methods
1020     ObjCMethodList &ClsMethList = b->second.second;
1021     if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc,
1022                                                       Method, ClsMethList) ||
1023         Warned)
1024       return;
1025   }
1026 }
1027 
1028 ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1029                                              SourceLocation AtLoc,
1030                                              SourceLocation SelLoc,
1031                                              SourceLocation LParenLoc,
1032                                              SourceLocation RParenLoc) {
1033   ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
1034                              SourceRange(LParenLoc, RParenLoc), false, false);
1035   if (!Method)
1036     Method = LookupFactoryMethodInGlobalPool(Sel,
1037                                           SourceRange(LParenLoc, RParenLoc));
1038   if (!Method) {
1039     if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1040       Selector MatchedSel = OM->getSelector();
1041       SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1042                                 RParenLoc.getLocWithOffset(-1));
1043       Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1044         << Sel << MatchedSel
1045         << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1046 
1047     } else
1048         Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
1049   } else
1050     DiagnoseMismatchedSelectors(*this, AtLoc, Method);
1051 
1052   if (!Method ||
1053       Method->getImplementationControl() != ObjCMethodDecl::Optional) {
1054     llvm::DenseMap<Selector, SourceLocation>::iterator Pos
1055       = ReferencedSelectors.find(Sel);
1056     if (Pos == ReferencedSelectors.end())
1057       ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
1058   }
1059 
1060   // In ARC, forbid the user from using @selector for
1061   // retain/release/autorelease/dealloc/retainCount.
1062   if (getLangOpts().ObjCAutoRefCount) {
1063     switch (Sel.getMethodFamily()) {
1064     case OMF_retain:
1065     case OMF_release:
1066     case OMF_autorelease:
1067     case OMF_retainCount:
1068     case OMF_dealloc:
1069       Diag(AtLoc, diag::err_arc_illegal_selector) <<
1070         Sel << SourceRange(LParenLoc, RParenLoc);
1071       break;
1072 
1073     case OMF_None:
1074     case OMF_alloc:
1075     case OMF_copy:
1076     case OMF_finalize:
1077     case OMF_init:
1078     case OMF_mutableCopy:
1079     case OMF_new:
1080     case OMF_self:
1081     case OMF_performSelector:
1082       break;
1083     }
1084   }
1085   QualType Ty = Context.getObjCSelType();
1086   return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
1087 }
1088 
1089 ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1090                                              SourceLocation AtLoc,
1091                                              SourceLocation ProtoLoc,
1092                                              SourceLocation LParenLoc,
1093                                              SourceLocation ProtoIdLoc,
1094                                              SourceLocation RParenLoc) {
1095   ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
1096   if (!PDecl) {
1097     Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
1098     return true;
1099   }
1100 
1101   QualType Ty = Context.getObjCProtoType();
1102   if (Ty.isNull())
1103     return true;
1104   Ty = Context.getObjCObjectPointerType(Ty);
1105   return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
1106 }
1107 
1108 /// Try to capture an implicit reference to 'self'.
1109 ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1110   DeclContext *DC = getFunctionLevelDeclContext();
1111 
1112   // If we're not in an ObjC method, error out.  Note that, unlike the
1113   // C++ case, we don't require an instance method --- class methods
1114   // still have a 'self', and we really do still need to capture it!
1115   ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1116   if (!method)
1117     return 0;
1118 
1119   tryCaptureVariable(method->getSelfDecl(), Loc);
1120 
1121   return method;
1122 }
1123 
1124 static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1125   if (T == Context.getObjCInstanceType())
1126     return Context.getObjCIdType();
1127 
1128   return T;
1129 }
1130 
1131 QualType Sema::getMessageSendResultType(QualType ReceiverType,
1132                                         ObjCMethodDecl *Method,
1133                                     bool isClassMessage, bool isSuperMessage) {
1134   assert(Method && "Must have a method");
1135   if (!Method->hasRelatedResultType())
1136     return Method->getSendResultType();
1137 
1138   // If a method has a related return type:
1139   //   - if the method found is an instance method, but the message send
1140   //     was a class message send, T is the declared return type of the method
1141   //     found
1142   if (Method->isInstanceMethod() && isClassMessage)
1143     return stripObjCInstanceType(Context, Method->getSendResultType());
1144 
1145   //   - if the receiver is super, T is a pointer to the class of the
1146   //     enclosing method definition
1147   if (isSuperMessage) {
1148     if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
1149       if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
1150         return Context.getObjCObjectPointerType(
1151                                         Context.getObjCInterfaceType(Class));
1152   }
1153 
1154   //   - if the receiver is the name of a class U, T is a pointer to U
1155   if (ReceiverType->getAs<ObjCInterfaceType>() ||
1156       ReceiverType->isObjCQualifiedInterfaceType())
1157     return Context.getObjCObjectPointerType(ReceiverType);
1158   //   - if the receiver is of type Class or qualified Class type,
1159   //     T is the declared return type of the method.
1160   if (ReceiverType->isObjCClassType() ||
1161       ReceiverType->isObjCQualifiedClassType())
1162     return stripObjCInstanceType(Context, Method->getSendResultType());
1163 
1164   //   - if the receiver is id, qualified id, Class, or qualified Class, T
1165   //     is the receiver type, otherwise
1166   //   - T is the type of the receiver expression.
1167   return ReceiverType;
1168 }
1169 
1170 /// Look for an ObjC method whose result type exactly matches the given type.
1171 static const ObjCMethodDecl *
1172 findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1173                                  QualType instancetype) {
1174   if (MD->getReturnType() == instancetype)
1175     return MD;
1176 
1177   // For these purposes, a method in an @implementation overrides a
1178   // declaration in the @interface.
1179   if (const ObjCImplDecl *impl =
1180         dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1181     const ObjCContainerDecl *iface;
1182     if (const ObjCCategoryImplDecl *catImpl =
1183           dyn_cast<ObjCCategoryImplDecl>(impl)) {
1184       iface = catImpl->getCategoryDecl();
1185     } else {
1186       iface = impl->getClassInterface();
1187     }
1188 
1189     const ObjCMethodDecl *ifaceMD =
1190       iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1191     if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1192   }
1193 
1194   SmallVector<const ObjCMethodDecl *, 4> overrides;
1195   MD->getOverriddenMethods(overrides);
1196   for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1197     if (const ObjCMethodDecl *result =
1198           findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1199       return result;
1200   }
1201 
1202   return 0;
1203 }
1204 
1205 void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1206   // Only complain if we're in an ObjC method and the required return
1207   // type doesn't match the method's declared return type.
1208   ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1209   if (!MD || !MD->hasRelatedResultType() ||
1210       Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
1211     return;
1212 
1213   // Look for a method overridden by this method which explicitly uses
1214   // 'instancetype'.
1215   if (const ObjCMethodDecl *overridden =
1216         findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
1217     SourceLocation loc;
1218     SourceRange range;
1219     if (TypeSourceInfo *TSI = overridden->getReturnTypeSourceInfo()) {
1220       range = TSI->getTypeLoc().getSourceRange();
1221       loc = range.getBegin();
1222     }
1223     if (loc.isInvalid())
1224       loc = overridden->getLocation();
1225     Diag(loc, diag::note_related_result_type_explicit)
1226       << /*current method*/ 1 << range;
1227     return;
1228   }
1229 
1230   // Otherwise, if we have an interesting method family, note that.
1231   // This should always trigger if the above didn't.
1232   if (ObjCMethodFamily family = MD->getMethodFamily())
1233     Diag(MD->getLocation(), diag::note_related_result_type_family)
1234       << /*current method*/ 1
1235       << family;
1236 }
1237 
1238 void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1239   E = E->IgnoreParenImpCasts();
1240   const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1241   if (!MsgSend)
1242     return;
1243 
1244   const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1245   if (!Method)
1246     return;
1247 
1248   if (!Method->hasRelatedResultType())
1249     return;
1250 
1251   if (Context.hasSameUnqualifiedType(
1252           Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
1253     return;
1254 
1255   if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
1256                                       Context.getObjCInstanceType()))
1257     return;
1258 
1259   Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1260     << Method->isInstanceMethod() << Method->getSelector()
1261     << MsgSend->getType();
1262 }
1263 
1264 bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
1265                                      MultiExprArg Args,
1266                                      Selector Sel,
1267                                      ArrayRef<SourceLocation> SelectorLocs,
1268                                      ObjCMethodDecl *Method,
1269                                      bool isClassMessage, bool isSuperMessage,
1270                                      SourceLocation lbrac, SourceLocation rbrac,
1271                                      QualType &ReturnType, ExprValueKind &VK) {
1272   SourceLocation SelLoc;
1273   if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1274     SelLoc = SelectorLocs.front();
1275   else
1276     SelLoc = lbrac;
1277 
1278   if (!Method) {
1279     // Apply default argument promotion as for (C99 6.5.2.2p6).
1280     for (unsigned i = 0, e = Args.size(); i != e; i++) {
1281       if (Args[i]->isTypeDependent())
1282         continue;
1283 
1284       ExprResult result;
1285       if (getLangOpts().DebuggerSupport) {
1286         QualType paramTy; // ignored
1287         result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
1288       } else {
1289         result = DefaultArgumentPromotion(Args[i]);
1290       }
1291       if (result.isInvalid())
1292         return true;
1293       Args[i] = result.take();
1294     }
1295 
1296     unsigned DiagID;
1297     if (getLangOpts().ObjCAutoRefCount)
1298       DiagID = diag::err_arc_method_not_found;
1299     else
1300       DiagID = isClassMessage ? diag::warn_class_method_not_found
1301                               : diag::warn_inst_method_not_found;
1302     if (!getLangOpts().DebuggerSupport) {
1303       const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
1304       if (OMD && !OMD->isInvalidDecl()) {
1305         if (getLangOpts().ObjCAutoRefCount)
1306           DiagID = diag::error_method_not_found_with_typo;
1307         else
1308           DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1309                                   : diag::warn_instance_method_not_found_with_typo;
1310         Selector MatchedSel = OMD->getSelector();
1311         SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
1312         Diag(SelLoc, DiagID)
1313           << Sel<< isClassMessage << MatchedSel
1314           << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1315       }
1316       else
1317         Diag(SelLoc, DiagID)
1318           << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
1319                                                 SelectorLocs.back());
1320       // Find the class to which we are sending this message.
1321       if (ReceiverType->isObjCObjectPointerType()) {
1322         if (ObjCInterfaceDecl *Class =
1323               ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl())
1324           Diag(Class->getLocation(), diag::note_receiver_class_declared);
1325       }
1326     }
1327 
1328     // In debuggers, we want to use __unknown_anytype for these
1329     // results so that clients can cast them.
1330     if (getLangOpts().DebuggerSupport) {
1331       ReturnType = Context.UnknownAnyTy;
1332     } else {
1333       ReturnType = Context.getObjCIdType();
1334     }
1335     VK = VK_RValue;
1336     return false;
1337   }
1338 
1339   ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1340                                         isSuperMessage);
1341   VK = Expr::getValueKindForType(Method->getReturnType());
1342 
1343   unsigned NumNamedArgs = Sel.getNumArgs();
1344   // Method might have more arguments than selector indicates. This is due
1345   // to addition of c-style arguments in method.
1346   if (Method->param_size() > Sel.getNumArgs())
1347     NumNamedArgs = Method->param_size();
1348   // FIXME. This need be cleaned up.
1349   if (Args.size() < NumNamedArgs) {
1350     Diag(SelLoc, diag::err_typecheck_call_too_few_args)
1351       << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
1352     return false;
1353   }
1354 
1355   bool IsError = false;
1356   for (unsigned i = 0; i < NumNamedArgs; i++) {
1357     // We can't do any type-checking on a type-dependent argument.
1358     if (Args[i]->isTypeDependent())
1359       continue;
1360 
1361     Expr *argExpr = Args[i];
1362 
1363     ParmVarDecl *param = Method->param_begin()[i];
1364     assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
1365 
1366     // Strip the unbridged-cast placeholder expression off unless it's
1367     // a consumed argument.
1368     if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1369         !param->hasAttr<CFConsumedAttr>())
1370       argExpr = stripARCUnbridgedCast(argExpr);
1371 
1372     // If the parameter is __unknown_anytype, infer its type
1373     // from the argument.
1374     if (param->getType() == Context.UnknownAnyTy) {
1375       QualType paramType;
1376       ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
1377       if (argE.isInvalid()) {
1378         IsError = true;
1379       } else {
1380         Args[i] = argE.take();
1381 
1382         // Update the parameter type in-place.
1383         param->setType(paramType);
1384       }
1385       continue;
1386     }
1387 
1388     if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
1389                             param->getType(),
1390                             diag::err_call_incomplete_argument, argExpr))
1391       return true;
1392 
1393     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1394                                                                       param);
1395     ExprResult ArgE = PerformCopyInitialization(Entity, SelLoc, Owned(argExpr));
1396     if (ArgE.isInvalid())
1397       IsError = true;
1398     else
1399       Args[i] = ArgE.takeAs<Expr>();
1400   }
1401 
1402   // Promote additional arguments to variadic methods.
1403   if (Method->isVariadic()) {
1404     for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
1405       if (Args[i]->isTypeDependent())
1406         continue;
1407 
1408       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
1409                                                         0);
1410       IsError |= Arg.isInvalid();
1411       Args[i] = Arg.take();
1412     }
1413   } else {
1414     // Check for extra arguments to non-variadic methods.
1415     if (Args.size() != NumNamedArgs) {
1416       Diag(Args[NumNamedArgs]->getLocStart(),
1417            diag::err_typecheck_call_too_many_args)
1418         << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
1419         << Method->getSourceRange()
1420         << SourceRange(Args[NumNamedArgs]->getLocStart(),
1421                        Args.back()->getLocEnd());
1422     }
1423   }
1424 
1425   DiagnoseSentinelCalls(Method, SelLoc, Args);
1426 
1427   // Do additional checkings on method.
1428   IsError |= CheckObjCMethodCall(
1429       Method, SelLoc, makeArrayRef<const Expr *>(Args.data(), Args.size()));
1430 
1431   return IsError;
1432 }
1433 
1434 bool Sema::isSelfExpr(Expr *RExpr) {
1435   // 'self' is objc 'self' in an objc method only.
1436   ObjCMethodDecl *Method =
1437       dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1438   return isSelfExpr(RExpr, Method);
1439 }
1440 
1441 bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
1442   if (!method) return false;
1443 
1444   receiver = receiver->IgnoreParenLValueCasts();
1445   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
1446     if (DRE->getDecl() == method->getSelfDecl())
1447       return true;
1448   return false;
1449 }
1450 
1451 /// LookupMethodInType - Look up a method in an ObjCObjectType.
1452 ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1453                                                bool isInstance) {
1454   const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1455   if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1456     // Look it up in the main interface (and categories, etc.)
1457     if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1458       return method;
1459 
1460     // Okay, look for "private" methods declared in any
1461     // @implementations we've seen.
1462     if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1463       return method;
1464   }
1465 
1466   // Check qualifiers.
1467   for (const auto *I : objType->quals())
1468     if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
1469       return method;
1470 
1471   return 0;
1472 }
1473 
1474 /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1475 /// list of a qualified objective pointer type.
1476 ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1477                                               const ObjCObjectPointerType *OPT,
1478                                               bool Instance)
1479 {
1480   ObjCMethodDecl *MD = 0;
1481   for (const auto *PROTO : OPT->quals()) {
1482     if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1483       return MD;
1484     }
1485   }
1486   return 0;
1487 }
1488 
1489 static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) {
1490   if (!Receiver)
1491     return;
1492 
1493   if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Receiver))
1494     Receiver = OVE->getSourceExpr();
1495 
1496   Expr *RExpr = Receiver->IgnoreParenImpCasts();
1497   SourceLocation Loc = RExpr->getLocStart();
1498   QualType T = RExpr->getType();
1499   const ObjCPropertyDecl *PDecl = 0;
1500   const ObjCMethodDecl *GDecl = 0;
1501   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) {
1502     RExpr = POE->getSyntacticForm();
1503     if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) {
1504       if (PRE->isImplicitProperty()) {
1505         GDecl = PRE->getImplicitPropertyGetter();
1506         if (GDecl) {
1507           T = GDecl->getReturnType();
1508         }
1509       }
1510       else {
1511         PDecl = PRE->getExplicitProperty();
1512         if (PDecl) {
1513           T = PDecl->getType();
1514         }
1515       }
1516     }
1517   }
1518   else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RExpr)) {
1519     // See if receiver is a method which envokes a synthesized getter
1520     // backing a 'weak' property.
1521     ObjCMethodDecl *Method = ME->getMethodDecl();
1522     if (Method && Method->getSelector().getNumArgs() == 0) {
1523       PDecl = Method->findPropertyDecl();
1524       if (PDecl)
1525         T = PDecl->getType();
1526     }
1527   }
1528 
1529   if (T.getObjCLifetime() != Qualifiers::OCL_Weak) {
1530     if (!PDecl)
1531       return;
1532     if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak))
1533       return;
1534   }
1535 
1536   S.Diag(Loc, diag::warn_receiver_is_weak)
1537     << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2));
1538 
1539   if (PDecl)
1540     S.Diag(PDecl->getLocation(), diag::note_property_declare);
1541   else if (GDecl)
1542     S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl;
1543 
1544   S.Diag(Loc, diag::note_arc_assign_to_strong);
1545 }
1546 
1547 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1548 /// objective C interface.  This is a property reference expression.
1549 ExprResult Sema::
1550 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
1551                           Expr *BaseExpr, SourceLocation OpLoc,
1552                           DeclarationName MemberName,
1553                           SourceLocation MemberLoc,
1554                           SourceLocation SuperLoc, QualType SuperType,
1555                           bool Super) {
1556   const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1557   ObjCInterfaceDecl *IFace = IFaceT->getDecl();
1558 
1559   if (!MemberName.isIdentifier()) {
1560     Diag(MemberLoc, diag::err_invalid_property_name)
1561       << MemberName << QualType(OPT, 0);
1562     return ExprError();
1563   }
1564 
1565   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1566 
1567   SourceRange BaseRange = Super? SourceRange(SuperLoc)
1568                                : BaseExpr->getSourceRange();
1569   if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
1570                           diag::err_property_not_found_forward_class,
1571                           MemberName, BaseRange))
1572     return ExprError();
1573 
1574   // Search for a declared property first.
1575   if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
1576     // Check whether we can reference this property.
1577     if (DiagnoseUseOfDecl(PD, MemberLoc))
1578       return ExprError();
1579     if (Super)
1580       return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
1581                                                      VK_LValue, OK_ObjCProperty,
1582                                                      MemberLoc,
1583                                                      SuperLoc, SuperType));
1584     else
1585       return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
1586                                                      VK_LValue, OK_ObjCProperty,
1587                                                      MemberLoc, BaseExpr));
1588   }
1589   // Check protocols on qualified interfaces.
1590   for (const auto *I : OPT->quals())
1591     if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
1592       // Check whether we can reference this property.
1593       if (DiagnoseUseOfDecl(PD, MemberLoc))
1594         return ExprError();
1595 
1596       if (Super)
1597         return Owned(new (Context) ObjCPropertyRefExpr(PD,
1598                                                        Context.PseudoObjectTy,
1599                                                        VK_LValue,
1600                                                        OK_ObjCProperty,
1601                                                        MemberLoc,
1602                                                        SuperLoc, SuperType));
1603       else
1604         return Owned(new (Context) ObjCPropertyRefExpr(PD,
1605                                                        Context.PseudoObjectTy,
1606                                                        VK_LValue,
1607                                                        OK_ObjCProperty,
1608                                                        MemberLoc,
1609                                                        BaseExpr));
1610     }
1611   // If that failed, look for an "implicit" property by seeing if the nullary
1612   // selector is implemented.
1613 
1614   // FIXME: The logic for looking up nullary and unary selectors should be
1615   // shared with the code in ActOnInstanceMessage.
1616 
1617   Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1618   ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1619 
1620   // May be founf in property's qualified list.
1621   if (!Getter)
1622     Getter = LookupMethodInQualifiedType(Sel, OPT, true);
1623 
1624   // If this reference is in an @implementation, check for 'private' methods.
1625   if (!Getter)
1626     Getter = IFace->lookupPrivateMethod(Sel);
1627 
1628   if (Getter) {
1629     // Check if we can reference this property.
1630     if (DiagnoseUseOfDecl(Getter, MemberLoc))
1631       return ExprError();
1632   }
1633   // If we found a getter then this may be a valid dot-reference, we
1634   // will look for the matching setter, in case it is needed.
1635   Selector SetterSel =
1636     SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1637                                            PP.getSelectorTable(), Member);
1638   ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1639 
1640   // May be founf in property's qualified list.
1641   if (!Setter)
1642     Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1643 
1644   if (!Setter) {
1645     // If this reference is in an @implementation, also check for 'private'
1646     // methods.
1647     Setter = IFace->lookupPrivateMethod(SetterSel);
1648   }
1649 
1650   if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1651     return ExprError();
1652 
1653   if (Getter || Setter) {
1654     if (Super)
1655       return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1656                                                      Context.PseudoObjectTy,
1657                                                      VK_LValue, OK_ObjCProperty,
1658                                                      MemberLoc,
1659                                                      SuperLoc, SuperType));
1660     else
1661       return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1662                                                      Context.PseudoObjectTy,
1663                                                      VK_LValue, OK_ObjCProperty,
1664                                                      MemberLoc, BaseExpr));
1665 
1666   }
1667 
1668   // Attempt to correct for typos in property names.
1669   DeclFilterCCC<ObjCPropertyDecl> Validator;
1670   if (TypoCorrection Corrected = CorrectTypo(
1671           DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
1672           NULL, Validator, CTK_ErrorRecovery, IFace, false, OPT)) {
1673     diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1674                               << MemberName << QualType(OPT, 0));
1675     DeclarationName TypoResult = Corrected.getCorrection();
1676     return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1677                                      TypoResult, MemberLoc,
1678                                      SuperLoc, SuperType, Super);
1679   }
1680   ObjCInterfaceDecl *ClassDeclared;
1681   if (ObjCIvarDecl *Ivar =
1682       IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1683     QualType T = Ivar->getType();
1684     if (const ObjCObjectPointerType * OBJPT =
1685         T->getAsObjCInterfacePointerType()) {
1686       if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
1687                               diag::err_property_not_as_forward_class,
1688                               MemberName, BaseExpr))
1689         return ExprError();
1690     }
1691     Diag(MemberLoc,
1692          diag::err_ivar_access_using_property_syntax_suggest)
1693     << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1694     << FixItHint::CreateReplacement(OpLoc, "->");
1695     return ExprError();
1696   }
1697 
1698   Diag(MemberLoc, diag::err_property_not_found)
1699     << MemberName << QualType(OPT, 0);
1700   if (Setter)
1701     Diag(Setter->getLocation(), diag::note_getter_unavailable)
1702           << MemberName << BaseExpr->getSourceRange();
1703   return ExprError();
1704 }
1705 
1706 
1707 
1708 ExprResult Sema::
1709 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1710                           IdentifierInfo &propertyName,
1711                           SourceLocation receiverNameLoc,
1712                           SourceLocation propertyNameLoc) {
1713 
1714   IdentifierInfo *receiverNamePtr = &receiverName;
1715   ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1716                                                   receiverNameLoc);
1717 
1718   bool IsSuper = false;
1719   if (IFace == 0) {
1720     // If the "receiver" is 'super' in a method, handle it as an expression-like
1721     // property reference.
1722     if (receiverNamePtr->isStr("super")) {
1723       IsSuper = true;
1724 
1725       if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
1726         if (CurMethod->isInstanceMethod()) {
1727           ObjCInterfaceDecl *Super =
1728             CurMethod->getClassInterface()->getSuperClass();
1729           if (!Super) {
1730             // The current class does not have a superclass.
1731             Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
1732             << CurMethod->getClassInterface()->getIdentifier();
1733             return ExprError();
1734           }
1735           QualType T = Context.getObjCInterfaceType(Super);
1736           T = Context.getObjCObjectPointerType(T);
1737 
1738           return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
1739                                            /*BaseExpr*/0,
1740                                            SourceLocation()/*OpLoc*/,
1741                                            &propertyName,
1742                                            propertyNameLoc,
1743                                            receiverNameLoc, T, true);
1744         }
1745 
1746         // Otherwise, if this is a class method, try dispatching to our
1747         // superclass.
1748         IFace = CurMethod->getClassInterface()->getSuperClass();
1749       }
1750     }
1751 
1752     if (IFace == 0) {
1753       Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
1754                                                        << tok::l_paren;
1755       return ExprError();
1756     }
1757   }
1758 
1759   // Search for a declared property first.
1760   Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
1761   ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
1762 
1763   // If this reference is in an @implementation, check for 'private' methods.
1764   if (!Getter)
1765     Getter = IFace->lookupPrivateClassMethod(Sel);
1766 
1767   if (Getter) {
1768     // FIXME: refactor/share with ActOnMemberReference().
1769     // Check if we can reference this property.
1770     if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1771       return ExprError();
1772   }
1773 
1774   // Look for the matching setter, in case it is needed.
1775   Selector SetterSel =
1776     SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1777                                            PP.getSelectorTable(),
1778                                            &propertyName);
1779 
1780   ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1781   if (!Setter) {
1782     // If this reference is in an @implementation, also check for 'private'
1783     // methods.
1784     Setter = IFace->lookupPrivateClassMethod(SetterSel);
1785   }
1786   // Look through local category implementations associated with the class.
1787   if (!Setter)
1788     Setter = IFace->getCategoryClassMethod(SetterSel);
1789 
1790   if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1791     return ExprError();
1792 
1793   if (Getter || Setter) {
1794     if (IsSuper)
1795     return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1796                                                    Context.PseudoObjectTy,
1797                                                    VK_LValue, OK_ObjCProperty,
1798                                                    propertyNameLoc,
1799                                                    receiverNameLoc,
1800                                           Context.getObjCInterfaceType(IFace)));
1801 
1802     return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1803                                                    Context.PseudoObjectTy,
1804                                                    VK_LValue, OK_ObjCProperty,
1805                                                    propertyNameLoc,
1806                                                    receiverNameLoc, IFace));
1807   }
1808   return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1809                      << &propertyName << Context.getObjCInterfaceType(IFace));
1810 }
1811 
1812 namespace {
1813 
1814 class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1815  public:
1816   ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1817     // Determine whether "super" is acceptable in the current context.
1818     if (Method && Method->getClassInterface())
1819       WantObjCSuper = Method->getClassInterface()->getSuperClass();
1820   }
1821 
1822   bool ValidateCandidate(const TypoCorrection &candidate) override {
1823     return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1824         candidate.isKeyword("super");
1825   }
1826 };
1827 
1828 }
1829 
1830 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
1831                                                IdentifierInfo *Name,
1832                                                SourceLocation NameLoc,
1833                                                bool IsSuper,
1834                                                bool HasTrailingDot,
1835                                                ParsedType &ReceiverType) {
1836   ReceiverType = ParsedType();
1837 
1838   // If the identifier is "super" and there is no trailing dot, we're
1839   // messaging super. If the identifier is "super" and there is a
1840   // trailing dot, it's an instance message.
1841   if (IsSuper && S->isInObjcMethodScope())
1842     return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
1843 
1844   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1845   LookupName(Result, S);
1846 
1847   switch (Result.getResultKind()) {
1848   case LookupResult::NotFound:
1849     // Normal name lookup didn't find anything. If we're in an
1850     // Objective-C method, look for ivars. If we find one, we're done!
1851     // FIXME: This is a hack. Ivar lookup should be part of normal
1852     // lookup.
1853     if (ObjCMethodDecl *Method = getCurMethodDecl()) {
1854       if (!Method->getClassInterface()) {
1855         // Fall back: let the parser try to parse it as an instance message.
1856         return ObjCInstanceMessage;
1857       }
1858 
1859       ObjCInterfaceDecl *ClassDeclared;
1860       if (Method->getClassInterface()->lookupInstanceVariable(Name,
1861                                                               ClassDeclared))
1862         return ObjCInstanceMessage;
1863     }
1864 
1865     // Break out; we'll perform typo correction below.
1866     break;
1867 
1868   case LookupResult::NotFoundInCurrentInstantiation:
1869   case LookupResult::FoundOverloaded:
1870   case LookupResult::FoundUnresolvedValue:
1871   case LookupResult::Ambiguous:
1872     Result.suppressDiagnostics();
1873     return ObjCInstanceMessage;
1874 
1875   case LookupResult::Found: {
1876     // If the identifier is a class or not, and there is a trailing dot,
1877     // it's an instance message.
1878     if (HasTrailingDot)
1879       return ObjCInstanceMessage;
1880     // We found something. If it's a type, then we have a class
1881     // message. Otherwise, it's an instance message.
1882     NamedDecl *ND = Result.getFoundDecl();
1883     QualType T;
1884     if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1885       T = Context.getObjCInterfaceType(Class);
1886     else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
1887       T = Context.getTypeDeclType(Type);
1888       DiagnoseUseOfDecl(Type, NameLoc);
1889     }
1890     else
1891       return ObjCInstanceMessage;
1892 
1893     //  We have a class message, and T is the type we're
1894     //  messaging. Build source-location information for it.
1895     TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1896     ReceiverType = CreateParsedType(T, TSInfo);
1897     return ObjCClassMessage;
1898   }
1899   }
1900 
1901   ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
1902   if (TypoCorrection Corrected =
1903           CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1904                       NULL, Validator, CTK_ErrorRecovery, NULL, false, NULL,
1905                       false)) {
1906     if (Corrected.isKeyword()) {
1907       // If we've found the keyword "super" (the only keyword that would be
1908       // returned by CorrectTypo), this is a send to super.
1909       diagnoseTypo(Corrected,
1910                    PDiag(diag::err_unknown_receiver_suggest) << Name);
1911       return ObjCSuperMessage;
1912     } else if (ObjCInterfaceDecl *Class =
1913                    Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1914       // If we found a declaration, correct when it refers to an Objective-C
1915       // class.
1916       diagnoseTypo(Corrected,
1917                    PDiag(diag::err_unknown_receiver_suggest) << Name);
1918       QualType T = Context.getObjCInterfaceType(Class);
1919       TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1920       ReceiverType = CreateParsedType(T, TSInfo);
1921       return ObjCClassMessage;
1922     }
1923   }
1924 
1925   // Fall back: let the parser try to parse it as an instance message.
1926   return ObjCInstanceMessage;
1927 }
1928 
1929 ExprResult Sema::ActOnSuperMessage(Scope *S,
1930                                    SourceLocation SuperLoc,
1931                                    Selector Sel,
1932                                    SourceLocation LBracLoc,
1933                                    ArrayRef<SourceLocation> SelectorLocs,
1934                                    SourceLocation RBracLoc,
1935                                    MultiExprArg Args) {
1936   // Determine whether we are inside a method or not.
1937   ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
1938   if (!Method) {
1939     Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1940     return ExprError();
1941   }
1942 
1943   ObjCInterfaceDecl *Class = Method->getClassInterface();
1944   if (!Class) {
1945     Diag(SuperLoc, diag::error_no_super_class_message)
1946       << Method->getDeclName();
1947     return ExprError();
1948   }
1949 
1950   ObjCInterfaceDecl *Super = Class->getSuperClass();
1951   if (!Super) {
1952     // The current class does not have a superclass.
1953     Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1954       << Class->getIdentifier();
1955     return ExprError();
1956   }
1957 
1958   // We are in a method whose class has a superclass, so 'super'
1959   // is acting as a keyword.
1960   if (Method->getSelector() == Sel)
1961     getCurFunction()->ObjCShouldCallSuper = false;
1962 
1963   if (Method->isInstanceMethod()) {
1964     // Since we are in an instance method, this is an instance
1965     // message to the superclass instance.
1966     QualType SuperTy = Context.getObjCInterfaceType(Super);
1967     SuperTy = Context.getObjCObjectPointerType(SuperTy);
1968     return BuildInstanceMessage(0, SuperTy, SuperLoc,
1969                                 Sel, /*Method=*/0,
1970                                 LBracLoc, SelectorLocs, RBracLoc, Args);
1971   }
1972 
1973   // Since we are in a class method, this is a class message to
1974   // the superclass.
1975   return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1976                            Context.getObjCInterfaceType(Super),
1977                            SuperLoc, Sel, /*Method=*/0,
1978                            LBracLoc, SelectorLocs, RBracLoc, Args);
1979 }
1980 
1981 
1982 ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
1983                                            bool isSuperReceiver,
1984                                            SourceLocation Loc,
1985                                            Selector Sel,
1986                                            ObjCMethodDecl *Method,
1987                                            MultiExprArg Args) {
1988   TypeSourceInfo *receiverTypeInfo = 0;
1989   if (!ReceiverType.isNull())
1990     receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
1991 
1992   return BuildClassMessage(receiverTypeInfo, ReceiverType,
1993                           /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
1994                            Sel, Method, Loc, Loc, Loc, Args,
1995                            /*isImplicit=*/true);
1996 
1997 }
1998 
1999 static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2000                                unsigned DiagID,
2001                                bool (*refactor)(const ObjCMessageExpr *,
2002                                               const NSAPI &, edit::Commit &)) {
2003   SourceLocation MsgLoc = Msg->getExprLoc();
2004   if (S.Diags.getDiagnosticLevel(DiagID, MsgLoc) == DiagnosticsEngine::Ignored)
2005     return;
2006 
2007   SourceManager &SM = S.SourceMgr;
2008   edit::Commit ECommit(SM, S.LangOpts);
2009   if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2010     DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2011                         << Msg->getSelector() << Msg->getSourceRange();
2012     // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2013     if (!ECommit.isCommitable())
2014       return;
2015     for (edit::Commit::edit_iterator
2016            I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2017       const edit::Commit::Edit &Edit = *I;
2018       switch (Edit.Kind) {
2019       case edit::Commit::Act_Insert:
2020         Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2021                                                         Edit.Text,
2022                                                         Edit.BeforePrev));
2023         break;
2024       case edit::Commit::Act_InsertFromRange:
2025         Builder.AddFixItHint(
2026             FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2027                                                 Edit.getInsertFromRange(SM),
2028                                                 Edit.BeforePrev));
2029         break;
2030       case edit::Commit::Act_Remove:
2031         Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2032         break;
2033       }
2034     }
2035   }
2036 }
2037 
2038 static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2039   applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2040                      edit::rewriteObjCRedundantCallWithLiteral);
2041 }
2042 
2043 /// \brief Build an Objective-C class message expression.
2044 ///
2045 /// This routine takes care of both normal class messages and
2046 /// class messages to the superclass.
2047 ///
2048 /// \param ReceiverTypeInfo Type source information that describes the
2049 /// receiver of this message. This may be NULL, in which case we are
2050 /// sending to the superclass and \p SuperLoc must be a valid source
2051 /// location.
2052 
2053 /// \param ReceiverType The type of the object receiving the
2054 /// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2055 /// type as that refers to. For a superclass send, this is the type of
2056 /// the superclass.
2057 ///
2058 /// \param SuperLoc The location of the "super" keyword in a
2059 /// superclass message.
2060 ///
2061 /// \param Sel The selector to which the message is being sent.
2062 ///
2063 /// \param Method The method that this class message is invoking, if
2064 /// already known.
2065 ///
2066 /// \param LBracLoc The location of the opening square bracket ']'.
2067 ///
2068 /// \param RBracLoc The location of the closing square bracket ']'.
2069 ///
2070 /// \param ArgsIn The message arguments.
2071 ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
2072                                    QualType ReceiverType,
2073                                    SourceLocation SuperLoc,
2074                                    Selector Sel,
2075                                    ObjCMethodDecl *Method,
2076                                    SourceLocation LBracLoc,
2077                                    ArrayRef<SourceLocation> SelectorLocs,
2078                                    SourceLocation RBracLoc,
2079                                    MultiExprArg ArgsIn,
2080                                    bool isImplicit) {
2081   SourceLocation Loc = SuperLoc.isValid()? SuperLoc
2082     : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
2083   if (LBracLoc.isInvalid()) {
2084     Diag(Loc, diag::err_missing_open_square_message_send)
2085       << FixItHint::CreateInsertion(Loc, "[");
2086     LBracLoc = Loc;
2087   }
2088   SourceLocation SelLoc;
2089   if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2090     SelLoc = SelectorLocs.front();
2091   else
2092     SelLoc = Loc;
2093 
2094   if (ReceiverType->isDependentType()) {
2095     // If the receiver type is dependent, we can't type-check anything
2096     // at this point. Build a dependent expression.
2097     unsigned NumArgs = ArgsIn.size();
2098     Expr **Args = ArgsIn.data();
2099     assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2100     return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
2101                                          VK_RValue, LBracLoc, ReceiverTypeInfo,
2102                                          Sel, SelectorLocs, /*Method=*/0,
2103                                          makeArrayRef(Args, NumArgs),RBracLoc,
2104                                          isImplicit));
2105   }
2106 
2107   // Find the class to which we are sending this message.
2108   ObjCInterfaceDecl *Class = 0;
2109   const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2110   if (!ClassType || !(Class = ClassType->getInterface())) {
2111     Diag(Loc, diag::err_invalid_receiver_class_message)
2112       << ReceiverType;
2113     return ExprError();
2114   }
2115   assert(Class && "We don't know which class we're messaging?");
2116   // objc++ diagnoses during typename annotation.
2117   if (!getLangOpts().CPlusPlus)
2118     (void)DiagnoseUseOfDecl(Class, SelLoc);
2119   // Find the method we are messaging.
2120   if (!Method) {
2121     SourceRange TypeRange
2122       = SuperLoc.isValid()? SourceRange(SuperLoc)
2123                           : ReceiverTypeInfo->getTypeLoc().getSourceRange();
2124     if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
2125                             (getLangOpts().ObjCAutoRefCount
2126                                ? diag::err_arc_receiver_forward_class
2127                                : diag::warn_receiver_forward_class),
2128                             TypeRange)) {
2129       // A forward class used in messaging is treated as a 'Class'
2130       Method = LookupFactoryMethodInGlobalPool(Sel,
2131                                                SourceRange(LBracLoc, RBracLoc));
2132       if (Method && !getLangOpts().ObjCAutoRefCount)
2133         Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2134           << Method->getDeclName();
2135     }
2136     if (!Method)
2137       Method = Class->lookupClassMethod(Sel);
2138 
2139     // If we have an implementation in scope, check "private" methods.
2140     if (!Method)
2141       Method = Class->lookupPrivateClassMethod(Sel);
2142 
2143     if (Method && DiagnoseUseOfDecl(Method, SelLoc))
2144       return ExprError();
2145   }
2146 
2147   // Check the argument types and determine the result type.
2148   QualType ReturnType;
2149   ExprValueKind VK = VK_RValue;
2150 
2151   unsigned NumArgs = ArgsIn.size();
2152   Expr **Args = ArgsIn.data();
2153   if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2154                                 Sel, SelectorLocs,
2155                                 Method, true,
2156                                 SuperLoc.isValid(), LBracLoc, RBracLoc,
2157                                 ReturnType, VK))
2158     return ExprError();
2159 
2160   if (Method && !Method->getReturnType()->isVoidType() &&
2161       RequireCompleteType(LBracLoc, Method->getReturnType(),
2162                           diag::err_illegal_message_expr_incomplete_type))
2163     return ExprError();
2164 
2165   // Construct the appropriate ObjCMessageExpr.
2166   ObjCMessageExpr *Result;
2167   if (SuperLoc.isValid())
2168     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2169                                      SuperLoc, /*IsInstanceSuper=*/false,
2170                                      ReceiverType, Sel, SelectorLocs,
2171                                      Method, makeArrayRef(Args, NumArgs),
2172                                      RBracLoc, isImplicit);
2173   else {
2174     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2175                                      ReceiverTypeInfo, Sel, SelectorLocs,
2176                                      Method, makeArrayRef(Args, NumArgs),
2177                                      RBracLoc, isImplicit);
2178     if (!isImplicit)
2179       checkCocoaAPI(*this, Result);
2180   }
2181   return MaybeBindToTemporary(Result);
2182 }
2183 
2184 // ActOnClassMessage - used for both unary and keyword messages.
2185 // ArgExprs is optional - if it is present, the number of expressions
2186 // is obtained from Sel.getNumArgs().
2187 ExprResult Sema::ActOnClassMessage(Scope *S,
2188                                    ParsedType Receiver,
2189                                    Selector Sel,
2190                                    SourceLocation LBracLoc,
2191                                    ArrayRef<SourceLocation> SelectorLocs,
2192                                    SourceLocation RBracLoc,
2193                                    MultiExprArg Args) {
2194   TypeSourceInfo *ReceiverTypeInfo;
2195   QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2196   if (ReceiverType.isNull())
2197     return ExprError();
2198 
2199 
2200   if (!ReceiverTypeInfo)
2201     ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2202 
2203   return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
2204                            /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
2205                            LBracLoc, SelectorLocs, RBracLoc, Args);
2206 }
2207 
2208 ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2209                                               QualType ReceiverType,
2210                                               SourceLocation Loc,
2211                                               Selector Sel,
2212                                               ObjCMethodDecl *Method,
2213                                               MultiExprArg Args) {
2214   return BuildInstanceMessage(Receiver, ReceiverType,
2215                               /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2216                               Sel, Method, Loc, Loc, Loc, Args,
2217                               /*isImplicit=*/true);
2218 }
2219 
2220 /// \brief Build an Objective-C instance message expression.
2221 ///
2222 /// This routine takes care of both normal instance messages and
2223 /// instance messages to the superclass instance.
2224 ///
2225 /// \param Receiver The expression that computes the object that will
2226 /// receive this message. This may be empty, in which case we are
2227 /// sending to the superclass instance and \p SuperLoc must be a valid
2228 /// source location.
2229 ///
2230 /// \param ReceiverType The (static) type of the object receiving the
2231 /// message. When a \p Receiver expression is provided, this is the
2232 /// same type as that expression. For a superclass instance send, this
2233 /// is a pointer to the type of the superclass.
2234 ///
2235 /// \param SuperLoc The location of the "super" keyword in a
2236 /// superclass instance message.
2237 ///
2238 /// \param Sel The selector to which the message is being sent.
2239 ///
2240 /// \param Method The method that this instance message is invoking, if
2241 /// already known.
2242 ///
2243 /// \param LBracLoc The location of the opening square bracket ']'.
2244 ///
2245 /// \param RBracLoc The location of the closing square bracket ']'.
2246 ///
2247 /// \param ArgsIn The message arguments.
2248 ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
2249                                       QualType ReceiverType,
2250                                       SourceLocation SuperLoc,
2251                                       Selector Sel,
2252                                       ObjCMethodDecl *Method,
2253                                       SourceLocation LBracLoc,
2254                                       ArrayRef<SourceLocation> SelectorLocs,
2255                                       SourceLocation RBracLoc,
2256                                       MultiExprArg ArgsIn,
2257                                       bool isImplicit) {
2258   // The location of the receiver.
2259   SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
2260   SourceRange RecRange =
2261       SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2262   SourceLocation SelLoc;
2263   if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2264     SelLoc = SelectorLocs.front();
2265   else
2266     SelLoc = Loc;
2267 
2268   if (LBracLoc.isInvalid()) {
2269     Diag(Loc, diag::err_missing_open_square_message_send)
2270       << FixItHint::CreateInsertion(Loc, "[");
2271     LBracLoc = Loc;
2272   }
2273 
2274   // If we have a receiver expression, perform appropriate promotions
2275   // and determine receiver type.
2276   if (Receiver) {
2277     if (Receiver->hasPlaceholderType()) {
2278       ExprResult Result;
2279       if (Receiver->getType() == Context.UnknownAnyTy)
2280         Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2281       else
2282         Result = CheckPlaceholderExpr(Receiver);
2283       if (Result.isInvalid()) return ExprError();
2284       Receiver = Result.take();
2285     }
2286 
2287     if (Receiver->isTypeDependent()) {
2288       // If the receiver is type-dependent, we can't type-check anything
2289       // at this point. Build a dependent expression.
2290       unsigned NumArgs = ArgsIn.size();
2291       Expr **Args = ArgsIn.data();
2292       assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2293       return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
2294                                            VK_RValue, LBracLoc, Receiver, Sel,
2295                                            SelectorLocs, /*Method=*/0,
2296                                            makeArrayRef(Args, NumArgs),
2297                                            RBracLoc, isImplicit));
2298     }
2299 
2300     // If necessary, apply function/array conversion to the receiver.
2301     // C99 6.7.5.3p[7,8].
2302     ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2303     if (Result.isInvalid())
2304       return ExprError();
2305     Receiver = Result.take();
2306     ReceiverType = Receiver->getType();
2307 
2308     // If the receiver is an ObjC pointer, a block pointer, or an
2309     // __attribute__((NSObject)) pointer, we don't need to do any
2310     // special conversion in order to look up a receiver.
2311     if (ReceiverType->isObjCRetainableType()) {
2312       // do nothing
2313     } else if (!getLangOpts().ObjCAutoRefCount &&
2314                !Context.getObjCIdType().isNull() &&
2315                (ReceiverType->isPointerType() ||
2316                 ReceiverType->isIntegerType())) {
2317       // Implicitly convert integers and pointers to 'id' but emit a warning.
2318       // But not in ARC.
2319       Diag(Loc, diag::warn_bad_receiver_type)
2320         << ReceiverType
2321         << Receiver->getSourceRange();
2322       if (ReceiverType->isPointerType()) {
2323         Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2324                                      CK_CPointerToObjCPointerCast).take();
2325       } else {
2326         // TODO: specialized warning on null receivers?
2327         bool IsNull = Receiver->isNullPointerConstant(Context,
2328                                               Expr::NPC_ValueDependentIsNull);
2329         CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2330         Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2331                                      Kind).take();
2332       }
2333       ReceiverType = Receiver->getType();
2334     } else if (getLangOpts().CPlusPlus) {
2335       // The receiver must be a complete type.
2336       if (RequireCompleteType(Loc, Receiver->getType(),
2337                               diag::err_incomplete_receiver_type))
2338         return ExprError();
2339 
2340       ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2341       if (result.isUsable()) {
2342         Receiver = result.take();
2343         ReceiverType = Receiver->getType();
2344       }
2345     }
2346   }
2347 
2348   // There's a somewhat weird interaction here where we assume that we
2349   // won't actually have a method unless we also don't need to do some
2350   // of the more detailed type-checking on the receiver.
2351 
2352   if (!Method) {
2353     // Handle messages to id.
2354     bool receiverIsId = ReceiverType->isObjCIdType();
2355     if (receiverIsId || ReceiverType->isBlockPointerType() ||
2356         (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2357       Method = LookupInstanceMethodInGlobalPool(Sel,
2358                                                 SourceRange(LBracLoc, RBracLoc),
2359                                                 receiverIsId);
2360       if (!Method)
2361         Method = LookupFactoryMethodInGlobalPool(Sel,
2362                                                  SourceRange(LBracLoc,RBracLoc),
2363                                                  receiverIsId);
2364     } else if (ReceiverType->isObjCClassType() ||
2365                ReceiverType->isObjCQualifiedClassType()) {
2366       // Handle messages to Class.
2367       // We allow sending a message to a qualified Class ("Class<foo>"), which
2368       // is ok as long as one of the protocols implements the selector (if not, warn).
2369       if (const ObjCObjectPointerType *QClassTy
2370             = ReceiverType->getAsObjCQualifiedClassType()) {
2371         // Search protocols for class methods.
2372         Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2373         if (!Method) {
2374           Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2375           // warn if instance method found for a Class message.
2376           if (Method) {
2377             Diag(SelLoc, diag::warn_instance_method_on_class_found)
2378               << Method->getSelector() << Sel;
2379             Diag(Method->getLocation(), diag::note_method_declared_at)
2380               << Method->getDeclName();
2381           }
2382         }
2383       } else {
2384         if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2385           if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2386             // First check the public methods in the class interface.
2387             Method = ClassDecl->lookupClassMethod(Sel);
2388 
2389             if (!Method)
2390               Method = ClassDecl->lookupPrivateClassMethod(Sel);
2391           }
2392           if (Method && DiagnoseUseOfDecl(Method, SelLoc))
2393             return ExprError();
2394         }
2395         if (!Method) {
2396           // If not messaging 'self', look for any factory method named 'Sel'.
2397           if (!Receiver || !isSelfExpr(Receiver)) {
2398             Method = LookupFactoryMethodInGlobalPool(Sel,
2399                                                 SourceRange(LBracLoc, RBracLoc),
2400                                                      true);
2401             if (!Method) {
2402               // If no class (factory) method was found, check if an _instance_
2403               // method of the same name exists in the root class only.
2404               Method = LookupInstanceMethodInGlobalPool(Sel,
2405                                                SourceRange(LBracLoc, RBracLoc),
2406                                                         true);
2407               if (Method)
2408                   if (const ObjCInterfaceDecl *ID =
2409                       dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2410                     if (ID->getSuperClass())
2411                       Diag(SelLoc, diag::warn_root_inst_method_not_found)
2412                       << Sel << SourceRange(LBracLoc, RBracLoc);
2413                   }
2414             }
2415           }
2416         }
2417       }
2418     } else {
2419       ObjCInterfaceDecl* ClassDecl = 0;
2420 
2421       // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2422       // long as one of the protocols implements the selector (if not, warn).
2423       // And as long as message is not deprecated/unavailable (warn if it is).
2424       if (const ObjCObjectPointerType *QIdTy
2425                                    = ReceiverType->getAsObjCQualifiedIdType()) {
2426         // Search protocols for instance methods.
2427         Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2428         if (!Method)
2429           Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
2430         if (Method && DiagnoseUseOfDecl(Method, SelLoc))
2431           return ExprError();
2432       } else if (const ObjCObjectPointerType *OCIType
2433                    = ReceiverType->getAsObjCInterfacePointerType()) {
2434         // We allow sending a message to a pointer to an interface (an object).
2435         ClassDecl = OCIType->getInterfaceDecl();
2436 
2437         // Try to complete the type. Under ARC, this is a hard error from which
2438         // we don't try to recover.
2439         const ObjCInterfaceDecl *forwardClass = 0;
2440         if (RequireCompleteType(Loc, OCIType->getPointeeType(),
2441               getLangOpts().ObjCAutoRefCount
2442                 ? diag::err_arc_receiver_forward_instance
2443                 : diag::warn_receiver_forward_instance,
2444                                 Receiver? Receiver->getSourceRange()
2445                                         : SourceRange(SuperLoc))) {
2446           if (getLangOpts().ObjCAutoRefCount)
2447             return ExprError();
2448 
2449           forwardClass = OCIType->getInterfaceDecl();
2450           Diag(Receiver ? Receiver->getLocStart()
2451                         : SuperLoc, diag::note_receiver_is_id);
2452           Method = 0;
2453         } else {
2454           Method = ClassDecl->lookupInstanceMethod(Sel);
2455         }
2456 
2457         if (!Method)
2458           // Search protocol qualifiers.
2459           Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2460 
2461         if (!Method) {
2462           // If we have implementations in scope, check "private" methods.
2463           Method = ClassDecl->lookupPrivateMethod(Sel);
2464 
2465           if (!Method && getLangOpts().ObjCAutoRefCount) {
2466             Diag(SelLoc, diag::err_arc_may_not_respond)
2467               << OCIType->getPointeeType() << Sel << RecRange
2468               << SourceRange(SelectorLocs.front(), SelectorLocs.back());
2469             return ExprError();
2470           }
2471 
2472           if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
2473             // If we still haven't found a method, look in the global pool. This
2474             // behavior isn't very desirable, however we need it for GCC
2475             // compatibility. FIXME: should we deviate??
2476             if (OCIType->qual_empty()) {
2477               Method = LookupInstanceMethodInGlobalPool(Sel,
2478                                               SourceRange(LBracLoc, RBracLoc));
2479               if (Method && !forwardClass)
2480                 Diag(SelLoc, diag::warn_maynot_respond)
2481                   << OCIType->getInterfaceDecl()->getIdentifier()
2482                   << Sel << RecRange;
2483             }
2484           }
2485         }
2486         if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
2487           return ExprError();
2488       } else {
2489         // Reject other random receiver types (e.g. structs).
2490         Diag(Loc, diag::err_bad_receiver_type)
2491           << ReceiverType << Receiver->getSourceRange();
2492         return ExprError();
2493       }
2494     }
2495   }
2496 
2497   FunctionScopeInfo *DIFunctionScopeInfo =
2498     (Method && Method->getMethodFamily() == OMF_init)
2499       ? getEnclosingFunction() : 0;
2500 
2501   if (DIFunctionScopeInfo &&
2502       DIFunctionScopeInfo->ObjCIsDesignatedInit &&
2503       (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2504     bool isDesignatedInitChain = false;
2505     if (SuperLoc.isValid()) {
2506       if (const ObjCObjectPointerType *
2507             OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2508         if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
2509           // Either we know this is a designated initializer or we
2510           // conservatively assume it because we don't know for sure.
2511           if (!ID->declaresOrInheritsDesignatedInitializers() ||
2512               ID->isDesignatedInitializer(Sel)) {
2513             isDesignatedInitChain = true;
2514             DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
2515           }
2516         }
2517       }
2518     }
2519     if (!isDesignatedInitChain) {
2520       const ObjCMethodDecl *InitMethod = 0;
2521       bool isDesignated =
2522         getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2523       assert(isDesignated && InitMethod);
2524       (void)isDesignated;
2525       Diag(SelLoc, SuperLoc.isValid() ?
2526              diag::warn_objc_designated_init_non_designated_init_call :
2527              diag::warn_objc_designated_init_non_super_designated_init_call);
2528       Diag(InitMethod->getLocation(),
2529            diag::note_objc_designated_init_marked_here);
2530     }
2531   }
2532 
2533   if (DIFunctionScopeInfo &&
2534       DIFunctionScopeInfo->ObjCIsSecondaryInit &&
2535       (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2536     if (SuperLoc.isValid()) {
2537       Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2538     } else {
2539       DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
2540     }
2541   }
2542 
2543   // Check the message arguments.
2544   unsigned NumArgs = ArgsIn.size();
2545   Expr **Args = ArgsIn.data();
2546   QualType ReturnType;
2547   ExprValueKind VK = VK_RValue;
2548   bool ClassMessage = (ReceiverType->isObjCClassType() ||
2549                        ReceiverType->isObjCQualifiedClassType());
2550   if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2551                                 Sel, SelectorLocs, Method,
2552                                 ClassMessage, SuperLoc.isValid(),
2553                                 LBracLoc, RBracLoc, ReturnType, VK))
2554     return ExprError();
2555 
2556   if (Method && !Method->getReturnType()->isVoidType() &&
2557       RequireCompleteType(LBracLoc, Method->getReturnType(),
2558                           diag::err_illegal_message_expr_incomplete_type))
2559     return ExprError();
2560 
2561   // In ARC, forbid the user from sending messages to
2562   // retain/release/autorelease/dealloc/retainCount explicitly.
2563   if (getLangOpts().ObjCAutoRefCount) {
2564     ObjCMethodFamily family =
2565       (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2566     switch (family) {
2567     case OMF_init:
2568       if (Method)
2569         checkInitMethod(Method, ReceiverType);
2570 
2571     case OMF_None:
2572     case OMF_alloc:
2573     case OMF_copy:
2574     case OMF_finalize:
2575     case OMF_mutableCopy:
2576     case OMF_new:
2577     case OMF_self:
2578       break;
2579 
2580     case OMF_dealloc:
2581     case OMF_retain:
2582     case OMF_release:
2583     case OMF_autorelease:
2584     case OMF_retainCount:
2585       Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2586         << Sel << RecRange;
2587       break;
2588 
2589     case OMF_performSelector:
2590       if (Method && NumArgs >= 1) {
2591         if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2592           Selector ArgSel = SelExp->getSelector();
2593           ObjCMethodDecl *SelMethod =
2594             LookupInstanceMethodInGlobalPool(ArgSel,
2595                                              SelExp->getSourceRange());
2596           if (!SelMethod)
2597             SelMethod =
2598               LookupFactoryMethodInGlobalPool(ArgSel,
2599                                               SelExp->getSourceRange());
2600           if (SelMethod) {
2601             ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2602             switch (SelFamily) {
2603               case OMF_alloc:
2604               case OMF_copy:
2605               case OMF_mutableCopy:
2606               case OMF_new:
2607               case OMF_self:
2608               case OMF_init:
2609                 // Issue error, unless ns_returns_not_retained.
2610                 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2611                   // selector names a +1 method
2612                   Diag(SelLoc,
2613                        diag::err_arc_perform_selector_retains);
2614                   Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2615                     << SelMethod->getDeclName();
2616                 }
2617                 break;
2618               default:
2619                 // +0 call. OK. unless ns_returns_retained.
2620                 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2621                   // selector names a +1 method
2622                   Diag(SelLoc,
2623                        diag::err_arc_perform_selector_retains);
2624                   Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2625                     << SelMethod->getDeclName();
2626                 }
2627                 break;
2628             }
2629           }
2630         } else {
2631           // error (may leak).
2632           Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
2633           Diag(Args[0]->getExprLoc(), diag::note_used_here);
2634         }
2635       }
2636       break;
2637     }
2638   }
2639 
2640   // Construct the appropriate ObjCMessageExpr instance.
2641   ObjCMessageExpr *Result;
2642   if (SuperLoc.isValid())
2643     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2644                                      SuperLoc,  /*IsInstanceSuper=*/true,
2645                                      ReceiverType, Sel, SelectorLocs, Method,
2646                                      makeArrayRef(Args, NumArgs), RBracLoc,
2647                                      isImplicit);
2648   else {
2649     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2650                                      Receiver, Sel, SelectorLocs, Method,
2651                                      makeArrayRef(Args, NumArgs), RBracLoc,
2652                                      isImplicit);
2653     if (!isImplicit)
2654       checkCocoaAPI(*this, Result);
2655   }
2656 
2657   if (getLangOpts().ObjCAutoRefCount) {
2658     DiagnoseARCUseOfWeakReceiver(*this, Receiver);
2659 
2660     // In ARC, annotate delegate init calls.
2661     if (Result->getMethodFamily() == OMF_init &&
2662         (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2663       // Only consider init calls *directly* in init implementations,
2664       // not within blocks.
2665       ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2666       if (method && method->getMethodFamily() == OMF_init) {
2667         // The implicit assignment to self means we also don't want to
2668         // consume the result.
2669         Result->setDelegateInitCall(true);
2670         return Owned(Result);
2671       }
2672     }
2673 
2674     // In ARC, check for message sends which are likely to introduce
2675     // retain cycles.
2676     checkRetainCycles(Result);
2677 
2678     if (!isImplicit && Method) {
2679       if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
2680         bool IsWeak =
2681           Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
2682         if (!IsWeak && Sel.isUnarySelector())
2683           IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
2684 
2685         if (IsWeak) {
2686           DiagnosticsEngine::Level Level =
2687             Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
2688                                      LBracLoc);
2689           if (Level != DiagnosticsEngine::Ignored)
2690             getCurFunction()->recordUseOfWeak(Result, Prop);
2691 
2692         }
2693       }
2694     }
2695   }
2696 
2697   return MaybeBindToTemporary(Result);
2698 }
2699 
2700 static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
2701   if (ObjCSelectorExpr *OSE =
2702       dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
2703     Selector Sel = OSE->getSelector();
2704     SourceLocation Loc = OSE->getAtLoc();
2705     llvm::DenseMap<Selector, SourceLocation>::iterator Pos
2706     = S.ReferencedSelectors.find(Sel);
2707     if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
2708       S.ReferencedSelectors.erase(Pos);
2709   }
2710 }
2711 
2712 // ActOnInstanceMessage - used for both unary and keyword messages.
2713 // ArgExprs is optional - if it is present, the number of expressions
2714 // is obtained from Sel.getNumArgs().
2715 ExprResult Sema::ActOnInstanceMessage(Scope *S,
2716                                       Expr *Receiver,
2717                                       Selector Sel,
2718                                       SourceLocation LBracLoc,
2719                                       ArrayRef<SourceLocation> SelectorLocs,
2720                                       SourceLocation RBracLoc,
2721                                       MultiExprArg Args) {
2722   if (!Receiver)
2723     return ExprError();
2724 
2725   // A ParenListExpr can show up while doing error recovery with invalid code.
2726   if (isa<ParenListExpr>(Receiver)) {
2727     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
2728     if (Result.isInvalid()) return ExprError();
2729     Receiver = Result.take();
2730   }
2731 
2732   if (RespondsToSelectorSel.isNull()) {
2733     IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
2734     RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
2735   }
2736   if (Sel == RespondsToSelectorSel)
2737     RemoveSelectorFromWarningCache(*this, Args[0]);
2738 
2739   return BuildInstanceMessage(Receiver, Receiver->getType(),
2740                               /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
2741                               LBracLoc, SelectorLocs, RBracLoc, Args);
2742 }
2743 
2744 enum ARCConversionTypeClass {
2745   /// int, void, struct A
2746   ACTC_none,
2747 
2748   /// id, void (^)()
2749   ACTC_retainable,
2750 
2751   /// id*, id***, void (^*)(),
2752   ACTC_indirectRetainable,
2753 
2754   /// void* might be a normal C type, or it might a CF type.
2755   ACTC_voidPtr,
2756 
2757   /// struct A*
2758   ACTC_coreFoundation
2759 };
2760 static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2761   return (ACTC == ACTC_retainable ||
2762           ACTC == ACTC_coreFoundation ||
2763           ACTC == ACTC_voidPtr);
2764 }
2765 static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2766   return ACTC == ACTC_none ||
2767          ACTC == ACTC_voidPtr ||
2768          ACTC == ACTC_coreFoundation;
2769 }
2770 
2771 static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
2772   bool isIndirect = false;
2773 
2774   // Ignore an outermost reference type.
2775   if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
2776     type = ref->getPointeeType();
2777     isIndirect = true;
2778   }
2779 
2780   // Drill through pointers and arrays recursively.
2781   while (true) {
2782     if (const PointerType *ptr = type->getAs<PointerType>()) {
2783       type = ptr->getPointeeType();
2784 
2785       // The first level of pointer may be the innermost pointer on a CF type.
2786       if (!isIndirect) {
2787         if (type->isVoidType()) return ACTC_voidPtr;
2788         if (type->isRecordType()) return ACTC_coreFoundation;
2789       }
2790     } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2791       type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2792     } else {
2793       break;
2794     }
2795     isIndirect = true;
2796   }
2797 
2798   if (isIndirect) {
2799     if (type->isObjCARCBridgableType())
2800       return ACTC_indirectRetainable;
2801     return ACTC_none;
2802   }
2803 
2804   if (type->isObjCARCBridgableType())
2805     return ACTC_retainable;
2806 
2807   return ACTC_none;
2808 }
2809 
2810 namespace {
2811   /// A result from the cast checker.
2812   enum ACCResult {
2813     /// Cannot be casted.
2814     ACC_invalid,
2815 
2816     /// Can be safely retained or not retained.
2817     ACC_bottom,
2818 
2819     /// Can be casted at +0.
2820     ACC_plusZero,
2821 
2822     /// Can be casted at +1.
2823     ACC_plusOne
2824   };
2825   ACCResult merge(ACCResult left, ACCResult right) {
2826     if (left == right) return left;
2827     if (left == ACC_bottom) return right;
2828     if (right == ACC_bottom) return left;
2829     return ACC_invalid;
2830   }
2831 
2832   /// A checker which white-lists certain expressions whose conversion
2833   /// to or from retainable type would otherwise be forbidden in ARC.
2834   class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2835     typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2836 
2837     ASTContext &Context;
2838     ARCConversionTypeClass SourceClass;
2839     ARCConversionTypeClass TargetClass;
2840     bool Diagnose;
2841 
2842     static bool isCFType(QualType type) {
2843       // Someday this can use ns_bridged.  For now, it has to do this.
2844       return type->isCARCBridgableType();
2845     }
2846 
2847   public:
2848     ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
2849                    ARCConversionTypeClass target, bool diagnose)
2850       : Context(Context), SourceClass(source), TargetClass(target),
2851         Diagnose(diagnose) {}
2852 
2853     using super::Visit;
2854     ACCResult Visit(Expr *e) {
2855       return super::Visit(e->IgnoreParens());
2856     }
2857 
2858     ACCResult VisitStmt(Stmt *s) {
2859       return ACC_invalid;
2860     }
2861 
2862     /// Null pointer constants can be casted however you please.
2863     ACCResult VisitExpr(Expr *e) {
2864       if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2865         return ACC_bottom;
2866       return ACC_invalid;
2867     }
2868 
2869     /// Objective-C string literals can be safely casted.
2870     ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2871       // If we're casting to any retainable type, go ahead.  Global
2872       // strings are immune to retains, so this is bottom.
2873       if (isAnyRetainable(TargetClass)) return ACC_bottom;
2874 
2875       return ACC_invalid;
2876     }
2877 
2878     /// Look through certain implicit and explicit casts.
2879     ACCResult VisitCastExpr(CastExpr *e) {
2880       switch (e->getCastKind()) {
2881         case CK_NullToPointer:
2882           return ACC_bottom;
2883 
2884         case CK_NoOp:
2885         case CK_LValueToRValue:
2886         case CK_BitCast:
2887         case CK_CPointerToObjCPointerCast:
2888         case CK_BlockPointerToObjCPointerCast:
2889         case CK_AnyPointerToBlockPointerCast:
2890           return Visit(e->getSubExpr());
2891 
2892         default:
2893           return ACC_invalid;
2894       }
2895     }
2896 
2897     /// Look through unary extension.
2898     ACCResult VisitUnaryExtension(UnaryOperator *e) {
2899       return Visit(e->getSubExpr());
2900     }
2901 
2902     /// Ignore the LHS of a comma operator.
2903     ACCResult VisitBinComma(BinaryOperator *e) {
2904       return Visit(e->getRHS());
2905     }
2906 
2907     /// Conditional operators are okay if both sides are okay.
2908     ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2909       ACCResult left = Visit(e->getTrueExpr());
2910       if (left == ACC_invalid) return ACC_invalid;
2911       return merge(left, Visit(e->getFalseExpr()));
2912     }
2913 
2914     /// Look through pseudo-objects.
2915     ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2916       // If we're getting here, we should always have a result.
2917       return Visit(e->getResultExpr());
2918     }
2919 
2920     /// Statement expressions are okay if their result expression is okay.
2921     ACCResult VisitStmtExpr(StmtExpr *e) {
2922       return Visit(e->getSubStmt()->body_back());
2923     }
2924 
2925     /// Some declaration references are okay.
2926     ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
2927       // References to global constants from system headers are okay.
2928       // These are things like 'kCFStringTransformToLatin'.  They are
2929       // can also be assumed to be immune to retains.
2930       VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
2931       if (isAnyRetainable(TargetClass) &&
2932           isAnyRetainable(SourceClass) &&
2933           var &&
2934           var->getStorageClass() == SC_Extern &&
2935           var->getType().isConstQualified() &&
2936           Context.getSourceManager().isInSystemHeader(var->getLocation())) {
2937         return ACC_bottom;
2938       }
2939 
2940       // Nothing else.
2941       return ACC_invalid;
2942     }
2943 
2944     /// Some calls are okay.
2945     ACCResult VisitCallExpr(CallExpr *e) {
2946       if (FunctionDecl *fn = e->getDirectCallee())
2947         if (ACCResult result = checkCallToFunction(fn))
2948           return result;
2949 
2950       return super::VisitCallExpr(e);
2951     }
2952 
2953     ACCResult checkCallToFunction(FunctionDecl *fn) {
2954       // Require a CF*Ref return type.
2955       if (!isCFType(fn->getReturnType()))
2956         return ACC_invalid;
2957 
2958       if (!isAnyRetainable(TargetClass))
2959         return ACC_invalid;
2960 
2961       // Honor an explicit 'not retained' attribute.
2962       if (fn->hasAttr<CFReturnsNotRetainedAttr>())
2963         return ACC_plusZero;
2964 
2965       // Honor an explicit 'retained' attribute, except that for
2966       // now we're not going to permit implicit handling of +1 results,
2967       // because it's a bit frightening.
2968       if (fn->hasAttr<CFReturnsRetainedAttr>())
2969         return Diagnose ? ACC_plusOne
2970                         : ACC_invalid; // ACC_plusOne if we start accepting this
2971 
2972       // Recognize this specific builtin function, which is used by CFSTR.
2973       unsigned builtinID = fn->getBuiltinID();
2974       if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
2975         return ACC_bottom;
2976 
2977       // Otherwise, don't do anything implicit with an unaudited function.
2978       if (!fn->hasAttr<CFAuditedTransferAttr>())
2979         return ACC_invalid;
2980 
2981       // Otherwise, it's +0 unless it follows the create convention.
2982       if (ento::coreFoundation::followsCreateRule(fn))
2983         return Diagnose ? ACC_plusOne
2984                         : ACC_invalid; // ACC_plusOne if we start accepting this
2985 
2986       return ACC_plusZero;
2987     }
2988 
2989     ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
2990       return checkCallToMethod(e->getMethodDecl());
2991     }
2992 
2993     ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
2994       ObjCMethodDecl *method;
2995       if (e->isExplicitProperty())
2996         method = e->getExplicitProperty()->getGetterMethodDecl();
2997       else
2998         method = e->getImplicitPropertyGetter();
2999       return checkCallToMethod(method);
3000     }
3001 
3002     ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3003       if (!method) return ACC_invalid;
3004 
3005       // Check for message sends to functions returning CF types.  We
3006       // just obey the Cocoa conventions with these, even though the
3007       // return type is CF.
3008       if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
3009         return ACC_invalid;
3010 
3011       // If the method is explicitly marked not-retained, it's +0.
3012       if (method->hasAttr<CFReturnsNotRetainedAttr>())
3013         return ACC_plusZero;
3014 
3015       // If the method is explicitly marked as returning retained, or its
3016       // selector follows a +1 Cocoa convention, treat it as +1.
3017       if (method->hasAttr<CFReturnsRetainedAttr>())
3018         return ACC_plusOne;
3019 
3020       switch (method->getSelector().getMethodFamily()) {
3021       case OMF_alloc:
3022       case OMF_copy:
3023       case OMF_mutableCopy:
3024       case OMF_new:
3025         return ACC_plusOne;
3026 
3027       default:
3028         // Otherwise, treat it as +0.
3029         return ACC_plusZero;
3030       }
3031     }
3032   };
3033 }
3034 
3035 bool Sema::isKnownName(StringRef name) {
3036   if (name.empty())
3037     return false;
3038   LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
3039                  Sema::LookupOrdinaryName);
3040   return LookupName(R, TUScope, false);
3041 }
3042 
3043 static void addFixitForObjCARCConversion(Sema &S,
3044                                          DiagnosticBuilder &DiagB,
3045                                          Sema::CheckedConversionKind CCK,
3046                                          SourceLocation afterLParen,
3047                                          QualType castType,
3048                                          Expr *castExpr,
3049                                          Expr *realCast,
3050                                          const char *bridgeKeyword,
3051                                          const char *CFBridgeName) {
3052   // We handle C-style and implicit casts here.
3053   switch (CCK) {
3054   case Sema::CCK_ImplicitConversion:
3055   case Sema::CCK_CStyleCast:
3056   case Sema::CCK_OtherCast:
3057     break;
3058   case Sema::CCK_FunctionalCast:
3059     return;
3060   }
3061 
3062   if (CFBridgeName) {
3063     if (CCK == Sema::CCK_OtherCast) {
3064       if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3065         SourceRange range(NCE->getOperatorLoc(),
3066                           NCE->getAngleBrackets().getEnd());
3067         SmallString<32> BridgeCall;
3068 
3069         SourceManager &SM = S.getSourceManager();
3070         char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3071         if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3072           BridgeCall += ' ';
3073 
3074         BridgeCall += CFBridgeName;
3075         DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3076       }
3077       return;
3078     }
3079     Expr *castedE = castExpr;
3080     if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3081       castedE = CCE->getSubExpr();
3082     castedE = castedE->IgnoreImpCasts();
3083     SourceRange range = castedE->getSourceRange();
3084 
3085     SmallString<32> BridgeCall;
3086 
3087     SourceManager &SM = S.getSourceManager();
3088     char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3089     if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3090       BridgeCall += ' ';
3091 
3092     BridgeCall += CFBridgeName;
3093 
3094     if (isa<ParenExpr>(castedE)) {
3095       DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3096                          BridgeCall));
3097     } else {
3098       BridgeCall += '(';
3099       DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3100                                                     BridgeCall));
3101       DiagB.AddFixItHint(FixItHint::CreateInsertion(
3102                                        S.PP.getLocForEndOfToken(range.getEnd()),
3103                                        ")"));
3104     }
3105     return;
3106   }
3107 
3108   if (CCK == Sema::CCK_CStyleCast) {
3109     DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
3110   } else if (CCK == Sema::CCK_OtherCast) {
3111     if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3112       std::string castCode = "(";
3113       castCode += bridgeKeyword;
3114       castCode += castType.getAsString();
3115       castCode += ")";
3116       SourceRange Range(NCE->getOperatorLoc(),
3117                         NCE->getAngleBrackets().getEnd());
3118       DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3119     }
3120   } else {
3121     std::string castCode = "(";
3122     castCode += bridgeKeyword;
3123     castCode += castType.getAsString();
3124     castCode += ")";
3125     Expr *castedE = castExpr->IgnoreImpCasts();
3126     SourceRange range = castedE->getSourceRange();
3127     if (isa<ParenExpr>(castedE)) {
3128       DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3129                          castCode));
3130     } else {
3131       castCode += "(";
3132       DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3133                                                     castCode));
3134       DiagB.AddFixItHint(FixItHint::CreateInsertion(
3135                                        S.PP.getLocForEndOfToken(range.getEnd()),
3136                                        ")"));
3137     }
3138   }
3139 }
3140 
3141 template <typename T>
3142 static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3143   TypedefNameDecl *TDNDecl = TD->getDecl();
3144   QualType QT = TDNDecl->getUnderlyingType();
3145   if (QT->isPointerType()) {
3146     QT = QT->getPointeeType();
3147     if (const RecordType *RT = QT->getAs<RecordType>())
3148       if (RecordDecl *RD = RT->getDecl())
3149         return RD->getAttr<T>();
3150   }
3151   return 0;
3152 }
3153 
3154 static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3155                                                             TypedefNameDecl *&TDNDecl) {
3156   while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3157     TDNDecl = TD->getDecl();
3158     if (ObjCBridgeRelatedAttr *ObjCBAttr =
3159         getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3160       return ObjCBAttr;
3161     T = TDNDecl->getUnderlyingType();
3162   }
3163   return 0;
3164 }
3165 
3166 static void
3167 diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3168                           QualType castType, ARCConversionTypeClass castACTC,
3169                           Expr *castExpr, Expr *realCast,
3170                           ARCConversionTypeClass exprACTC,
3171                           Sema::CheckedConversionKind CCK) {
3172   SourceLocation loc =
3173     (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
3174 
3175   if (S.makeUnavailableInSystemHeader(loc,
3176                 "converts between Objective-C and C pointers in -fobjc-arc"))
3177     return;
3178 
3179   QualType castExprType = castExpr->getType();
3180   TypedefNameDecl *TDNDecl = 0;
3181   if ((castACTC == ACTC_coreFoundation &&  exprACTC == ACTC_retainable &&
3182        ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3183       (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
3184        ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
3185     return;
3186 
3187   unsigned srcKind = 0;
3188   switch (exprACTC) {
3189   case ACTC_none:
3190   case ACTC_coreFoundation:
3191   case ACTC_voidPtr:
3192     srcKind = (castExprType->isPointerType() ? 1 : 0);
3193     break;
3194   case ACTC_retainable:
3195     srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3196     break;
3197   case ACTC_indirectRetainable:
3198     srcKind = 4;
3199     break;
3200   }
3201 
3202   // Check whether this could be fixed with a bridge cast.
3203   SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
3204   SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
3205 
3206   // Bridge from an ARC type to a CF type.
3207   if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
3208 
3209     S.Diag(loc, diag::err_arc_cast_requires_bridge)
3210       << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3211       << 2 // of C pointer type
3212       << castExprType
3213       << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3214       << castType
3215       << castRange
3216       << castExpr->getSourceRange();
3217     bool br = S.isKnownName("CFBridgingRelease");
3218     ACCResult CreateRule =
3219       ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3220     assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3221     if (CreateRule != ACC_plusOne)
3222     {
3223       DiagnosticBuilder DiagB =
3224         (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3225                               : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3226 
3227       addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3228                                    castType, castExpr, realCast, "__bridge ", 0);
3229     }
3230     if (CreateRule != ACC_plusZero)
3231     {
3232       DiagnosticBuilder DiagB =
3233         (CCK == Sema::CCK_OtherCast && !br) ?
3234           S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3235           S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3236                  diag::note_arc_bridge_transfer)
3237             << castExprType << br;
3238 
3239       addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3240                                    castType, castExpr, realCast, "__bridge_transfer ",
3241                                    br ? "CFBridgingRelease" : 0);
3242     }
3243 
3244     return;
3245   }
3246 
3247   // Bridge from a CF type to an ARC type.
3248   if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
3249     bool br = S.isKnownName("CFBridgingRetain");
3250     S.Diag(loc, diag::err_arc_cast_requires_bridge)
3251       << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3252       << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3253       << castExprType
3254       << 2 // to C pointer type
3255       << castType
3256       << castRange
3257       << castExpr->getSourceRange();
3258     ACCResult CreateRule =
3259       ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3260     assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3261     if (CreateRule != ACC_plusOne)
3262     {
3263       DiagnosticBuilder DiagB =
3264       (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3265                                : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3266       addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3267                                    castType, castExpr, realCast, "__bridge ", 0);
3268     }
3269     if (CreateRule != ACC_plusZero)
3270     {
3271       DiagnosticBuilder DiagB =
3272         (CCK == Sema::CCK_OtherCast && !br) ?
3273           S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3274           S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3275                  diag::note_arc_bridge_retained)
3276             << castType << br;
3277 
3278       addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3279                                    castType, castExpr, realCast, "__bridge_retained ",
3280                                    br ? "CFBridgingRetain" : 0);
3281     }
3282 
3283     return;
3284   }
3285 
3286   S.Diag(loc, diag::err_arc_mismatched_cast)
3287     << (CCK != Sema::CCK_ImplicitConversion)
3288     << srcKind << castExprType << castType
3289     << castRange << castExpr->getSourceRange();
3290 }
3291 
3292 template <typename TB>
3293 static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3294                                   bool TollFreeBridgeCast) {
3295   QualType T = castExpr->getType();
3296   while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3297     TypedefNameDecl *TDNDecl = TD->getDecl();
3298     if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
3299       if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3300         NamedDecl *Target = 0;
3301         // Check for an existing type with this name.
3302         LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3303                        Sema::LookupOrdinaryName);
3304         if (S.LookupName(R, S.TUScope)) {
3305           Target = R.getFoundDecl();
3306           if (Target && isa<ObjCInterfaceDecl>(Target)) {
3307             ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3308             if (const ObjCObjectPointerType *InterfacePointerType =
3309                   castType->getAsObjCInterfacePointerType()) {
3310               ObjCInterfaceDecl *CastClass
3311                 = InterfacePointerType->getObjectType()->getInterface();
3312               if ((CastClass == ExprClass) ||
3313                   (CastClass && ExprClass->isSuperClassOf(CastClass))) {
3314                 if (!TollFreeBridgeCast && S.getLangOpts().ObjCAutoRefCount) {
3315                   // bridge attribute is ok. However, under ARC, cast still requires
3316                   // an explicit cast and should not compile under ARC.
3317                   S.Diag(castExpr->getLocStart(), diag::err_objc_invalid_bridge)
3318                     << T << Target->getName();
3319                 }
3320                 return true;
3321               }
3322               S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3323                 << T << Target->getName() << castType->getPointeeType();
3324               return true;
3325             } else if (castType->isObjCIdType() ||
3326                        (S.Context.ObjCObjectAdoptsQTypeProtocols(
3327                           castType, ExprClass)))
3328               // ok to cast to 'id'.
3329               // casting to id<p-list> is ok if bridge type adopts all of
3330               // p-list protocols.
3331               return true;
3332             else {
3333               S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3334                 << T << Target->getName() << castType;
3335               S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3336               S.Diag(Target->getLocStart(), diag::note_declared_at);
3337               return true;
3338            }
3339           }
3340         }
3341         S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
3342           << castExpr->getType() << Parm;
3343         S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3344         if (Target)
3345           S.Diag(Target->getLocStart(), diag::note_declared_at);
3346       }
3347       return true;
3348     }
3349     T = TDNDecl->getUnderlyingType();
3350   }
3351   return false;
3352 }
3353 
3354 template <typename TB>
3355 static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr) {
3356   QualType T = castType;
3357   while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3358     TypedefNameDecl *TDNDecl = TD->getDecl();
3359     if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
3360       if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3361         NamedDecl *Target = 0;
3362         // Check for an existing type with this name.
3363         LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3364                        Sema::LookupOrdinaryName);
3365         if (S.LookupName(R, S.TUScope)) {
3366           Target = R.getFoundDecl();
3367           if (Target && isa<ObjCInterfaceDecl>(Target)) {
3368             ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3369             if (const ObjCObjectPointerType *InterfacePointerType =
3370                   castExpr->getType()->getAsObjCInterfacePointerType()) {
3371               ObjCInterfaceDecl *ExprClass
3372                 = InterfacePointerType->getObjectType()->getInterface();
3373               if ((CastClass == ExprClass) ||
3374                   (ExprClass && CastClass->isSuperClassOf(ExprClass)))
3375                 return true;
3376               S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3377                 << castExpr->getType()->getPointeeType() << T;
3378               S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3379               return true;
3380             } else if (castExpr->getType()->isObjCIdType() ||
3381                        (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3382                           castExpr->getType(), CastClass)))
3383               // ok to cast an 'id' expression to a CFtype.
3384               // ok to cast an 'id<plist>' expression to CFtype provided plist
3385               // adopts all of CFtype's ObjetiveC's class plist.
3386               return true;
3387             else {
3388               S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3389                 << castExpr->getType() << castType;
3390               S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3391               S.Diag(Target->getLocStart(), diag::note_declared_at);
3392               return true;
3393             }
3394           }
3395         }
3396         S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3397         << castExpr->getType() << castType;
3398         S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3399         if (Target)
3400           S.Diag(Target->getLocStart(), diag::note_declared_at);
3401       }
3402       return true;
3403     }
3404     T = TDNDecl->getUnderlyingType();
3405   }
3406   return false;
3407 }
3408 
3409 void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
3410   // warn in presence of __bridge casting to or from a toll free bridge cast.
3411   ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3412   ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3413   if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
3414     (void)CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, true);
3415     (void)CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr, true);
3416   }
3417   else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
3418     (void)CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr);
3419     (void)CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr);
3420   }
3421 }
3422 
3423 
3424 bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3425                                             QualType DestType, QualType SrcType,
3426                                             ObjCInterfaceDecl *&RelatedClass,
3427                                             ObjCMethodDecl *&ClassMethod,
3428                                             ObjCMethodDecl *&InstanceMethod,
3429                                             TypedefNameDecl *&TDNDecl,
3430                                             bool CfToNs) {
3431   QualType T = CfToNs ? SrcType : DestType;
3432   ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3433   if (!ObjCBAttr)
3434     return false;
3435 
3436   IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3437   IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3438   IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3439   if (!RCId)
3440     return false;
3441   NamedDecl *Target = 0;
3442   // Check for an existing type with this name.
3443   LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3444                  Sema::LookupOrdinaryName);
3445   if (!LookupName(R, TUScope)) {
3446     Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
3447           << SrcType << DestType;
3448     Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3449     return false;
3450   }
3451   Target = R.getFoundDecl();
3452   if (Target && isa<ObjCInterfaceDecl>(Target))
3453     RelatedClass = cast<ObjCInterfaceDecl>(Target);
3454   else {
3455     Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3456           << SrcType << DestType;
3457     Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3458     if (Target)
3459       Diag(Target->getLocStart(), diag::note_declared_at);
3460     return false;
3461   }
3462 
3463   // Check for an existing class method with the given selector name.
3464   if (CfToNs && CMId) {
3465     Selector Sel = Context.Selectors.getUnarySelector(CMId);
3466     ClassMethod = RelatedClass->lookupMethod(Sel, false);
3467     if (!ClassMethod) {
3468       Diag(Loc, diag::err_objc_bridged_related_known_method)
3469             << SrcType << DestType << Sel << false;
3470       Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3471       return false;
3472     }
3473   }
3474 
3475   // Check for an existing instance method with the given selector name.
3476   if (!CfToNs && IMId) {
3477     Selector Sel = Context.Selectors.getNullarySelector(IMId);
3478     InstanceMethod = RelatedClass->lookupMethod(Sel, true);
3479     if (!InstanceMethod) {
3480       Diag(Loc, diag::err_objc_bridged_related_known_method)
3481             << SrcType << DestType << Sel << true;
3482       Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3483       return false;
3484     }
3485   }
3486   return true;
3487 }
3488 
3489 bool
3490 Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
3491                                         QualType DestType, QualType SrcType,
3492                                         Expr *&SrcExpr) {
3493   ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
3494   ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
3495   bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
3496   bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
3497   if (!CfToNs && !NsToCf)
3498     return false;
3499 
3500   ObjCInterfaceDecl *RelatedClass;
3501   ObjCMethodDecl *ClassMethod = 0;
3502   ObjCMethodDecl *InstanceMethod = 0;
3503   TypedefNameDecl *TDNDecl = 0;
3504   if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
3505                                         ClassMethod, InstanceMethod, TDNDecl, CfToNs))
3506     return false;
3507 
3508   if (CfToNs) {
3509     // Implicit conversion from CF to ObjC object is needed.
3510     if (ClassMethod) {
3511       std::string ExpressionString = "[";
3512       ExpressionString += RelatedClass->getNameAsString();
3513       ExpressionString += " ";
3514       ExpressionString += ClassMethod->getSelector().getAsString();
3515       SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
3516       // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
3517       Diag(Loc, diag::err_objc_bridged_related_known_method)
3518         << SrcType << DestType << ClassMethod->getSelector() << false
3519         << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
3520         << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
3521       Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3522       Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3523 
3524       QualType receiverType =
3525         Context.getObjCInterfaceType(RelatedClass);
3526       // Argument.
3527       Expr *args[] = { SrcExpr };
3528       ExprResult msg = BuildClassMessageImplicit(receiverType, false,
3529                                       ClassMethod->getLocation(),
3530                                       ClassMethod->getSelector(), ClassMethod,
3531                                       MultiExprArg(args, 1));
3532       SrcExpr = msg.take();
3533       return true;
3534     }
3535   }
3536   else {
3537     // Implicit conversion from ObjC type to CF object is needed.
3538     if (InstanceMethod) {
3539       std::string ExpressionString;
3540       SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
3541       if (InstanceMethod->isPropertyAccessor())
3542         if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) {
3543           // fixit: ObjectExpr.propertyname when it is  aproperty accessor.
3544           ExpressionString = ".";
3545           ExpressionString += PDecl->getNameAsString();
3546           Diag(Loc, diag::err_objc_bridged_related_known_method)
3547           << SrcType << DestType << InstanceMethod->getSelector() << true
3548           << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3549         }
3550       if (ExpressionString.empty()) {
3551         // Provide a fixit: [ObjectExpr InstanceMethod]
3552         ExpressionString = " ";
3553         ExpressionString += InstanceMethod->getSelector().getAsString();
3554         ExpressionString += "]";
3555 
3556         Diag(Loc, diag::err_objc_bridged_related_known_method)
3557         << SrcType << DestType << InstanceMethod->getSelector() << true
3558         << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
3559         << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3560       }
3561       Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3562       Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3563 
3564       ExprResult msg =
3565         BuildInstanceMessageImplicit(SrcExpr, SrcType,
3566                                      InstanceMethod->getLocation(),
3567                                      InstanceMethod->getSelector(),
3568                                      InstanceMethod, None);
3569       SrcExpr = msg.take();
3570       return true;
3571     }
3572   }
3573   return false;
3574 }
3575 
3576 Sema::ARCConversionResult
3577 Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
3578                              Expr *&castExpr, CheckedConversionKind CCK,
3579                              bool DiagnoseCFAudited) {
3580   QualType castExprType = castExpr->getType();
3581 
3582   // For the purposes of the classification, we assume reference types
3583   // will bind to temporaries.
3584   QualType effCastType = castType;
3585   if (const ReferenceType *ref = castType->getAs<ReferenceType>())
3586     effCastType = ref->getPointeeType();
3587 
3588   ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
3589   ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
3590   if (exprACTC == castACTC) {
3591     // check for viablity and report error if casting an rvalue to a
3592     // life-time qualifier.
3593     if ((castACTC == ACTC_retainable) &&
3594         (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
3595         (castType != castExprType)) {
3596       const Type *DT = castType.getTypePtr();
3597       QualType QDT = castType;
3598       // We desugar some types but not others. We ignore those
3599       // that cannot happen in a cast; i.e. auto, and those which
3600       // should not be de-sugared; i.e typedef.
3601       if (const ParenType *PT = dyn_cast<ParenType>(DT))
3602         QDT = PT->desugar();
3603       else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
3604         QDT = TP->desugar();
3605       else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
3606         QDT = AT->desugar();
3607       if (QDT != castType &&
3608           QDT.getObjCLifetime() !=  Qualifiers::OCL_None) {
3609         SourceLocation loc =
3610           (castRange.isValid() ? castRange.getBegin()
3611                               : castExpr->getExprLoc());
3612         Diag(loc, diag::err_arc_nolifetime_behavior);
3613       }
3614     }
3615     return ACR_okay;
3616   }
3617 
3618   if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
3619 
3620   // Allow all of these types to be cast to integer types (but not
3621   // vice-versa).
3622   if (castACTC == ACTC_none && castType->isIntegralType(Context))
3623     return ACR_okay;
3624 
3625   // Allow casts between pointers to lifetime types (e.g., __strong id*)
3626   // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
3627   // must be explicit.
3628   if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
3629     return ACR_okay;
3630   if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
3631       CCK != CCK_ImplicitConversion)
3632     return ACR_okay;
3633 
3634   if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation &&
3635       (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast))
3636     if (CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, false) ||
3637         CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr, false))
3638       return ACR_okay;
3639 
3640   if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3641       (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast))
3642     if (CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr) ||
3643         CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr))
3644       return ACR_okay;
3645 
3646 
3647   switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
3648   // For invalid casts, fall through.
3649   case ACC_invalid:
3650     break;
3651 
3652   // Do nothing for both bottom and +0.
3653   case ACC_bottom:
3654   case ACC_plusZero:
3655     return ACR_okay;
3656 
3657   // If the result is +1, consume it here.
3658   case ACC_plusOne:
3659     castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
3660                                         CK_ARCConsumeObject, castExpr,
3661                                         0, VK_RValue);
3662     ExprNeedsCleanups = true;
3663     return ACR_okay;
3664   }
3665 
3666   // If this is a non-implicit cast from id or block type to a
3667   // CoreFoundation type, delay complaining in case the cast is used
3668   // in an acceptable context.
3669   if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
3670       CCK != CCK_ImplicitConversion)
3671     return ACR_unbridged;
3672 
3673   // Do not issue bridge cast" diagnostic when implicit casting a cstring
3674   // to 'NSString *'. Let caller issue a normal mismatched diagnostic with
3675   // suitable fix-it.
3676   if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
3677       ConversionToObjCStringLiteralCheck(castType, castExpr))
3678     return ACR_okay;
3679 
3680   // Do not issue "bridge cast" diagnostic when implicit casting
3681   // a retainable object to a CF type parameter belonging to an audited
3682   // CF API function. Let caller issue a normal type mismatched diagnostic
3683   // instead.
3684   if (!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
3685       castACTC != ACTC_coreFoundation)
3686     diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3687                               castExpr, castExpr, exprACTC, CCK);
3688   return ACR_okay;
3689 }
3690 
3691 /// Given that we saw an expression with the ARCUnbridgedCastTy
3692 /// placeholder type, complain bitterly.
3693 void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3694   // We expect the spurious ImplicitCastExpr to already have been stripped.
3695   assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3696   CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3697 
3698   SourceRange castRange;
3699   QualType castType;
3700   CheckedConversionKind CCK;
3701 
3702   if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3703     castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3704     castType = cast->getTypeAsWritten();
3705     CCK = CCK_CStyleCast;
3706   } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3707     castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3708     castType = cast->getTypeAsWritten();
3709     CCK = CCK_OtherCast;
3710   } else {
3711     castType = cast->getType();
3712     CCK = CCK_ImplicitConversion;
3713   }
3714 
3715   ARCConversionTypeClass castACTC =
3716     classifyTypeForARCConversion(castType.getNonReferenceType());
3717 
3718   Expr *castExpr = realCast->getSubExpr();
3719   assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3720 
3721   diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3722                             castExpr, realCast, ACTC_retainable, CCK);
3723 }
3724 
3725 /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3726 /// type, remove the placeholder cast.
3727 Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3728   assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3729 
3730   if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3731     Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3732     return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3733   } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3734     assert(uo->getOpcode() == UO_Extension);
3735     Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3736     return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3737                                    sub->getValueKind(), sub->getObjectKind(),
3738                                        uo->getOperatorLoc());
3739   } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3740     assert(!gse->isResultDependent());
3741 
3742     unsigned n = gse->getNumAssocs();
3743     SmallVector<Expr*, 4> subExprs(n);
3744     SmallVector<TypeSourceInfo*, 4> subTypes(n);
3745     for (unsigned i = 0; i != n; ++i) {
3746       subTypes[i] = gse->getAssocTypeSourceInfo(i);
3747       Expr *sub = gse->getAssocExpr(i);
3748       if (i == gse->getResultIndex())
3749         sub = stripARCUnbridgedCast(sub);
3750       subExprs[i] = sub;
3751     }
3752 
3753     return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3754                                               gse->getControllingExpr(),
3755                                               subTypes, subExprs,
3756                                               gse->getDefaultLoc(),
3757                                               gse->getRParenLoc(),
3758                                        gse->containsUnexpandedParameterPack(),
3759                                               gse->getResultIndex());
3760   } else {
3761     assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3762     return cast<ImplicitCastExpr>(e)->getSubExpr();
3763   }
3764 }
3765 
3766 bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3767                                                  QualType exprType) {
3768   QualType canCastType =
3769     Context.getCanonicalType(castType).getUnqualifiedType();
3770   QualType canExprType =
3771     Context.getCanonicalType(exprType).getUnqualifiedType();
3772   if (isa<ObjCObjectPointerType>(canCastType) &&
3773       castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3774       canExprType->isObjCObjectPointerType()) {
3775     if (const ObjCObjectPointerType *ObjT =
3776         canExprType->getAs<ObjCObjectPointerType>())
3777       if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
3778         return !ObjI->isArcWeakrefUnavailable();
3779   }
3780   return true;
3781 }
3782 
3783 /// Look for an ObjCReclaimReturnedObject cast and destroy it.
3784 static Expr *maybeUndoReclaimObject(Expr *e) {
3785   // For now, we just undo operands that are *immediately* reclaim
3786   // expressions, which prevents the vast majority of potential
3787   // problems here.  To catch them all, we'd need to rebuild arbitrary
3788   // value-propagating subexpressions --- we can't reliably rebuild
3789   // in-place because of expression sharing.
3790   if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
3791     if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
3792       return ice->getSubExpr();
3793 
3794   return e;
3795 }
3796 
3797 ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
3798                                       ObjCBridgeCastKind Kind,
3799                                       SourceLocation BridgeKeywordLoc,
3800                                       TypeSourceInfo *TSInfo,
3801                                       Expr *SubExpr) {
3802   ExprResult SubResult = UsualUnaryConversions(SubExpr);
3803   if (SubResult.isInvalid()) return ExprError();
3804   SubExpr = SubResult.take();
3805 
3806   QualType T = TSInfo->getType();
3807   QualType FromType = SubExpr->getType();
3808 
3809   CastKind CK;
3810 
3811   bool MustConsume = false;
3812   if (T->isDependentType() || SubExpr->isTypeDependent()) {
3813     // Okay: we'll build a dependent expression type.
3814     CK = CK_Dependent;
3815   } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
3816     // Casting CF -> id
3817     CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
3818                                   : CK_CPointerToObjCPointerCast);
3819     switch (Kind) {
3820     case OBC_Bridge:
3821       break;
3822 
3823     case OBC_BridgeRetained: {
3824       bool br = isKnownName("CFBridgingRelease");
3825       Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3826         << 2
3827         << FromType
3828         << (T->isBlockPointerType()? 1 : 0)
3829         << T
3830         << SubExpr->getSourceRange()
3831         << Kind;
3832       Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3833         << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
3834       Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
3835         << FromType << br
3836         << FixItHint::CreateReplacement(BridgeKeywordLoc,
3837                                         br ? "CFBridgingRelease "
3838                                            : "__bridge_transfer ");
3839 
3840       Kind = OBC_Bridge;
3841       break;
3842     }
3843 
3844     case OBC_BridgeTransfer:
3845       // We must consume the Objective-C object produced by the cast.
3846       MustConsume = true;
3847       break;
3848     }
3849   } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
3850     // Okay: id -> CF
3851     CK = CK_BitCast;
3852     switch (Kind) {
3853     case OBC_Bridge:
3854       // Reclaiming a value that's going to be __bridge-casted to CF
3855       // is very dangerous, so we don't do it.
3856       SubExpr = maybeUndoReclaimObject(SubExpr);
3857       break;
3858 
3859     case OBC_BridgeRetained:
3860       // Produce the object before casting it.
3861       SubExpr = ImplicitCastExpr::Create(Context, FromType,
3862                                          CK_ARCProduceObject,
3863                                          SubExpr, 0, VK_RValue);
3864       break;
3865 
3866     case OBC_BridgeTransfer: {
3867       bool br = isKnownName("CFBridgingRetain");
3868       Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3869         << (FromType->isBlockPointerType()? 1 : 0)
3870         << FromType
3871         << 2
3872         << T
3873         << SubExpr->getSourceRange()
3874         << Kind;
3875 
3876       Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3877         << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
3878       Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
3879         << T << br
3880         << FixItHint::CreateReplacement(BridgeKeywordLoc,
3881                           br ? "CFBridgingRetain " : "__bridge_retained");
3882 
3883       Kind = OBC_Bridge;
3884       break;
3885     }
3886     }
3887   } else {
3888     Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
3889       << FromType << T << Kind
3890       << SubExpr->getSourceRange()
3891       << TSInfo->getTypeLoc().getSourceRange();
3892     return ExprError();
3893   }
3894 
3895   Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
3896                                                    BridgeKeywordLoc,
3897                                                    TSInfo, SubExpr);
3898 
3899   if (MustConsume) {
3900     ExprNeedsCleanups = true;
3901     Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
3902                                       0, VK_RValue);
3903   }
3904 
3905   return Result;
3906 }
3907 
3908 ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
3909                                       SourceLocation LParenLoc,
3910                                       ObjCBridgeCastKind Kind,
3911                                       SourceLocation BridgeKeywordLoc,
3912                                       ParsedType Type,
3913                                       SourceLocation RParenLoc,
3914                                       Expr *SubExpr) {
3915   TypeSourceInfo *TSInfo = 0;
3916   QualType T = GetTypeFromParser(Type, &TSInfo);
3917   if (Kind == OBC_Bridge)
3918     CheckTollFreeBridgeCast(T, SubExpr);
3919   if (!TSInfo)
3920     TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
3921   return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
3922                               SubExpr);
3923 }
3924