Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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