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