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