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