Bug Summary

File:tools/clang/lib/Sema/SemaExprObjC.cpp
Warning:line 1708, column 14
Called C++ object pointer is null

Annotated Source Code

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