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