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