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