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