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