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/Sema/Lookup.h"
16 #include "clang/Sema/Scope.h"
17 #include "clang/Sema/ScopeInfo.h"
18 #include "clang/Sema/Initialization.h"
19 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/StmtVisitor.h"
24 #include "clang/AST/TypeLoc.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "clang/Lex/Preprocessor.h"
27 
28 using namespace clang;
29 using namespace sema;
30 using llvm::makeArrayRef;
31 
32 ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
33                                         Expr **strings,
34                                         unsigned NumStrings) {
35   StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
36 
37   // Most ObjC strings are formed out of a single piece.  However, we *can*
38   // have strings formed out of multiple @ strings with multiple pptokens in
39   // each one, e.g. @"foo" "bar" @"baz" "qux"   which need to be turned into one
40   // StringLiteral for ObjCStringLiteral to hold onto.
41   StringLiteral *S = Strings[0];
42 
43   // If we have a multi-part string, merge it all together.
44   if (NumStrings != 1) {
45     // Concatenate objc strings.
46     llvm::SmallString<128> StrBuf;
47     SmallVector<SourceLocation, 8> StrLocs;
48 
49     for (unsigned i = 0; i != NumStrings; ++i) {
50       S = Strings[i];
51 
52       // ObjC strings can't be wide or UTF.
53       if (!S->isAscii()) {
54         Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
55           << S->getSourceRange();
56         return true;
57       }
58 
59       // Append the string.
60       StrBuf += S->getString();
61 
62       // Get the locations of the string tokens.
63       StrLocs.append(S->tokloc_begin(), S->tokloc_end());
64     }
65 
66     // Create the aggregate string with the appropriate content and location
67     // information.
68     S = StringLiteral::Create(Context, StrBuf,
69                               StringLiteral::Ascii, /*Pascal=*/false,
70                               Context.getPointerType(Context.CharTy),
71                               &StrLocs[0], StrLocs.size());
72   }
73 
74   // Verify that this composite string is acceptable for ObjC strings.
75   if (CheckObjCString(S))
76     return true;
77 
78   // Initialize the constant string interface lazily. This assumes
79   // the NSString interface is seen in this translation unit. Note: We
80   // don't use NSConstantString, since the runtime team considers this
81   // interface private (even though it appears in the header files).
82   QualType Ty = Context.getObjCConstantStringInterface();
83   if (!Ty.isNull()) {
84     Ty = Context.getObjCObjectPointerType(Ty);
85   } else if (getLangOptions().NoConstantCFStrings) {
86     IdentifierInfo *NSIdent=0;
87     std::string StringClass(getLangOptions().ObjCConstantStringClass);
88 
89     if (StringClass.empty())
90       NSIdent = &Context.Idents.get("NSConstantString");
91     else
92       NSIdent = &Context.Idents.get(StringClass);
93 
94     NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
95                                      LookupOrdinaryName);
96     if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
97       Context.setObjCConstantStringInterface(StrIF);
98       Ty = Context.getObjCConstantStringInterface();
99       Ty = Context.getObjCObjectPointerType(Ty);
100     } else {
101       // If there is no NSConstantString interface defined then treat this
102       // as error and recover from it.
103       Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
104         << S->getSourceRange();
105       Ty = Context.getObjCIdType();
106     }
107   } else {
108     IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
109     NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
110                                      LookupOrdinaryName);
111     if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
112       Context.setObjCConstantStringInterface(StrIF);
113       Ty = Context.getObjCConstantStringInterface();
114       Ty = Context.getObjCObjectPointerType(Ty);
115     } else {
116       // If there is no NSString interface defined then treat constant
117       // strings as untyped objects and let the runtime figure it out later.
118       Ty = Context.getObjCIdType();
119     }
120   }
121 
122   return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
123 }
124 
125 ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
126                                       TypeSourceInfo *EncodedTypeInfo,
127                                       SourceLocation RParenLoc) {
128   QualType EncodedType = EncodedTypeInfo->getType();
129   QualType StrTy;
130   if (EncodedType->isDependentType())
131     StrTy = Context.DependentTy;
132   else {
133     if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
134         !EncodedType->isVoidType()) // void is handled too.
135       if (RequireCompleteType(AtLoc, EncodedType,
136                          PDiag(diag::err_incomplete_type_objc_at_encode)
137                              << EncodedTypeInfo->getTypeLoc().getSourceRange()))
138         return ExprError();
139 
140     std::string Str;
141     Context.getObjCEncodingForType(EncodedType, Str);
142 
143     // The type of @encode is the same as the type of the corresponding string,
144     // which is an array type.
145     StrTy = Context.CharTy;
146     // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
147     if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
148       StrTy.addConst();
149     StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
150                                          ArrayType::Normal, 0);
151   }
152 
153   return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
154 }
155 
156 ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
157                                            SourceLocation EncodeLoc,
158                                            SourceLocation LParenLoc,
159                                            ParsedType ty,
160                                            SourceLocation RParenLoc) {
161   // FIXME: Preserve type source info ?
162   TypeSourceInfo *TInfo;
163   QualType EncodedType = GetTypeFromParser(ty, &TInfo);
164   if (!TInfo)
165     TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
166                                              PP.getLocForEndOfToken(LParenLoc));
167 
168   return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
169 }
170 
171 ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
172                                              SourceLocation AtLoc,
173                                              SourceLocation SelLoc,
174                                              SourceLocation LParenLoc,
175                                              SourceLocation RParenLoc) {
176   ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
177                              SourceRange(LParenLoc, RParenLoc), false, false);
178   if (!Method)
179     Method = LookupFactoryMethodInGlobalPool(Sel,
180                                           SourceRange(LParenLoc, RParenLoc));
181   if (!Method)
182     Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
183 
184   if (!Method ||
185       Method->getImplementationControl() != ObjCMethodDecl::Optional) {
186     llvm::DenseMap<Selector, SourceLocation>::iterator Pos
187       = ReferencedSelectors.find(Sel);
188     if (Pos == ReferencedSelectors.end())
189       ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
190   }
191 
192   // In ARC, forbid the user from using @selector for
193   // retain/release/autorelease/dealloc/retainCount.
194   if (getLangOptions().ObjCAutoRefCount) {
195     switch (Sel.getMethodFamily()) {
196     case OMF_retain:
197     case OMF_release:
198     case OMF_autorelease:
199     case OMF_retainCount:
200     case OMF_dealloc:
201       Diag(AtLoc, diag::err_arc_illegal_selector) <<
202         Sel << SourceRange(LParenLoc, RParenLoc);
203       break;
204 
205     case OMF_None:
206     case OMF_alloc:
207     case OMF_copy:
208     case OMF_finalize:
209     case OMF_init:
210     case OMF_mutableCopy:
211     case OMF_new:
212     case OMF_self:
213     case OMF_performSelector:
214       break;
215     }
216   }
217   QualType Ty = Context.getObjCSelType();
218   return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
219 }
220 
221 ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
222                                              SourceLocation AtLoc,
223                                              SourceLocation ProtoLoc,
224                                              SourceLocation LParenLoc,
225                                              SourceLocation RParenLoc) {
226   ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
227   if (!PDecl) {
228     Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
229     return true;
230   }
231 
232   QualType Ty = Context.getObjCProtoType();
233   if (Ty.isNull())
234     return true;
235   Ty = Context.getObjCObjectPointerType(Ty);
236   return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
237 }
238 
239 /// Try to capture an implicit reference to 'self'.
240 ObjCMethodDecl *Sema::tryCaptureObjCSelf() {
241   // Ignore block scopes: we can capture through them.
242   DeclContext *DC = CurContext;
243   while (true) {
244     if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
245     else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
246     else break;
247   }
248 
249   // If we're not in an ObjC method, error out.  Note that, unlike the
250   // C++ case, we don't require an instance method --- class methods
251   // still have a 'self', and we really do still need to capture it!
252   ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
253   if (!method)
254     return 0;
255 
256   ImplicitParamDecl *self = method->getSelfDecl();
257   assert(self && "capturing 'self' in non-definition?");
258 
259   // Mark that we're closing on 'this' in all the block scopes, if applicable.
260   for (unsigned idx = FunctionScopes.size() - 1;
261        isa<BlockScopeInfo>(FunctionScopes[idx]);
262        --idx) {
263     BlockScopeInfo *blockScope = cast<BlockScopeInfo>(FunctionScopes[idx]);
264     unsigned &captureIndex = blockScope->CaptureMap[self];
265     if (captureIndex) break;
266 
267     bool nested = isa<BlockScopeInfo>(FunctionScopes[idx-1]);
268     blockScope->Captures.push_back(
269               BlockDecl::Capture(self, /*byref*/ false, nested, /*copy*/ 0));
270     captureIndex = blockScope->Captures.size(); // +1
271   }
272 
273   return method;
274 }
275 
276 static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
277   if (T == Context.getObjCInstanceType())
278     return Context.getObjCIdType();
279 
280   return T;
281 }
282 
283 QualType Sema::getMessageSendResultType(QualType ReceiverType,
284                                         ObjCMethodDecl *Method,
285                                     bool isClassMessage, bool isSuperMessage) {
286   assert(Method && "Must have a method");
287   if (!Method->hasRelatedResultType())
288     return Method->getSendResultType();
289 
290   // If a method has a related return type:
291   //   - if the method found is an instance method, but the message send
292   //     was a class message send, T is the declared return type of the method
293   //     found
294   if (Method->isInstanceMethod() && isClassMessage)
295     return stripObjCInstanceType(Context, Method->getSendResultType());
296 
297   //   - if the receiver is super, T is a pointer to the class of the
298   //     enclosing method definition
299   if (isSuperMessage) {
300     if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
301       if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
302         return Context.getObjCObjectPointerType(
303                                         Context.getObjCInterfaceType(Class));
304   }
305 
306   //   - if the receiver is the name of a class U, T is a pointer to U
307   if (ReceiverType->getAs<ObjCInterfaceType>() ||
308       ReceiverType->isObjCQualifiedInterfaceType())
309     return Context.getObjCObjectPointerType(ReceiverType);
310   //   - if the receiver is of type Class or qualified Class type,
311   //     T is the declared return type of the method.
312   if (ReceiverType->isObjCClassType() ||
313       ReceiverType->isObjCQualifiedClassType())
314     return stripObjCInstanceType(Context, Method->getSendResultType());
315 
316   //   - if the receiver is id, qualified id, Class, or qualified Class, T
317   //     is the receiver type, otherwise
318   //   - T is the type of the receiver expression.
319   return ReceiverType;
320 }
321 
322 void Sema::EmitRelatedResultTypeNote(const Expr *E) {
323   E = E->IgnoreParenImpCasts();
324   const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
325   if (!MsgSend)
326     return;
327 
328   const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
329   if (!Method)
330     return;
331 
332   if (!Method->hasRelatedResultType())
333     return;
334 
335   if (Context.hasSameUnqualifiedType(Method->getResultType()
336                                                         .getNonReferenceType(),
337                                      MsgSend->getType()))
338     return;
339 
340   if (!Context.hasSameUnqualifiedType(Method->getResultType(),
341                                       Context.getObjCInstanceType()))
342     return;
343 
344   Diag(Method->getLocation(), diag::note_related_result_type_inferred)
345     << Method->isInstanceMethod() << Method->getSelector()
346     << MsgSend->getType();
347 }
348 
349 bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
350                                      Expr **Args, unsigned NumArgs,
351                                      Selector Sel, ObjCMethodDecl *Method,
352                                      bool isClassMessage, bool isSuperMessage,
353                                      SourceLocation lbrac, SourceLocation rbrac,
354                                      QualType &ReturnType, ExprValueKind &VK) {
355   if (!Method) {
356     // Apply default argument promotion as for (C99 6.5.2.2p6).
357     for (unsigned i = 0; i != NumArgs; i++) {
358       if (Args[i]->isTypeDependent())
359         continue;
360 
361       ExprResult Result = DefaultArgumentPromotion(Args[i]);
362       if (Result.isInvalid())
363         return true;
364       Args[i] = Result.take();
365     }
366 
367     unsigned DiagID;
368     if (getLangOptions().ObjCAutoRefCount)
369       DiagID = diag::err_arc_method_not_found;
370     else
371       DiagID = isClassMessage ? diag::warn_class_method_not_found
372                               : diag::warn_inst_method_not_found;
373     if (!getLangOptions().DebuggerSupport)
374       Diag(lbrac, DiagID)
375         << Sel << isClassMessage << SourceRange(lbrac, rbrac);
376 
377     // In debuggers, we want to use __unknown_anytype for these
378     // results so that clients can cast them.
379     if (getLangOptions().DebuggerSupport) {
380       ReturnType = Context.UnknownAnyTy;
381     } else {
382       ReturnType = Context.getObjCIdType();
383     }
384     VK = VK_RValue;
385     return false;
386   }
387 
388   ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
389                                         isSuperMessage);
390   VK = Expr::getValueKindForType(Method->getResultType());
391 
392   unsigned NumNamedArgs = Sel.getNumArgs();
393   // Method might have more arguments than selector indicates. This is due
394   // to addition of c-style arguments in method.
395   if (Method->param_size() > Sel.getNumArgs())
396     NumNamedArgs = Method->param_size();
397   // FIXME. This need be cleaned up.
398   if (NumArgs < NumNamedArgs) {
399     Diag(lbrac, diag::err_typecheck_call_too_few_args)
400       << 2 << NumNamedArgs << NumArgs;
401     return false;
402   }
403 
404   bool IsError = false;
405   for (unsigned i = 0; i < NumNamedArgs; i++) {
406     // We can't do any type-checking on a type-dependent argument.
407     if (Args[i]->isTypeDependent())
408       continue;
409 
410     Expr *argExpr = Args[i];
411 
412     ParmVarDecl *param = Method->param_begin()[i];
413     assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
414 
415     // Strip the unbridged-cast placeholder expression off unless it's
416     // a consumed argument.
417     if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
418         !param->hasAttr<CFConsumedAttr>())
419       argExpr = stripARCUnbridgedCast(argExpr);
420 
421     if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
422                             param->getType(),
423                             PDiag(diag::err_call_incomplete_argument)
424                               << argExpr->getSourceRange()))
425       return true;
426 
427     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
428                                                                       param);
429     ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
430     if (ArgE.isInvalid())
431       IsError = true;
432     else
433       Args[i] = ArgE.takeAs<Expr>();
434   }
435 
436   // Promote additional arguments to variadic methods.
437   if (Method->isVariadic()) {
438     for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
439       if (Args[i]->isTypeDependent())
440         continue;
441 
442       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
443       IsError |= Arg.isInvalid();
444       Args[i] = Arg.take();
445     }
446   } else {
447     // Check for extra arguments to non-variadic methods.
448     if (NumArgs != NumNamedArgs) {
449       Diag(Args[NumNamedArgs]->getLocStart(),
450            diag::err_typecheck_call_too_many_args)
451         << 2 /*method*/ << NumNamedArgs << NumArgs
452         << Method->getSourceRange()
453         << SourceRange(Args[NumNamedArgs]->getLocStart(),
454                        Args[NumArgs-1]->getLocEnd());
455     }
456   }
457   // diagnose nonnull arguments.
458   for (specific_attr_iterator<NonNullAttr>
459        i = Method->specific_attr_begin<NonNullAttr>(),
460        e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
461     CheckNonNullArguments(*i, Args, lbrac);
462   }
463 
464   DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
465   return IsError;
466 }
467 
468 bool Sema::isSelfExpr(Expr *receiver) {
469   // 'self' is objc 'self' in an objc method only.
470   ObjCMethodDecl *method =
471     dyn_cast<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
472   if (!method) return false;
473 
474   receiver = receiver->IgnoreParenLValueCasts();
475   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
476     if (DRE->getDecl() == method->getSelfDecl())
477       return true;
478   return false;
479 }
480 
481 // Helper method for ActOnClassMethod/ActOnInstanceMethod.
482 // Will search "local" class/category implementations for a method decl.
483 // If failed, then we search in class's root for an instance method.
484 // Returns 0 if no method is found.
485 ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
486                                           ObjCInterfaceDecl *ClassDecl) {
487   ObjCMethodDecl *Method = 0;
488   // lookup in class and all superclasses
489   while (ClassDecl && !Method) {
490     if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
491       Method = ImpDecl->getClassMethod(Sel);
492 
493     // Look through local category implementations associated with the class.
494     if (!Method)
495       Method = ClassDecl->getCategoryClassMethod(Sel);
496 
497     // Before we give up, check if the selector is an instance method.
498     // But only in the root. This matches gcc's behaviour and what the
499     // runtime expects.
500     if (!Method && !ClassDecl->getSuperClass()) {
501       Method = ClassDecl->lookupInstanceMethod(Sel);
502       // Look through local category implementations associated
503       // with the root class.
504       if (!Method)
505         Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
506     }
507 
508     ClassDecl = ClassDecl->getSuperClass();
509   }
510   return Method;
511 }
512 
513 ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
514                                               ObjCInterfaceDecl *ClassDecl) {
515   ObjCMethodDecl *Method = 0;
516   while (ClassDecl && !Method) {
517     // If we have implementations in scope, check "private" methods.
518     if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
519       Method = ImpDecl->getInstanceMethod(Sel);
520 
521     // Look through local category implementations associated with the class.
522     if (!Method)
523       Method = ClassDecl->getCategoryInstanceMethod(Sel);
524     ClassDecl = ClassDecl->getSuperClass();
525   }
526   return Method;
527 }
528 
529 /// LookupMethodInType - Look up a method in an ObjCObjectType.
530 ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
531                                                bool isInstance) {
532   const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
533   if (ObjCInterfaceDecl *iface = objType->getInterface()) {
534     // Look it up in the main interface (and categories, etc.)
535     if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
536       return method;
537 
538     // Okay, look for "private" methods declared in any
539     // @implementations we've seen.
540     if (isInstance) {
541       if (ObjCMethodDecl *method = LookupPrivateInstanceMethod(sel, iface))
542         return method;
543     } else {
544       if (ObjCMethodDecl *method = LookupPrivateClassMethod(sel, iface))
545         return method;
546     }
547   }
548 
549   // Check qualifiers.
550   for (ObjCObjectType::qual_iterator
551          i = objType->qual_begin(), e = objType->qual_end(); i != e; ++i)
552     if (ObjCMethodDecl *method = (*i)->lookupMethod(sel, isInstance))
553       return method;
554 
555   return 0;
556 }
557 
558 /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
559 /// list of a qualified objective pointer type.
560 ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
561                                               const ObjCObjectPointerType *OPT,
562                                               bool Instance)
563 {
564   ObjCMethodDecl *MD = 0;
565   for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
566        E = OPT->qual_end(); I != E; ++I) {
567     ObjCProtocolDecl *PROTO = (*I);
568     if ((MD = PROTO->lookupMethod(Sel, Instance))) {
569       return MD;
570     }
571   }
572   return 0;
573 }
574 
575 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
576 /// objective C interface.  This is a property reference expression.
577 ExprResult Sema::
578 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
579                           Expr *BaseExpr, SourceLocation OpLoc,
580                           DeclarationName MemberName,
581                           SourceLocation MemberLoc,
582                           SourceLocation SuperLoc, QualType SuperType,
583                           bool Super) {
584   const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
585   ObjCInterfaceDecl *IFace = IFaceT->getDecl();
586 
587   if (MemberName.getNameKind() != DeclarationName::Identifier) {
588     Diag(MemberLoc, diag::err_invalid_property_name)
589       << MemberName << QualType(OPT, 0);
590     return ExprError();
591   }
592 
593   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
594   SourceRange BaseRange = Super? SourceRange(SuperLoc)
595                                : BaseExpr->getSourceRange();
596   if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
597                           PDiag(diag::err_property_not_found_forward_class)
598                             << MemberName << BaseRange))
599     return ExprError();
600 
601   // Search for a declared property first.
602   if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
603     // Check whether we can reference this property.
604     if (DiagnoseUseOfDecl(PD, MemberLoc))
605       return ExprError();
606 
607     if (Super)
608       return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
609                                                      VK_LValue, OK_ObjCProperty,
610                                                      MemberLoc,
611                                                      SuperLoc, SuperType));
612     else
613       return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
614                                                      VK_LValue, OK_ObjCProperty,
615                                                      MemberLoc, BaseExpr));
616   }
617   // Check protocols on qualified interfaces.
618   for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
619        E = OPT->qual_end(); I != E; ++I)
620     if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
621       // Check whether we can reference this property.
622       if (DiagnoseUseOfDecl(PD, MemberLoc))
623         return ExprError();
624 
625       if (Super)
626         return Owned(new (Context) ObjCPropertyRefExpr(PD,
627                                                        Context.PseudoObjectTy,
628                                                        VK_LValue,
629                                                        OK_ObjCProperty,
630                                                        MemberLoc,
631                                                        SuperLoc, SuperType));
632       else
633         return Owned(new (Context) ObjCPropertyRefExpr(PD,
634                                                        Context.PseudoObjectTy,
635                                                        VK_LValue,
636                                                        OK_ObjCProperty,
637                                                        MemberLoc,
638                                                        BaseExpr));
639     }
640   // If that failed, look for an "implicit" property by seeing if the nullary
641   // selector is implemented.
642 
643   // FIXME: The logic for looking up nullary and unary selectors should be
644   // shared with the code in ActOnInstanceMessage.
645 
646   Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
647   ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
648 
649   // May be founf in property's qualified list.
650   if (!Getter)
651     Getter = LookupMethodInQualifiedType(Sel, OPT, true);
652 
653   // If this reference is in an @implementation, check for 'private' methods.
654   if (!Getter)
655     Getter = IFace->lookupPrivateMethod(Sel);
656 
657   // Look through local category implementations associated with the class.
658   if (!Getter)
659     Getter = IFace->getCategoryInstanceMethod(Sel);
660   if (Getter) {
661     // Check if we can reference this property.
662     if (DiagnoseUseOfDecl(Getter, MemberLoc))
663       return ExprError();
664   }
665   // If we found a getter then this may be a valid dot-reference, we
666   // will look for the matching setter, in case it is needed.
667   Selector SetterSel =
668     SelectorTable::constructSetterName(PP.getIdentifierTable(),
669                                        PP.getSelectorTable(), Member);
670   ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
671 
672   // May be founf in property's qualified list.
673   if (!Setter)
674     Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
675 
676   if (!Setter) {
677     // If this reference is in an @implementation, also check for 'private'
678     // methods.
679     Setter = IFace->lookupPrivateMethod(SetterSel);
680   }
681   // Look through local category implementations associated with the class.
682   if (!Setter)
683     Setter = IFace->getCategoryInstanceMethod(SetterSel);
684 
685   if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
686     return ExprError();
687 
688   if (Getter || Setter) {
689     if (Super)
690       return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
691                                                      Context.PseudoObjectTy,
692                                                      VK_LValue, OK_ObjCProperty,
693                                                      MemberLoc,
694                                                      SuperLoc, SuperType));
695     else
696       return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
697                                                      Context.PseudoObjectTy,
698                                                      VK_LValue, OK_ObjCProperty,
699                                                      MemberLoc, BaseExpr));
700 
701   }
702 
703   // Attempt to correct for typos in property names.
704   TypoCorrection Corrected = CorrectTypo(
705       DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
706       NULL, IFace, false, CTC_NoKeywords, OPT);
707   if (ObjCPropertyDecl *Property =
708       Corrected.getCorrectionDeclAs<ObjCPropertyDecl>()) {
709     DeclarationName TypoResult = Corrected.getCorrection();
710     Diag(MemberLoc, diag::err_property_not_found_suggest)
711       << MemberName << QualType(OPT, 0) << TypoResult
712       << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
713     Diag(Property->getLocation(), diag::note_previous_decl)
714       << Property->getDeclName();
715     return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
716                                      TypoResult, MemberLoc,
717                                      SuperLoc, SuperType, Super);
718   }
719   ObjCInterfaceDecl *ClassDeclared;
720   if (ObjCIvarDecl *Ivar =
721       IFace->lookupInstanceVariable(Member, ClassDeclared)) {
722     QualType T = Ivar->getType();
723     if (const ObjCObjectPointerType * OBJPT =
724         T->getAsObjCInterfacePointerType()) {
725       if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
726                               PDiag(diag::err_property_not_as_forward_class)
727                                 << MemberName << BaseExpr->getSourceRange()))
728         return ExprError();
729     }
730     Diag(MemberLoc,
731          diag::err_ivar_access_using_property_syntax_suggest)
732     << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
733     << FixItHint::CreateReplacement(OpLoc, "->");
734     return ExprError();
735   }
736 
737   Diag(MemberLoc, diag::err_property_not_found)
738     << MemberName << QualType(OPT, 0);
739   if (Setter)
740     Diag(Setter->getLocation(), diag::note_getter_unavailable)
741           << MemberName << BaseExpr->getSourceRange();
742   return ExprError();
743 }
744 
745 
746 
747 ExprResult Sema::
748 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
749                           IdentifierInfo &propertyName,
750                           SourceLocation receiverNameLoc,
751                           SourceLocation propertyNameLoc) {
752 
753   IdentifierInfo *receiverNamePtr = &receiverName;
754   ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
755                                                   receiverNameLoc);
756 
757   bool IsSuper = false;
758   if (IFace == 0) {
759     // If the "receiver" is 'super' in a method, handle it as an expression-like
760     // property reference.
761     if (receiverNamePtr->isStr("super")) {
762       IsSuper = true;
763 
764       if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf()) {
765         if (CurMethod->isInstanceMethod()) {
766           QualType T =
767             Context.getObjCInterfaceType(CurMethod->getClassInterface());
768           T = Context.getObjCObjectPointerType(T);
769 
770           return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
771                                            /*BaseExpr*/0,
772                                            SourceLocation()/*OpLoc*/,
773                                            &propertyName,
774                                            propertyNameLoc,
775                                            receiverNameLoc, T, true);
776         }
777 
778         // Otherwise, if this is a class method, try dispatching to our
779         // superclass.
780         IFace = CurMethod->getClassInterface()->getSuperClass();
781       }
782     }
783 
784     if (IFace == 0) {
785       Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
786       return ExprError();
787     }
788   }
789 
790   // Search for a declared property first.
791   Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
792   ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
793 
794   // If this reference is in an @implementation, check for 'private' methods.
795   if (!Getter)
796     if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
797       if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
798         if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
799           Getter = ImpDecl->getClassMethod(Sel);
800 
801   if (Getter) {
802     // FIXME: refactor/share with ActOnMemberReference().
803     // Check if we can reference this property.
804     if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
805       return ExprError();
806   }
807 
808   // Look for the matching setter, in case it is needed.
809   Selector SetterSel =
810     SelectorTable::constructSetterName(PP.getIdentifierTable(),
811                                        PP.getSelectorTable(), &propertyName);
812 
813   ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
814   if (!Setter) {
815     // If this reference is in an @implementation, also check for 'private'
816     // methods.
817     if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
818       if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
819         if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
820           Setter = ImpDecl->getClassMethod(SetterSel);
821   }
822   // Look through local category implementations associated with the class.
823   if (!Setter)
824     Setter = IFace->getCategoryClassMethod(SetterSel);
825 
826   if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
827     return ExprError();
828 
829   if (Getter || Setter) {
830     if (IsSuper)
831     return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
832                                                    Context.PseudoObjectTy,
833                                                    VK_LValue, OK_ObjCProperty,
834                                                    propertyNameLoc,
835                                                    receiverNameLoc,
836                                           Context.getObjCInterfaceType(IFace)));
837 
838     return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
839                                                    Context.PseudoObjectTy,
840                                                    VK_LValue, OK_ObjCProperty,
841                                                    propertyNameLoc,
842                                                    receiverNameLoc, IFace));
843   }
844   return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
845                      << &propertyName << Context.getObjCInterfaceType(IFace));
846 }
847 
848 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
849                                                IdentifierInfo *Name,
850                                                SourceLocation NameLoc,
851                                                bool IsSuper,
852                                                bool HasTrailingDot,
853                                                ParsedType &ReceiverType) {
854   ReceiverType = ParsedType();
855 
856   // If the identifier is "super" and there is no trailing dot, we're
857   // messaging super. If the identifier is "super" and there is a
858   // trailing dot, it's an instance message.
859   if (IsSuper && S->isInObjcMethodScope())
860     return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
861 
862   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
863   LookupName(Result, S);
864 
865   switch (Result.getResultKind()) {
866   case LookupResult::NotFound:
867     // Normal name lookup didn't find anything. If we're in an
868     // Objective-C method, look for ivars. If we find one, we're done!
869     // FIXME: This is a hack. Ivar lookup should be part of normal
870     // lookup.
871     if (ObjCMethodDecl *Method = getCurMethodDecl()) {
872       if (!Method->getClassInterface()) {
873         // Fall back: let the parser try to parse it as an instance message.
874         return ObjCInstanceMessage;
875       }
876 
877       ObjCInterfaceDecl *ClassDeclared;
878       if (Method->getClassInterface()->lookupInstanceVariable(Name,
879                                                               ClassDeclared))
880         return ObjCInstanceMessage;
881     }
882 
883     // Break out; we'll perform typo correction below.
884     break;
885 
886   case LookupResult::NotFoundInCurrentInstantiation:
887   case LookupResult::FoundOverloaded:
888   case LookupResult::FoundUnresolvedValue:
889   case LookupResult::Ambiguous:
890     Result.suppressDiagnostics();
891     return ObjCInstanceMessage;
892 
893   case LookupResult::Found: {
894     // If the identifier is a class or not, and there is a trailing dot,
895     // it's an instance message.
896     if (HasTrailingDot)
897       return ObjCInstanceMessage;
898     // We found something. If it's a type, then we have a class
899     // message. Otherwise, it's an instance message.
900     NamedDecl *ND = Result.getFoundDecl();
901     QualType T;
902     if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
903       T = Context.getObjCInterfaceType(Class);
904     else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
905       T = Context.getTypeDeclType(Type);
906     else
907       return ObjCInstanceMessage;
908 
909     //  We have a class message, and T is the type we're
910     //  messaging. Build source-location information for it.
911     TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
912     ReceiverType = CreateParsedType(T, TSInfo);
913     return ObjCClassMessage;
914   }
915   }
916 
917   // Determine our typo-correction context.
918   CorrectTypoContext CTC = CTC_Expression;
919   if (ObjCMethodDecl *Method = getCurMethodDecl())
920     if (Method->getClassInterface() &&
921         Method->getClassInterface()->getSuperClass())
922       CTC = CTC_ObjCMessageReceiver;
923 
924   if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
925                                              Result.getLookupKind(), S, NULL,
926                                              NULL, false, CTC)) {
927     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
928       // If we found a declaration, correct when it refers to an Objective-C
929       // class.
930       if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
931         Diag(NameLoc, diag::err_unknown_receiver_suggest)
932           << Name << Corrected.getCorrection()
933           << FixItHint::CreateReplacement(SourceRange(NameLoc),
934                                           ND->getNameAsString());
935         Diag(ND->getLocation(), diag::note_previous_decl)
936           << Corrected.getCorrection();
937 
938         QualType T = Context.getObjCInterfaceType(Class);
939         TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
940         ReceiverType = CreateParsedType(T, TSInfo);
941         return ObjCClassMessage;
942       }
943     } else if (Corrected.isKeyword() &&
944                Corrected.getCorrectionAsIdentifierInfo()->isStr("super")) {
945       // If we've found the keyword "super", this is a send to super.
946       Diag(NameLoc, diag::err_unknown_receiver_suggest)
947         << Name << Corrected.getCorrection()
948         << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
949       return ObjCSuperMessage;
950     }
951   }
952 
953   // Fall back: let the parser try to parse it as an instance message.
954   return ObjCInstanceMessage;
955 }
956 
957 ExprResult Sema::ActOnSuperMessage(Scope *S,
958                                    SourceLocation SuperLoc,
959                                    Selector Sel,
960                                    SourceLocation LBracLoc,
961                                    ArrayRef<SourceLocation> SelectorLocs,
962                                    SourceLocation RBracLoc,
963                                    MultiExprArg Args) {
964   // Determine whether we are inside a method or not.
965   ObjCMethodDecl *Method = tryCaptureObjCSelf();
966   if (!Method) {
967     Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
968     return ExprError();
969   }
970 
971   ObjCInterfaceDecl *Class = Method->getClassInterface();
972   if (!Class) {
973     Diag(SuperLoc, diag::error_no_super_class_message)
974       << Method->getDeclName();
975     return ExprError();
976   }
977 
978   ObjCInterfaceDecl *Super = Class->getSuperClass();
979   if (!Super) {
980     // The current class does not have a superclass.
981     Diag(SuperLoc, diag::error_root_class_cannot_use_super)
982       << Class->getIdentifier();
983     return ExprError();
984   }
985 
986   // We are in a method whose class has a superclass, so 'super'
987   // is acting as a keyword.
988   if (Method->isInstanceMethod()) {
989     if (Sel.getMethodFamily() == OMF_dealloc)
990       ObjCShouldCallSuperDealloc = false;
991     if (Sel.getMethodFamily() == OMF_finalize)
992       ObjCShouldCallSuperFinalize = false;
993 
994     // Since we are in an instance method, this is an instance
995     // message to the superclass instance.
996     QualType SuperTy = Context.getObjCInterfaceType(Super);
997     SuperTy = Context.getObjCObjectPointerType(SuperTy);
998     return BuildInstanceMessage(0, SuperTy, SuperLoc,
999                                 Sel, /*Method=*/0,
1000                                 LBracLoc, SelectorLocs, RBracLoc, move(Args));
1001   }
1002 
1003   // Since we are in a class method, this is a class message to
1004   // the superclass.
1005   return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1006                            Context.getObjCInterfaceType(Super),
1007                            SuperLoc, Sel, /*Method=*/0,
1008                            LBracLoc, SelectorLocs, RBracLoc, move(Args));
1009 }
1010 
1011 /// \brief Build an Objective-C class message expression.
1012 ///
1013 /// This routine takes care of both normal class messages and
1014 /// class messages to the superclass.
1015 ///
1016 /// \param ReceiverTypeInfo Type source information that describes the
1017 /// receiver of this message. This may be NULL, in which case we are
1018 /// sending to the superclass and \p SuperLoc must be a valid source
1019 /// location.
1020 
1021 /// \param ReceiverType The type of the object receiving the
1022 /// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1023 /// type as that refers to. For a superclass send, this is the type of
1024 /// the superclass.
1025 ///
1026 /// \param SuperLoc The location of the "super" keyword in a
1027 /// superclass message.
1028 ///
1029 /// \param Sel The selector to which the message is being sent.
1030 ///
1031 /// \param Method The method that this class message is invoking, if
1032 /// already known.
1033 ///
1034 /// \param LBracLoc The location of the opening square bracket ']'.
1035 ///
1036 /// \param RBrac The location of the closing square bracket ']'.
1037 ///
1038 /// \param Args The message arguments.
1039 ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
1040                                    QualType ReceiverType,
1041                                    SourceLocation SuperLoc,
1042                                    Selector Sel,
1043                                    ObjCMethodDecl *Method,
1044                                    SourceLocation LBracLoc,
1045                                    ArrayRef<SourceLocation> SelectorLocs,
1046                                    SourceLocation RBracLoc,
1047                                    MultiExprArg ArgsIn) {
1048   SourceLocation Loc = SuperLoc.isValid()? SuperLoc
1049     : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
1050   if (LBracLoc.isInvalid()) {
1051     Diag(Loc, diag::err_missing_open_square_message_send)
1052       << FixItHint::CreateInsertion(Loc, "[");
1053     LBracLoc = Loc;
1054   }
1055 
1056   if (ReceiverType->isDependentType()) {
1057     // If the receiver type is dependent, we can't type-check anything
1058     // at this point. Build a dependent expression.
1059     unsigned NumArgs = ArgsIn.size();
1060     Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1061     assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1062     return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1063                                          VK_RValue, LBracLoc, ReceiverTypeInfo,
1064                                          Sel, SelectorLocs, /*Method=*/0,
1065                                          makeArrayRef(Args, NumArgs),RBracLoc));
1066   }
1067 
1068   // Find the class to which we are sending this message.
1069   ObjCInterfaceDecl *Class = 0;
1070   const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1071   if (!ClassType || !(Class = ClassType->getInterface())) {
1072     Diag(Loc, diag::err_invalid_receiver_class_message)
1073       << ReceiverType;
1074     return ExprError();
1075   }
1076   assert(Class && "We don't know which class we're messaging?");
1077   // objc++ diagnoses during typename annotation.
1078   if (!getLangOptions().CPlusPlus)
1079     (void)DiagnoseUseOfDecl(Class, Loc);
1080   // Find the method we are messaging.
1081   if (!Method) {
1082     SourceRange TypeRange
1083       = SuperLoc.isValid()? SourceRange(SuperLoc)
1084                           : ReceiverTypeInfo->getTypeLoc().getSourceRange();
1085     if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
1086                             (getLangOptions().ObjCAutoRefCount
1087                                ? PDiag(diag::err_arc_receiver_forward_class)
1088                                : PDiag(diag::warn_receiver_forward_class))
1089                                    << TypeRange)) {
1090       // A forward class used in messaging is treated as a 'Class'
1091       Method = LookupFactoryMethodInGlobalPool(Sel,
1092                                                SourceRange(LBracLoc, RBracLoc));
1093       if (Method && !getLangOptions().ObjCAutoRefCount)
1094         Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1095           << Method->getDeclName();
1096     }
1097     if (!Method)
1098       Method = Class->lookupClassMethod(Sel);
1099 
1100     // If we have an implementation in scope, check "private" methods.
1101     if (!Method)
1102       Method = LookupPrivateClassMethod(Sel, Class);
1103 
1104     if (Method && DiagnoseUseOfDecl(Method, Loc))
1105       return ExprError();
1106   }
1107 
1108   // Check the argument types and determine the result type.
1109   QualType ReturnType;
1110   ExprValueKind VK = VK_RValue;
1111 
1112   unsigned NumArgs = ArgsIn.size();
1113   Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1114   if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1115                                 SuperLoc.isValid(), LBracLoc, RBracLoc,
1116                                 ReturnType, VK))
1117     return ExprError();
1118 
1119   if (Method && !Method->getResultType()->isVoidType() &&
1120       RequireCompleteType(LBracLoc, Method->getResultType(),
1121                           diag::err_illegal_message_expr_incomplete_type))
1122     return ExprError();
1123 
1124   // Construct the appropriate ObjCMessageExpr.
1125   Expr *Result;
1126   if (SuperLoc.isValid())
1127     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
1128                                      SuperLoc, /*IsInstanceSuper=*/false,
1129                                      ReceiverType, Sel, SelectorLocs,
1130                                      Method, makeArrayRef(Args, NumArgs),
1131                                      RBracLoc);
1132   else
1133     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
1134                                      ReceiverTypeInfo, Sel, SelectorLocs,
1135                                      Method, makeArrayRef(Args, NumArgs),
1136                                      RBracLoc);
1137   return MaybeBindToTemporary(Result);
1138 }
1139 
1140 // ActOnClassMessage - used for both unary and keyword messages.
1141 // ArgExprs is optional - if it is present, the number of expressions
1142 // is obtained from Sel.getNumArgs().
1143 ExprResult Sema::ActOnClassMessage(Scope *S,
1144                                    ParsedType Receiver,
1145                                    Selector Sel,
1146                                    SourceLocation LBracLoc,
1147                                    ArrayRef<SourceLocation> SelectorLocs,
1148                                    SourceLocation RBracLoc,
1149                                    MultiExprArg Args) {
1150   TypeSourceInfo *ReceiverTypeInfo;
1151   QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
1152   if (ReceiverType.isNull())
1153     return ExprError();
1154 
1155 
1156   if (!ReceiverTypeInfo)
1157     ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
1158 
1159   return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
1160                            /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
1161                            LBracLoc, SelectorLocs, RBracLoc, move(Args));
1162 }
1163 
1164 /// \brief Build an Objective-C instance message expression.
1165 ///
1166 /// This routine takes care of both normal instance messages and
1167 /// instance messages to the superclass instance.
1168 ///
1169 /// \param Receiver The expression that computes the object that will
1170 /// receive this message. This may be empty, in which case we are
1171 /// sending to the superclass instance and \p SuperLoc must be a valid
1172 /// source location.
1173 ///
1174 /// \param ReceiverType The (static) type of the object receiving the
1175 /// message. When a \p Receiver expression is provided, this is the
1176 /// same type as that expression. For a superclass instance send, this
1177 /// is a pointer to the type of the superclass.
1178 ///
1179 /// \param SuperLoc The location of the "super" keyword in a
1180 /// superclass instance message.
1181 ///
1182 /// \param Sel The selector to which the message is being sent.
1183 ///
1184 /// \param Method The method that this instance message is invoking, if
1185 /// already known.
1186 ///
1187 /// \param LBracLoc The location of the opening square bracket ']'.
1188 ///
1189 /// \param RBrac The location of the closing square bracket ']'.
1190 ///
1191 /// \param Args The message arguments.
1192 ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
1193                                       QualType ReceiverType,
1194                                       SourceLocation SuperLoc,
1195                                       Selector Sel,
1196                                       ObjCMethodDecl *Method,
1197                                       SourceLocation LBracLoc,
1198                                       ArrayRef<SourceLocation> SelectorLocs,
1199                                       SourceLocation RBracLoc,
1200                                       MultiExprArg ArgsIn) {
1201   // The location of the receiver.
1202   SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
1203 
1204   if (LBracLoc.isInvalid()) {
1205     Diag(Loc, diag::err_missing_open_square_message_send)
1206       << FixItHint::CreateInsertion(Loc, "[");
1207     LBracLoc = Loc;
1208   }
1209 
1210   // If we have a receiver expression, perform appropriate promotions
1211   // and determine receiver type.
1212   if (Receiver) {
1213     if (Receiver->hasPlaceholderType()) {
1214       ExprResult result = CheckPlaceholderExpr(Receiver);
1215       if (result.isInvalid()) return ExprError();
1216       Receiver = result.take();
1217     }
1218 
1219     if (Receiver->isTypeDependent()) {
1220       // If the receiver is type-dependent, we can't type-check anything
1221       // at this point. Build a dependent expression.
1222       unsigned NumArgs = ArgsIn.size();
1223       Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1224       assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1225       return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
1226                                            VK_RValue, LBracLoc, Receiver, Sel,
1227                                            SelectorLocs, /*Method=*/0,
1228                                            makeArrayRef(Args, NumArgs),
1229                                            RBracLoc));
1230     }
1231 
1232     // If necessary, apply function/array conversion to the receiver.
1233     // C99 6.7.5.3p[7,8].
1234     ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
1235     if (Result.isInvalid())
1236       return ExprError();
1237     Receiver = Result.take();
1238     ReceiverType = Receiver->getType();
1239   }
1240 
1241   if (!Method) {
1242     // Handle messages to id.
1243     bool receiverIsId = ReceiverType->isObjCIdType();
1244     if (receiverIsId || ReceiverType->isBlockPointerType() ||
1245         (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1246       Method = LookupInstanceMethodInGlobalPool(Sel,
1247                                                 SourceRange(LBracLoc, RBracLoc),
1248                                                 receiverIsId);
1249       if (!Method)
1250         Method = LookupFactoryMethodInGlobalPool(Sel,
1251                                                  SourceRange(LBracLoc, RBracLoc),
1252                                                  receiverIsId);
1253     } else if (ReceiverType->isObjCClassType() ||
1254                ReceiverType->isObjCQualifiedClassType()) {
1255       // Handle messages to Class.
1256       // We allow sending a message to a qualified Class ("Class<foo>"), which
1257       // is ok as long as one of the protocols implements the selector (if not, warn).
1258       if (const ObjCObjectPointerType *QClassTy
1259             = ReceiverType->getAsObjCQualifiedClassType()) {
1260         // Search protocols for class methods.
1261         Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
1262         if (!Method) {
1263           Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
1264           // warn if instance method found for a Class message.
1265           if (Method) {
1266             Diag(Loc, diag::warn_instance_method_on_class_found)
1267               << Method->getSelector() << Sel;
1268             Diag(Method->getLocation(), diag::note_method_declared_at);
1269           }
1270         }
1271       } else {
1272         if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
1273           if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
1274             // First check the public methods in the class interface.
1275             Method = ClassDecl->lookupClassMethod(Sel);
1276 
1277             if (!Method)
1278               Method = LookupPrivateClassMethod(Sel, ClassDecl);
1279           }
1280           if (Method && DiagnoseUseOfDecl(Method, Loc))
1281             return ExprError();
1282         }
1283         if (!Method) {
1284           // If not messaging 'self', look for any factory method named 'Sel'.
1285           if (!Receiver || !isSelfExpr(Receiver)) {
1286             Method = LookupFactoryMethodInGlobalPool(Sel,
1287                                                 SourceRange(LBracLoc, RBracLoc),
1288                                                      true);
1289             if (!Method) {
1290               // If no class (factory) method was found, check if an _instance_
1291               // method of the same name exists in the root class only.
1292               Method = LookupInstanceMethodInGlobalPool(Sel,
1293                                                SourceRange(LBracLoc, RBracLoc),
1294                                                         true);
1295               if (Method)
1296                   if (const ObjCInterfaceDecl *ID =
1297                       dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
1298                     if (ID->getSuperClass())
1299                       Diag(Loc, diag::warn_root_inst_method_not_found)
1300                       << Sel << SourceRange(LBracLoc, RBracLoc);
1301                   }
1302             }
1303           }
1304         }
1305       }
1306     } else {
1307       ObjCInterfaceDecl* ClassDecl = 0;
1308 
1309       // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
1310       // long as one of the protocols implements the selector (if not, warn).
1311       if (const ObjCObjectPointerType *QIdTy
1312                                    = ReceiverType->getAsObjCQualifiedIdType()) {
1313         // Search protocols for instance methods.
1314         Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
1315         if (!Method)
1316           Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
1317       } else if (const ObjCObjectPointerType *OCIType
1318                    = ReceiverType->getAsObjCInterfacePointerType()) {
1319         // We allow sending a message to a pointer to an interface (an object).
1320         ClassDecl = OCIType->getInterfaceDecl();
1321 
1322         // Try to complete the type. Under ARC, this is a hard error from which
1323         // we don't try to recover.
1324         const ObjCInterfaceDecl *forwardClass = 0;
1325         if (RequireCompleteType(Loc, OCIType->getPointeeType(),
1326               getLangOptions().ObjCAutoRefCount
1327                 ? PDiag(diag::err_arc_receiver_forward_instance)
1328                     << (Receiver ? Receiver->getSourceRange()
1329                                  : SourceRange(SuperLoc))
1330                 : PDiag())) {
1331           if (getLangOptions().ObjCAutoRefCount)
1332             return ExprError();
1333 
1334           forwardClass = OCIType->getInterfaceDecl();
1335         }
1336 
1337         // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
1338         // faster than the following method (which can do *many* linear searches).
1339         // The idea is to add class info to MethodPool.
1340         Method = ClassDecl->lookupInstanceMethod(Sel);
1341 
1342         if (!Method)
1343           // Search protocol qualifiers.
1344           Method = LookupMethodInQualifiedType(Sel, OCIType, true);
1345 
1346         if (!Method) {
1347           // If we have implementations in scope, check "private" methods.
1348           Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1349 
1350           if (!Method && getLangOptions().ObjCAutoRefCount) {
1351             Diag(Loc, diag::err_arc_may_not_respond)
1352               << OCIType->getPointeeType() << Sel;
1353             return ExprError();
1354           }
1355 
1356           if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
1357             // If we still haven't found a method, look in the global pool. This
1358             // behavior isn't very desirable, however we need it for GCC
1359             // compatibility. FIXME: should we deviate??
1360             if (OCIType->qual_empty()) {
1361               Method = LookupInstanceMethodInGlobalPool(Sel,
1362                                                  SourceRange(LBracLoc, RBracLoc));
1363               if (Method && !forwardClass)
1364                 Diag(Loc, diag::warn_maynot_respond)
1365                   << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
1366             }
1367           }
1368         }
1369         if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
1370           return ExprError();
1371       } else if (!getLangOptions().ObjCAutoRefCount &&
1372                  !Context.getObjCIdType().isNull() &&
1373                  (ReceiverType->isPointerType() ||
1374                   ReceiverType->isIntegerType())) {
1375         // Implicitly convert integers and pointers to 'id' but emit a warning.
1376         // But not in ARC.
1377         Diag(Loc, diag::warn_bad_receiver_type)
1378           << ReceiverType
1379           << Receiver->getSourceRange();
1380         if (ReceiverType->isPointerType())
1381           Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1382                             CK_CPointerToObjCPointerCast).take();
1383         else {
1384           // TODO: specialized warning on null receivers?
1385           bool IsNull = Receiver->isNullPointerConstant(Context,
1386                                               Expr::NPC_ValueDependentIsNull);
1387           Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1388                             IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
1389         }
1390         ReceiverType = Receiver->getType();
1391       } else {
1392         ExprResult ReceiverRes;
1393         if (getLangOptions().CPlusPlus)
1394           ReceiverRes = PerformContextuallyConvertToObjCPointer(Receiver);
1395         if (ReceiverRes.isUsable()) {
1396           Receiver = ReceiverRes.take();
1397           return BuildInstanceMessage(Receiver,
1398                                       ReceiverType,
1399                                       SuperLoc,
1400                                       Sel,
1401                                       Method,
1402                                       LBracLoc,
1403                                       SelectorLocs,
1404                                       RBracLoc,
1405                                       move(ArgsIn));
1406         } else {
1407           // Reject other random receiver types (e.g. structs).
1408           Diag(Loc, diag::err_bad_receiver_type)
1409             << ReceiverType << Receiver->getSourceRange();
1410           return ExprError();
1411         }
1412       }
1413     }
1414   }
1415 
1416   // Check the message arguments.
1417   unsigned NumArgs = ArgsIn.size();
1418   Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1419   QualType ReturnType;
1420   ExprValueKind VK = VK_RValue;
1421   bool ClassMessage = (ReceiverType->isObjCClassType() ||
1422                        ReceiverType->isObjCQualifiedClassType());
1423   if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
1424                                 ClassMessage, SuperLoc.isValid(),
1425                                 LBracLoc, RBracLoc, ReturnType, VK))
1426     return ExprError();
1427 
1428   if (Method && !Method->getResultType()->isVoidType() &&
1429       RequireCompleteType(LBracLoc, Method->getResultType(),
1430                           diag::err_illegal_message_expr_incomplete_type))
1431     return ExprError();
1432 
1433   SourceLocation SelLoc = SelectorLocs.front();
1434 
1435   // In ARC, forbid the user from sending messages to
1436   // retain/release/autorelease/dealloc/retainCount explicitly.
1437   if (getLangOptions().ObjCAutoRefCount) {
1438     ObjCMethodFamily family =
1439       (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
1440     switch (family) {
1441     case OMF_init:
1442       if (Method)
1443         checkInitMethod(Method, ReceiverType);
1444 
1445     case OMF_None:
1446     case OMF_alloc:
1447     case OMF_copy:
1448     case OMF_finalize:
1449     case OMF_mutableCopy:
1450     case OMF_new:
1451     case OMF_self:
1452       break;
1453 
1454     case OMF_dealloc:
1455     case OMF_retain:
1456     case OMF_release:
1457     case OMF_autorelease:
1458     case OMF_retainCount:
1459       Diag(Loc, diag::err_arc_illegal_explicit_message)
1460         << Sel << SelLoc;
1461       break;
1462 
1463     case OMF_performSelector:
1464       if (Method && NumArgs >= 1) {
1465         if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
1466           Selector ArgSel = SelExp->getSelector();
1467           ObjCMethodDecl *SelMethod =
1468             LookupInstanceMethodInGlobalPool(ArgSel,
1469                                              SelExp->getSourceRange());
1470           if (!SelMethod)
1471             SelMethod =
1472               LookupFactoryMethodInGlobalPool(ArgSel,
1473                                               SelExp->getSourceRange());
1474           if (SelMethod) {
1475             ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
1476             switch (SelFamily) {
1477               case OMF_alloc:
1478               case OMF_copy:
1479               case OMF_mutableCopy:
1480               case OMF_new:
1481               case OMF_self:
1482               case OMF_init:
1483                 // Issue error, unless ns_returns_not_retained.
1484                 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
1485                   // selector names a +1 method
1486                   Diag(SelLoc,
1487                        diag::err_arc_perform_selector_retains);
1488                   Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1489                 }
1490                 break;
1491               default:
1492                 // +0 call. OK. unless ns_returns_retained.
1493                 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
1494                   // selector names a +1 method
1495                   Diag(SelLoc,
1496                        diag::err_arc_perform_selector_retains);
1497                   Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1498                 }
1499                 break;
1500             }
1501           }
1502         } else {
1503           // error (may leak).
1504           Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
1505           Diag(Args[0]->getExprLoc(), diag::note_used_here);
1506         }
1507       }
1508       break;
1509     }
1510   }
1511 
1512   // Construct the appropriate ObjCMessageExpr instance.
1513   ObjCMessageExpr *Result;
1514   if (SuperLoc.isValid())
1515     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
1516                                      SuperLoc,  /*IsInstanceSuper=*/true,
1517                                      ReceiverType, Sel, SelectorLocs, Method,
1518                                      makeArrayRef(Args, NumArgs), RBracLoc);
1519   else
1520     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
1521                                      Receiver, Sel, SelectorLocs, Method,
1522                                      makeArrayRef(Args, NumArgs), RBracLoc);
1523 
1524   if (getLangOptions().ObjCAutoRefCount) {
1525     // In ARC, annotate delegate init calls.
1526     if (Result->getMethodFamily() == OMF_init &&
1527         (SuperLoc.isValid() || isSelfExpr(Receiver))) {
1528       // Only consider init calls *directly* in init implementations,
1529       // not within blocks.
1530       ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
1531       if (method && method->getMethodFamily() == OMF_init) {
1532         // The implicit assignment to self means we also don't want to
1533         // consume the result.
1534         Result->setDelegateInitCall(true);
1535         return Owned(Result);
1536       }
1537     }
1538 
1539     // In ARC, check for message sends which are likely to introduce
1540     // retain cycles.
1541     checkRetainCycles(Result);
1542   }
1543 
1544   return MaybeBindToTemporary(Result);
1545 }
1546 
1547 // ActOnInstanceMessage - used for both unary and keyword messages.
1548 // ArgExprs is optional - if it is present, the number of expressions
1549 // is obtained from Sel.getNumArgs().
1550 ExprResult Sema::ActOnInstanceMessage(Scope *S,
1551                                       Expr *Receiver,
1552                                       Selector Sel,
1553                                       SourceLocation LBracLoc,
1554                                       ArrayRef<SourceLocation> SelectorLocs,
1555                                       SourceLocation RBracLoc,
1556                                       MultiExprArg Args) {
1557   if (!Receiver)
1558     return ExprError();
1559 
1560   return BuildInstanceMessage(Receiver, Receiver->getType(),
1561                               /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
1562                               LBracLoc, SelectorLocs, RBracLoc, move(Args));
1563 }
1564 
1565 enum ARCConversionTypeClass {
1566   /// int, void, struct A
1567   ACTC_none,
1568 
1569   /// id, void (^)()
1570   ACTC_retainable,
1571 
1572   /// id*, id***, void (^*)(),
1573   ACTC_indirectRetainable,
1574 
1575   /// void* might be a normal C type, or it might a CF type.
1576   ACTC_voidPtr,
1577 
1578   /// struct A*
1579   ACTC_coreFoundation
1580 };
1581 static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
1582   return (ACTC == ACTC_retainable ||
1583           ACTC == ACTC_coreFoundation ||
1584           ACTC == ACTC_voidPtr);
1585 }
1586 static bool isAnyCLike(ARCConversionTypeClass ACTC) {
1587   return ACTC == ACTC_none ||
1588          ACTC == ACTC_voidPtr ||
1589          ACTC == ACTC_coreFoundation;
1590 }
1591 
1592 static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
1593   bool isIndirect = false;
1594 
1595   // Ignore an outermost reference type.
1596   if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
1597     type = ref->getPointeeType();
1598     isIndirect = true;
1599   }
1600 
1601   // Drill through pointers and arrays recursively.
1602   while (true) {
1603     if (const PointerType *ptr = type->getAs<PointerType>()) {
1604       type = ptr->getPointeeType();
1605 
1606       // The first level of pointer may be the innermost pointer on a CF type.
1607       if (!isIndirect) {
1608         if (type->isVoidType()) return ACTC_voidPtr;
1609         if (type->isRecordType()) return ACTC_coreFoundation;
1610       }
1611     } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
1612       type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
1613     } else {
1614       break;
1615     }
1616     isIndirect = true;
1617   }
1618 
1619   if (isIndirect) {
1620     if (type->isObjCARCBridgableType())
1621       return ACTC_indirectRetainable;
1622     return ACTC_none;
1623   }
1624 
1625   if (type->isObjCARCBridgableType())
1626     return ACTC_retainable;
1627 
1628   return ACTC_none;
1629 }
1630 
1631 namespace {
1632   /// A result from the cast checker.
1633   enum ACCResult {
1634     /// Cannot be casted.
1635     ACC_invalid,
1636 
1637     /// Can be safely retained or not retained.
1638     ACC_bottom,
1639 
1640     /// Can be casted at +0.
1641     ACC_plusZero,
1642 
1643     /// Can be casted at +1.
1644     ACC_plusOne
1645   };
1646   ACCResult merge(ACCResult left, ACCResult right) {
1647     if (left == right) return left;
1648     if (left == ACC_bottom) return right;
1649     if (right == ACC_bottom) return left;
1650     return ACC_invalid;
1651   }
1652 
1653   /// A checker which white-lists certain expressions whose conversion
1654   /// to or from retainable type would otherwise be forbidden in ARC.
1655   class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
1656     typedef StmtVisitor<ARCCastChecker, ACCResult> super;
1657 
1658     ASTContext &Context;
1659     ARCConversionTypeClass SourceClass;
1660     ARCConversionTypeClass TargetClass;
1661 
1662     static bool isCFType(QualType type) {
1663       // Someday this can use ns_bridged.  For now, it has to do this.
1664       return type->isCARCBridgableType();
1665     }
1666 
1667   public:
1668     ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
1669                    ARCConversionTypeClass target)
1670       : Context(Context), SourceClass(source), TargetClass(target) {}
1671 
1672     using super::Visit;
1673     ACCResult Visit(Expr *e) {
1674       return super::Visit(e->IgnoreParens());
1675     }
1676 
1677     ACCResult VisitStmt(Stmt *s) {
1678       return ACC_invalid;
1679     }
1680 
1681     /// Null pointer constants can be casted however you please.
1682     ACCResult VisitExpr(Expr *e) {
1683       if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1684         return ACC_bottom;
1685       return ACC_invalid;
1686     }
1687 
1688     /// Objective-C string literals can be safely casted.
1689     ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
1690       // If we're casting to any retainable type, go ahead.  Global
1691       // strings are immune to retains, so this is bottom.
1692       if (isAnyRetainable(TargetClass)) return ACC_bottom;
1693 
1694       return ACC_invalid;
1695     }
1696 
1697     /// Look through certain implicit and explicit casts.
1698     ACCResult VisitCastExpr(CastExpr *e) {
1699       switch (e->getCastKind()) {
1700         case CK_NullToPointer:
1701           return ACC_bottom;
1702 
1703         case CK_NoOp:
1704         case CK_LValueToRValue:
1705         case CK_BitCast:
1706         case CK_CPointerToObjCPointerCast:
1707         case CK_BlockPointerToObjCPointerCast:
1708         case CK_AnyPointerToBlockPointerCast:
1709           return Visit(e->getSubExpr());
1710 
1711         default:
1712           return ACC_invalid;
1713       }
1714     }
1715 
1716     /// Look through unary extension.
1717     ACCResult VisitUnaryExtension(UnaryOperator *e) {
1718       return Visit(e->getSubExpr());
1719     }
1720 
1721     /// Ignore the LHS of a comma operator.
1722     ACCResult VisitBinComma(BinaryOperator *e) {
1723       return Visit(e->getRHS());
1724     }
1725 
1726     /// Conditional operators are okay if both sides are okay.
1727     ACCResult VisitConditionalOperator(ConditionalOperator *e) {
1728       ACCResult left = Visit(e->getTrueExpr());
1729       if (left == ACC_invalid) return ACC_invalid;
1730       return merge(left, Visit(e->getFalseExpr()));
1731     }
1732 
1733     /// Look through pseudo-objects.
1734     ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
1735       // If we're getting here, we should always have a result.
1736       return Visit(e->getResultExpr());
1737     }
1738 
1739     /// Statement expressions are okay if their result expression is okay.
1740     ACCResult VisitStmtExpr(StmtExpr *e) {
1741       return Visit(e->getSubStmt()->body_back());
1742     }
1743 
1744     /// Some declaration references are okay.
1745     ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
1746       // References to global constants from system headers are okay.
1747       // These are things like 'kCFStringTransformToLatin'.  They are
1748       // can also be assumed to be immune to retains.
1749       VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
1750       if (isAnyRetainable(TargetClass) &&
1751           isAnyRetainable(SourceClass) &&
1752           var &&
1753           var->getStorageClass() == SC_Extern &&
1754           var->getType().isConstQualified() &&
1755           Context.getSourceManager().isInSystemHeader(var->getLocation())) {
1756         return ACC_bottom;
1757       }
1758 
1759       // Nothing else.
1760       return ACC_invalid;
1761     }
1762 
1763     /// Some calls are okay.
1764     ACCResult VisitCallExpr(CallExpr *e) {
1765       if (FunctionDecl *fn = e->getDirectCallee())
1766         if (ACCResult result = checkCallToFunction(fn))
1767           return result;
1768 
1769       return super::VisitCallExpr(e);
1770     }
1771 
1772     ACCResult checkCallToFunction(FunctionDecl *fn) {
1773       // Require a CF*Ref return type.
1774       if (!isCFType(fn->getResultType()))
1775         return ACC_invalid;
1776 
1777       if (!isAnyRetainable(TargetClass))
1778         return ACC_invalid;
1779 
1780       // Honor an explicit 'not retained' attribute.
1781       if (fn->hasAttr<CFReturnsNotRetainedAttr>())
1782         return ACC_plusZero;
1783 
1784       // Honor an explicit 'retained' attribute, except that for
1785       // now we're not going to permit implicit handling of +1 results,
1786       // because it's a bit frightening.
1787       if (fn->hasAttr<CFReturnsRetainedAttr>())
1788         return ACC_invalid; // ACC_plusOne if we start accepting this
1789 
1790       // Recognize this specific builtin function, which is used by CFSTR.
1791       unsigned builtinID = fn->getBuiltinID();
1792       if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
1793         return ACC_bottom;
1794 
1795       // Otherwise, don't do anything implicit with an unaudited function.
1796       if (!fn->hasAttr<CFAuditedTransferAttr>())
1797         return ACC_invalid;
1798 
1799       // Otherwise, it's +0 unless it follows the create convention.
1800       if (ento::coreFoundation::followsCreateRule(fn))
1801         return ACC_invalid; // ACC_plusOne if we start accepting this
1802 
1803       return ACC_plusZero;
1804     }
1805 
1806     ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
1807       return checkCallToMethod(e->getMethodDecl());
1808     }
1809 
1810     ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
1811       ObjCMethodDecl *method;
1812       if (e->isExplicitProperty())
1813         method = e->getExplicitProperty()->getGetterMethodDecl();
1814       else
1815         method = e->getImplicitPropertyGetter();
1816       return checkCallToMethod(method);
1817     }
1818 
1819     ACCResult checkCallToMethod(ObjCMethodDecl *method) {
1820       if (!method) return ACC_invalid;
1821 
1822       // Check for message sends to functions returning CF types.  We
1823       // just obey the Cocoa conventions with these, even though the
1824       // return type is CF.
1825       if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType()))
1826         return ACC_invalid;
1827 
1828       // If the method is explicitly marked not-retained, it's +0.
1829       if (method->hasAttr<CFReturnsNotRetainedAttr>())
1830         return ACC_plusZero;
1831 
1832       // If the method is explicitly marked as returning retained, or its
1833       // selector follows a +1 Cocoa convention, treat it as +1.
1834       if (method->hasAttr<CFReturnsRetainedAttr>())
1835         return ACC_plusOne;
1836 
1837       switch (method->getSelector().getMethodFamily()) {
1838       case OMF_alloc:
1839       case OMF_copy:
1840       case OMF_mutableCopy:
1841       case OMF_new:
1842         return ACC_plusOne;
1843 
1844       default:
1845         // Otherwise, treat it as +0.
1846         return ACC_plusZero;
1847       }
1848     }
1849   };
1850 }
1851 
1852 static void
1853 diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
1854                           QualType castType, ARCConversionTypeClass castACTC,
1855                           Expr *castExpr, ARCConversionTypeClass exprACTC,
1856                           Sema::CheckedConversionKind CCK) {
1857   SourceLocation loc =
1858     (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
1859 
1860   if (S.makeUnavailableInSystemHeader(loc,
1861                 "converts between Objective-C and C pointers in -fobjc-arc"))
1862     return;
1863 
1864   QualType castExprType = castExpr->getType();
1865 
1866   unsigned srcKind = 0;
1867   switch (exprACTC) {
1868   case ACTC_none:
1869   case ACTC_coreFoundation:
1870   case ACTC_voidPtr:
1871     srcKind = (castExprType->isPointerType() ? 1 : 0);
1872     break;
1873   case ACTC_retainable:
1874     srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
1875     break;
1876   case ACTC_indirectRetainable:
1877     srcKind = 4;
1878     break;
1879   }
1880 
1881   // Check whether this could be fixed with a bridge cast.
1882   SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
1883   SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
1884 
1885   // Bridge from an ARC type to a CF type.
1886   if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
1887     S.Diag(loc, diag::err_arc_cast_requires_bridge)
1888       << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
1889       << 2 // of C pointer type
1890       << castExprType
1891       << unsigned(castType->isBlockPointerType()) // to ObjC|block type
1892       << castType
1893       << castRange
1894       << castExpr->getSourceRange();
1895 
1896     S.Diag(noteLoc, diag::note_arc_bridge)
1897       << (CCK != Sema::CCK_CStyleCast ? FixItHint() :
1898             FixItHint::CreateInsertion(afterLParen, "__bridge "));
1899     S.Diag(noteLoc, diag::note_arc_bridge_transfer)
1900       << castExprType
1901       << (CCK != Sema::CCK_CStyleCast ? FixItHint() :
1902             FixItHint::CreateInsertion(afterLParen, "__bridge_transfer "));
1903 
1904     return;
1905   }
1906 
1907   // Bridge from a CF type to an ARC type.
1908   if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
1909     S.Diag(loc, diag::err_arc_cast_requires_bridge)
1910       << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
1911       << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
1912       << castExprType
1913       << 2 // to C pointer type
1914       << castType
1915       << castRange
1916       << castExpr->getSourceRange();
1917 
1918     S.Diag(noteLoc, diag::note_arc_bridge)
1919       << (CCK != Sema::CCK_CStyleCast ? FixItHint() :
1920             FixItHint::CreateInsertion(afterLParen, "__bridge "));
1921     S.Diag(noteLoc, diag::note_arc_bridge_retained)
1922       << castType
1923       << (CCK != Sema::CCK_CStyleCast ? FixItHint() :
1924             FixItHint::CreateInsertion(afterLParen, "__bridge_retained "));
1925 
1926     return;
1927   }
1928 
1929   S.Diag(loc, diag::err_arc_mismatched_cast)
1930     << (CCK != Sema::CCK_ImplicitConversion)
1931     << srcKind << castExprType << castType
1932     << castRange << castExpr->getSourceRange();
1933 }
1934 
1935 Sema::ARCConversionResult
1936 Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
1937                              Expr *&castExpr, CheckedConversionKind CCK) {
1938   QualType castExprType = castExpr->getType();
1939 
1940   // For the purposes of the classification, we assume reference types
1941   // will bind to temporaries.
1942   QualType effCastType = castType;
1943   if (const ReferenceType *ref = castType->getAs<ReferenceType>())
1944     effCastType = ref->getPointeeType();
1945 
1946   ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
1947   ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
1948   if (exprACTC == castACTC) {
1949     // check for viablity and report error if casting an rvalue to a
1950     // life-time qualifier.
1951     if ((castACTC == ACTC_retainable) &&
1952         (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
1953         (castType != castExprType)) {
1954       const Type *DT = castType.getTypePtr();
1955       QualType QDT = castType;
1956       // We desugar some types but not others. We ignore those
1957       // that cannot happen in a cast; i.e. auto, and those which
1958       // should not be de-sugared; i.e typedef.
1959       if (const ParenType *PT = dyn_cast<ParenType>(DT))
1960         QDT = PT->desugar();
1961       else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
1962         QDT = TP->desugar();
1963       else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
1964         QDT = AT->desugar();
1965       if (QDT != castType &&
1966           QDT.getObjCLifetime() !=  Qualifiers::OCL_None) {
1967         SourceLocation loc =
1968           (castRange.isValid() ? castRange.getBegin()
1969                               : castExpr->getExprLoc());
1970         Diag(loc, diag::err_arc_nolifetime_behavior);
1971       }
1972     }
1973     return ACR_okay;
1974   }
1975 
1976   if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
1977 
1978   // Allow all of these types to be cast to integer types (but not
1979   // vice-versa).
1980   if (castACTC == ACTC_none && castType->isIntegralType(Context))
1981     return ACR_okay;
1982 
1983   // Allow casts between pointers to lifetime types (e.g., __strong id*)
1984   // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
1985   // must be explicit.
1986   if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
1987     return ACR_okay;
1988   if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
1989       CCK != CCK_ImplicitConversion)
1990     return ACR_okay;
1991 
1992   switch (ARCCastChecker(Context, exprACTC, castACTC).Visit(castExpr)) {
1993   // For invalid casts, fall through.
1994   case ACC_invalid:
1995     break;
1996 
1997   // Do nothing for both bottom and +0.
1998   case ACC_bottom:
1999   case ACC_plusZero:
2000     return ACR_okay;
2001 
2002   // If the result is +1, consume it here.
2003   case ACC_plusOne:
2004     castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
2005                                         CK_ARCConsumeObject, castExpr,
2006                                         0, VK_RValue);
2007     ExprNeedsCleanups = true;
2008     return ACR_okay;
2009   }
2010 
2011   // If this is a non-implicit cast from id or block type to a
2012   // CoreFoundation type, delay complaining in case the cast is used
2013   // in an acceptable context.
2014   if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
2015       CCK != CCK_ImplicitConversion)
2016     return ACR_unbridged;
2017 
2018   diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
2019                             castExpr, exprACTC, CCK);
2020   return ACR_okay;
2021 }
2022 
2023 /// Given that we saw an expression with the ARCUnbridgedCastTy
2024 /// placeholder type, complain bitterly.
2025 void Sema::diagnoseARCUnbridgedCast(Expr *e) {
2026   // We expect the spurious ImplicitCastExpr to already have been stripped.
2027   assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
2028   CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
2029 
2030   SourceRange castRange;
2031   QualType castType;
2032   CheckedConversionKind CCK;
2033 
2034   if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
2035     castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
2036     castType = cast->getTypeAsWritten();
2037     CCK = CCK_CStyleCast;
2038   } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
2039     castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
2040     castType = cast->getTypeAsWritten();
2041     CCK = CCK_OtherCast;
2042   } else {
2043     castType = cast->getType();
2044     CCK = CCK_ImplicitConversion;
2045   }
2046 
2047   ARCConversionTypeClass castACTC =
2048     classifyTypeForARCConversion(castType.getNonReferenceType());
2049 
2050   Expr *castExpr = realCast->getSubExpr();
2051   assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
2052 
2053   diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
2054                             castExpr, ACTC_retainable, CCK);
2055 }
2056 
2057 /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
2058 /// type, remove the placeholder cast.
2059 Expr *Sema::stripARCUnbridgedCast(Expr *e) {
2060   assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
2061 
2062   if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
2063     Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
2064     return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
2065   } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
2066     assert(uo->getOpcode() == UO_Extension);
2067     Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
2068     return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
2069                                    sub->getValueKind(), sub->getObjectKind(),
2070                                        uo->getOperatorLoc());
2071   } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
2072     assert(!gse->isResultDependent());
2073 
2074     unsigned n = gse->getNumAssocs();
2075     SmallVector<Expr*, 4> subExprs(n);
2076     SmallVector<TypeSourceInfo*, 4> subTypes(n);
2077     for (unsigned i = 0; i != n; ++i) {
2078       subTypes[i] = gse->getAssocTypeSourceInfo(i);
2079       Expr *sub = gse->getAssocExpr(i);
2080       if (i == gse->getResultIndex())
2081         sub = stripARCUnbridgedCast(sub);
2082       subExprs[i] = sub;
2083     }
2084 
2085     return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
2086                                               gse->getControllingExpr(),
2087                                               subTypes.data(), subExprs.data(),
2088                                               n, gse->getDefaultLoc(),
2089                                               gse->getRParenLoc(),
2090                                        gse->containsUnexpandedParameterPack(),
2091                                               gse->getResultIndex());
2092   } else {
2093     assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
2094     return cast<ImplicitCastExpr>(e)->getSubExpr();
2095   }
2096 }
2097 
2098 bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
2099                                                  QualType exprType) {
2100   QualType canCastType =
2101     Context.getCanonicalType(castType).getUnqualifiedType();
2102   QualType canExprType =
2103     Context.getCanonicalType(exprType).getUnqualifiedType();
2104   if (isa<ObjCObjectPointerType>(canCastType) &&
2105       castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
2106       canExprType->isObjCObjectPointerType()) {
2107     if (const ObjCObjectPointerType *ObjT =
2108         canExprType->getAs<ObjCObjectPointerType>())
2109       if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
2110         return false;
2111   }
2112   return true;
2113 }
2114 
2115 /// Look for an ObjCReclaimReturnedObject cast and destroy it.
2116 static Expr *maybeUndoReclaimObject(Expr *e) {
2117   // For now, we just undo operands that are *immediately* reclaim
2118   // expressions, which prevents the vast majority of potential
2119   // problems here.  To catch them all, we'd need to rebuild arbitrary
2120   // value-propagating subexpressions --- we can't reliably rebuild
2121   // in-place because of expression sharing.
2122   if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2123     if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
2124       return ice->getSubExpr();
2125 
2126   return e;
2127 }
2128 
2129 ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
2130                                       ObjCBridgeCastKind Kind,
2131                                       SourceLocation BridgeKeywordLoc,
2132                                       TypeSourceInfo *TSInfo,
2133                                       Expr *SubExpr) {
2134   ExprResult SubResult = UsualUnaryConversions(SubExpr);
2135   if (SubResult.isInvalid()) return ExprError();
2136   SubExpr = SubResult.take();
2137 
2138   QualType T = TSInfo->getType();
2139   QualType FromType = SubExpr->getType();
2140 
2141   CastKind CK;
2142 
2143   bool MustConsume = false;
2144   if (T->isDependentType() || SubExpr->isTypeDependent()) {
2145     // Okay: we'll build a dependent expression type.
2146     CK = CK_Dependent;
2147   } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
2148     // Casting CF -> id
2149     CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
2150                                   : CK_CPointerToObjCPointerCast);
2151     switch (Kind) {
2152     case OBC_Bridge:
2153       break;
2154 
2155     case OBC_BridgeRetained:
2156       Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2157         << 2
2158         << FromType
2159         << (T->isBlockPointerType()? 1 : 0)
2160         << T
2161         << SubExpr->getSourceRange()
2162         << Kind;
2163       Diag(BridgeKeywordLoc, diag::note_arc_bridge)
2164         << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
2165       Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
2166         << FromType
2167         << FixItHint::CreateReplacement(BridgeKeywordLoc,
2168                                         "__bridge_transfer ");
2169 
2170       Kind = OBC_Bridge;
2171       break;
2172 
2173     case OBC_BridgeTransfer:
2174       // We must consume the Objective-C object produced by the cast.
2175       MustConsume = true;
2176       break;
2177     }
2178   } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
2179     // Okay: id -> CF
2180     CK = CK_BitCast;
2181     switch (Kind) {
2182     case OBC_Bridge:
2183       // Reclaiming a value that's going to be __bridge-casted to CF
2184       // is very dangerous, so we don't do it.
2185       SubExpr = maybeUndoReclaimObject(SubExpr);
2186       break;
2187 
2188     case OBC_BridgeRetained:
2189       // Produce the object before casting it.
2190       SubExpr = ImplicitCastExpr::Create(Context, FromType,
2191                                          CK_ARCProduceObject,
2192                                          SubExpr, 0, VK_RValue);
2193       break;
2194 
2195     case OBC_BridgeTransfer:
2196       Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2197         << (FromType->isBlockPointerType()? 1 : 0)
2198         << FromType
2199         << 2
2200         << T
2201         << SubExpr->getSourceRange()
2202         << Kind;
2203 
2204       Diag(BridgeKeywordLoc, diag::note_arc_bridge)
2205         << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
2206       Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
2207         << T
2208         << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge_retained ");
2209 
2210       Kind = OBC_Bridge;
2211       break;
2212     }
2213   } else {
2214     Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
2215       << FromType << T << Kind
2216       << SubExpr->getSourceRange()
2217       << TSInfo->getTypeLoc().getSourceRange();
2218     return ExprError();
2219   }
2220 
2221   Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
2222                                                    BridgeKeywordLoc,
2223                                                    TSInfo, SubExpr);
2224 
2225   if (MustConsume) {
2226     ExprNeedsCleanups = true;
2227     Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
2228                                       0, VK_RValue);
2229   }
2230 
2231   return Result;
2232 }
2233 
2234 ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
2235                                       SourceLocation LParenLoc,
2236                                       ObjCBridgeCastKind Kind,
2237                                       SourceLocation BridgeKeywordLoc,
2238                                       ParsedType Type,
2239                                       SourceLocation RParenLoc,
2240                                       Expr *SubExpr) {
2241   TypeSourceInfo *TSInfo = 0;
2242   QualType T = GetTypeFromParser(Type, &TSInfo);
2243   if (!TSInfo)
2244     TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
2245   return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
2246                               SubExpr);
2247 }
2248