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