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