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 "Sema.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/ExprObjC.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "clang/Lex/Preprocessor.h"
20 
21 using namespace clang;
22 
23 Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
24                                               ExprTy **strings,
25                                               unsigned NumStrings) {
26   StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
27 
28   // Most ObjC strings are formed out of a single piece.  However, we *can*
29   // have strings formed out of multiple @ strings with multiple pptokens in
30   // each one, e.g. @"foo" "bar" @"baz" "qux"   which need to be turned into one
31   // StringLiteral for ObjCStringLiteral to hold onto.
32   StringLiteral *S = Strings[0];
33 
34   // If we have a multi-part string, merge it all together.
35   if (NumStrings != 1) {
36     // Concatenate objc strings.
37     llvm::SmallString<128> StrBuf;
38     llvm::SmallVector<SourceLocation, 8> StrLocs;
39 
40     for (unsigned i = 0; i != NumStrings; ++i) {
41       S = Strings[i];
42 
43       // ObjC strings can't be wide.
44       if (S->isWide()) {
45         Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
46           << S->getSourceRange();
47         return true;
48       }
49 
50       // Get the string data.
51       StrBuf.append(S->getStrData(), S->getStrData()+S->getByteLength());
52 
53       // Get the locations of the string tokens.
54       StrLocs.append(S->tokloc_begin(), S->tokloc_end());
55 
56       // Free the temporary string.
57       S->Destroy(Context);
58     }
59 
60     // Create the aggregate string with the appropriate content and location
61     // information.
62     S = StringLiteral::Create(Context, &StrBuf[0], StrBuf.size(), false,
63                               Context.getPointerType(Context.CharTy),
64                               &StrLocs[0], StrLocs.size());
65   }
66 
67   // Verify that this composite string is acceptable for ObjC strings.
68   if (CheckObjCString(S))
69     return true;
70 
71   // Initialize the constant string interface lazily. This assumes
72   // the NSString interface is seen in this translation unit. Note: We
73   // don't use NSConstantString, since the runtime team considers this
74   // interface private (even though it appears in the header files).
75   QualType Ty = Context.getObjCConstantStringInterface();
76   if (!Ty.isNull()) {
77     Ty = Context.getPointerType(Ty);
78   } else {
79     IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
80     NamedDecl *IF = LookupName(TUScope, NSIdent, LookupOrdinaryName);
81     if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
82       Context.setObjCConstantStringInterface(StrIF);
83       Ty = Context.getObjCConstantStringInterface();
84       Ty = Context.getPointerType(Ty);
85     } else {
86       // If there is no NSString interface defined then treat constant
87       // strings as untyped objects and let the runtime figure it out later.
88       Ty = Context.getObjCIdType();
89     }
90   }
91 
92   return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
93 }
94 
95 Expr *Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
96                                       QualType EncodedType,
97                                       SourceLocation RParenLoc) {
98   QualType StrTy;
99   if (EncodedType->isDependentType())
100     StrTy = Context.DependentTy;
101   else {
102     std::string Str;
103     Context.getObjCEncodingForType(EncodedType, Str);
104 
105     // The type of @encode is the same as the type of the corresponding string,
106     // which is an array type.
107     StrTy = Context.CharTy;
108     // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
109     if (getLangOptions().CPlusPlus)
110       StrTy.addConst();
111     StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
112                                          ArrayType::Normal, 0);
113   }
114 
115   return new (Context) ObjCEncodeExpr(StrTy, EncodedType, AtLoc, RParenLoc);
116 }
117 
118 Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
119                                                  SourceLocation EncodeLoc,
120                                                  SourceLocation LParenLoc,
121                                                  TypeTy *ty,
122                                                  SourceLocation RParenLoc) {
123   QualType EncodedType = QualType::getFromOpaquePtr(ty);
124 
125   return BuildObjCEncodeExpression(AtLoc, EncodedType, RParenLoc);
126 }
127 
128 Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
129                                                    SourceLocation AtLoc,
130                                                    SourceLocation SelLoc,
131                                                    SourceLocation LParenLoc,
132                                                    SourceLocation RParenLoc) {
133   QualType Ty = Context.getObjCSelType();
134   return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
135 }
136 
137 Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
138                                                    SourceLocation AtLoc,
139                                                    SourceLocation ProtoLoc,
140                                                    SourceLocation LParenLoc,
141                                                    SourceLocation RParenLoc) {
142   ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId);
143   if (!PDecl) {
144     Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
145     return true;
146   }
147 
148   QualType Ty = Context.getObjCProtoType();
149   if (Ty.isNull())
150     return true;
151   Ty = Context.getPointerType(Ty);
152   return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
153 }
154 
155 bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
156                                      Selector Sel, ObjCMethodDecl *Method,
157                                      bool isClassMessage,
158                                      SourceLocation lbrac, SourceLocation rbrac,
159                                      QualType &ReturnType) {
160   if (!Method) {
161     // Apply default argument promotion as for (C99 6.5.2.2p6).
162     for (unsigned i = 0; i != NumArgs; i++)
163       DefaultArgumentPromotion(Args[i]);
164 
165     unsigned DiagID = isClassMessage ? diag::warn_class_method_not_found :
166                                        diag::warn_inst_method_not_found;
167     Diag(lbrac, DiagID)
168       << Sel << isClassMessage << SourceRange(lbrac, rbrac);
169     ReturnType = Context.getObjCIdType();
170     return false;
171   }
172 
173   ReturnType = Method->getResultType();
174 
175   unsigned NumNamedArgs = Sel.getNumArgs();
176   assert(NumArgs >= NumNamedArgs && "Too few arguments for selector!");
177 
178   bool IsError = false;
179   for (unsigned i = 0; i < NumNamedArgs; i++) {
180     Expr *argExpr = Args[i];
181     assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
182 
183     QualType lhsType = Method->param_begin()[i]->getType();
184     QualType rhsType = argExpr->getType();
185 
186     // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
187     if (lhsType->isArrayType())
188       lhsType = Context.getArrayDecayedType(lhsType);
189     else if (lhsType->isFunctionType())
190       lhsType = Context.getPointerType(lhsType);
191 
192     AssignConvertType Result =
193       CheckSingleAssignmentConstraints(lhsType, argExpr);
194     if (Args[i] != argExpr) // The expression was converted.
195       Args[i] = argExpr; // Make sure we store the converted expression.
196 
197     IsError |=
198       DiagnoseAssignmentResult(Result, argExpr->getLocStart(), lhsType, rhsType,
199                                argExpr, "sending");
200   }
201 
202   // Promote additional arguments to variadic methods.
203   if (Method->isVariadic()) {
204     for (unsigned i = NumNamedArgs; i < NumArgs; ++i)
205       IsError |= DefaultVariadicArgumentPromotion(Args[i], VariadicMethod);
206   } else {
207     // Check for extra arguments to non-variadic methods.
208     if (NumArgs != NumNamedArgs) {
209       Diag(Args[NumNamedArgs]->getLocStart(),
210            diag::err_typecheck_call_too_many_args)
211         << 2 /*method*/ << Method->getSourceRange()
212         << SourceRange(Args[NumNamedArgs]->getLocStart(),
213                        Args[NumArgs-1]->getLocEnd());
214     }
215   }
216 
217   return IsError;
218 }
219 
220 bool Sema::isSelfExpr(Expr *RExpr) {
221   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(RExpr))
222     if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
223       return true;
224   return false;
225 }
226 
227 // Helper method for ActOnClassMethod/ActOnInstanceMethod.
228 // Will search "local" class/category implementations for a method decl.
229 // If failed, then we search in class's root for an instance method.
230 // Returns 0 if no method is found.
231 ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
232                                           ObjCInterfaceDecl *ClassDecl) {
233   ObjCMethodDecl *Method = 0;
234   // lookup in class and all superclasses
235   while (ClassDecl && !Method) {
236     if (ObjCImplementationDecl *ImpDecl
237           = LookupObjCImplementation(ClassDecl->getIdentifier()))
238       Method = ImpDecl->getClassMethod(Context, Sel);
239 
240     // Look through local category implementations associated with the class.
241     if (!Method) {
242       for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Method; i++) {
243         if (ObjCCategoryImpls[i]->getClassInterface() == ClassDecl)
244           Method = ObjCCategoryImpls[i]->getClassMethod(Context, Sel);
245       }
246     }
247 
248     // Before we give up, check if the selector is an instance method.
249     // But only in the root. This matches gcc's behaviour and what the
250     // runtime expects.
251     if (!Method && !ClassDecl->getSuperClass()) {
252       Method = ClassDecl->lookupInstanceMethod(Context, Sel);
253       // Look through local category implementations associated
254       // with the root class.
255       if (!Method)
256         Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
257     }
258 
259     ClassDecl = ClassDecl->getSuperClass();
260   }
261   return Method;
262 }
263 
264 ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
265                                               ObjCInterfaceDecl *ClassDecl) {
266   ObjCMethodDecl *Method = 0;
267   while (ClassDecl && !Method) {
268     // If we have implementations in scope, check "private" methods.
269     if (ObjCImplementationDecl *ImpDecl
270           = LookupObjCImplementation(ClassDecl->getIdentifier()))
271       Method = ImpDecl->getInstanceMethod(Context, Sel);
272 
273     // Look through local category implementations associated with the class.
274     if (!Method) {
275       for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Method; i++) {
276         if (ObjCCategoryImpls[i]->getClassInterface() == ClassDecl)
277           Method = ObjCCategoryImpls[i]->getInstanceMethod(Context, Sel);
278       }
279     }
280     ClassDecl = ClassDecl->getSuperClass();
281   }
282   return Method;
283 }
284 
285 Action::OwningExprResult Sema::ActOnClassPropertyRefExpr(
286   IdentifierInfo &receiverName,
287   IdentifierInfo &propertyName,
288   SourceLocation &receiverNameLoc,
289   SourceLocation &propertyNameLoc) {
290 
291   ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(&receiverName);
292 
293   // Search for a declared property first.
294 
295   Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
296   ObjCMethodDecl *Getter = IFace->lookupClassMethod(Context, Sel);
297 
298   // If this reference is in an @implementation, check for 'private' methods.
299   if (!Getter)
300     if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
301       if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
302         if (ObjCImplementationDecl *ImpDecl
303               = LookupObjCImplementation(ClassDecl->getIdentifier()))
304           Getter = ImpDecl->getClassMethod(Context, Sel);
305 
306   if (Getter) {
307     // FIXME: refactor/share with ActOnMemberReference().
308     // Check if we can reference this property.
309     if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
310       return ExprError();
311   }
312 
313   // Look for the matching setter, in case it is needed.
314   Selector SetterSel =
315     SelectorTable::constructSetterName(PP.getIdentifierTable(),
316                                        PP.getSelectorTable(), &propertyName);
317 
318   ObjCMethodDecl *Setter = IFace->lookupClassMethod(Context, SetterSel);
319   if (!Setter) {
320     // If this reference is in an @implementation, also check for 'private'
321     // methods.
322     if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
323       if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
324         if (ObjCImplementationDecl *ImpDecl
325               = LookupObjCImplementation(ClassDecl->getIdentifier()))
326           Setter = ImpDecl->getClassMethod(Context, SetterSel);
327   }
328   // Look through local category implementations associated with the class.
329   if (!Setter) {
330     for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
331       if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
332         Setter = ObjCCategoryImpls[i]->getClassMethod(Context, SetterSel);
333     }
334   }
335 
336   if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
337     return ExprError();
338 
339   if (Getter || Setter) {
340     QualType PType;
341 
342     if (Getter)
343       PType = Getter->getResultType();
344     else {
345       for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
346            E = Setter->param_end(); PI != E; ++PI)
347         PType = (*PI)->getType();
348     }
349     return Owned(new (Context) ObjCKVCRefExpr(Getter, PType, Setter,
350                                   propertyNameLoc, IFace, receiverNameLoc));
351   }
352   return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
353                      << &propertyName << Context.getObjCInterfaceType(IFace));
354 }
355 
356 
357 // ActOnClassMessage - used for both unary and keyword messages.
358 // ArgExprs is optional - if it is present, the number of expressions
359 // is obtained from Sel.getNumArgs().
360 Sema::ExprResult Sema::ActOnClassMessage(
361   Scope *S,
362   IdentifierInfo *receiverName, Selector Sel,
363   SourceLocation lbrac, SourceLocation receiverLoc,
364   SourceLocation selectorLoc, SourceLocation rbrac,
365   ExprTy **Args, unsigned NumArgs)
366 {
367   assert(receiverName && "missing receiver class name");
368 
369   Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
370   ObjCInterfaceDecl* ClassDecl = 0;
371   bool isSuper = false;
372 
373   if (receiverName->isStr("super")) {
374     if (getCurMethodDecl()) {
375       isSuper = true;
376       ObjCInterfaceDecl *OID = getCurMethodDecl()->getClassInterface();
377       if (!OID)
378         return Diag(lbrac, diag::error_no_super_class_message)
379                       << getCurMethodDecl()->getDeclName();
380       ClassDecl = OID->getSuperClass();
381       if (!ClassDecl)
382         return Diag(lbrac, diag::error_no_super_class) << OID->getDeclName();
383       if (getCurMethodDecl()->isInstanceMethod()) {
384         QualType superTy = Context.getObjCInterfaceType(ClassDecl);
385         superTy = Context.getPointerType(superTy);
386         ExprResult ReceiverExpr = new (Context) ObjCSuperExpr(SourceLocation(),
387                                                               superTy);
388         // We are really in an instance method, redirect.
389         return ActOnInstanceMessage(ReceiverExpr.get(), Sel, lbrac,
390                                     selectorLoc, rbrac, Args, NumArgs);
391       }
392       // We are sending a message to 'super' within a class method. Do nothing,
393       // the receiver will pass through as 'super' (how convenient:-).
394     } else {
395       // 'super' has been used outside a method context. If a variable named
396       // 'super' has been declared, redirect. If not, produce a diagnostic.
397       NamedDecl *SuperDecl = LookupName(S, receiverName, LookupOrdinaryName);
398       ValueDecl *VD = dyn_cast_or_null<ValueDecl>(SuperDecl);
399       if (VD) {
400         ExprResult ReceiverExpr = new (Context) DeclRefExpr(VD, VD->getType(),
401                                                             receiverLoc);
402         // We are really in an instance method, redirect.
403         return ActOnInstanceMessage(ReceiverExpr.get(), Sel, lbrac,
404                                     selectorLoc, rbrac, Args, NumArgs);
405       }
406       return Diag(receiverLoc, diag::err_undeclared_var_use) << receiverName;
407     }
408   } else
409     ClassDecl = getObjCInterfaceDecl(receiverName);
410 
411   // The following code allows for the following GCC-ism:
412   //
413   //  typedef XCElementDisplayRect XCElementGraphicsRect;
414   //
415   //  @implementation XCRASlice
416   //  - whatever { // Note that XCElementGraphicsRect is a typedef name.
417   //    _sGraphicsDelegate =[[XCElementGraphicsRect alloc] init];
418   //  }
419   //
420   // If necessary, the following lookup could move to getObjCInterfaceDecl().
421   if (!ClassDecl) {
422     NamedDecl *IDecl = LookupName(TUScope, receiverName, LookupOrdinaryName);
423     if (TypedefDecl *OCTD = dyn_cast_or_null<TypedefDecl>(IDecl)) {
424       const ObjCInterfaceType *OCIT;
425       OCIT = OCTD->getUnderlyingType()->getAsObjCInterfaceType();
426       if (!OCIT) {
427         Diag(receiverLoc, diag::err_invalid_receiver_to_message);
428         return true;
429       }
430       ClassDecl = OCIT->getDecl();
431     }
432   }
433   assert(ClassDecl && "missing interface declaration");
434   ObjCMethodDecl *Method = 0;
435   QualType returnType;
436   if (ClassDecl->isForwardDecl()) {
437     // A forward class used in messaging is tread as a 'Class'
438     Diag(lbrac, diag::warn_receiver_forward_class) << ClassDecl->getDeclName();
439     Method = LookupFactoryMethodInGlobalPool(Sel, SourceRange(lbrac,rbrac));
440     if (Method)
441       Diag(Method->getLocation(), diag::note_method_sent_forward_class)
442         << Method->getDeclName();
443   }
444   if (!Method)
445     Method = ClassDecl->lookupClassMethod(Context, Sel);
446 
447   // If we have an implementation in scope, check "private" methods.
448   if (!Method)
449     Method = LookupPrivateClassMethod(Sel, ClassDecl);
450 
451   if (Method && DiagnoseUseOfDecl(Method, receiverLoc))
452     return true;
453 
454   if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, true,
455                                 lbrac, rbrac, returnType))
456     return true;
457 
458   returnType = returnType.getNonReferenceType();
459 
460   // If we have the ObjCInterfaceDecl* for the class that is receiving the
461   // message, use that to construct the ObjCMessageExpr.  Otherwise pass on the
462   // IdentifierInfo* for the class.
463   // FIXME: need to do a better job handling 'super' usage within a class.  For
464   // now, we simply pass the "super" identifier through (which isn't consistent
465   // with instance methods.
466   if (isSuper)
467     return new (Context) ObjCMessageExpr(receiverName, Sel, returnType, Method,
468                                          lbrac, rbrac, ArgExprs, NumArgs);
469   else
470     return new (Context) ObjCMessageExpr(ClassDecl, Sel, returnType, Method,
471                                          lbrac, rbrac, ArgExprs, NumArgs);
472 }
473 
474 // ActOnInstanceMessage - used for both unary and keyword messages.
475 // ArgExprs is optional - if it is present, the number of expressions
476 // is obtained from Sel.getNumArgs().
477 Sema::ExprResult Sema::ActOnInstanceMessage(ExprTy *receiver, Selector Sel,
478                                             SourceLocation lbrac,
479                                             SourceLocation receiverLoc,
480                                             SourceLocation rbrac,
481                                             ExprTy **Args, unsigned NumArgs) {
482   assert(receiver && "missing receiver expression");
483 
484   Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
485   Expr *RExpr = static_cast<Expr *>(receiver);
486 
487   // If necessary, apply function/array conversion to the receiver.
488   // C99 6.7.5.3p[7,8].
489   DefaultFunctionArrayConversion(RExpr);
490 
491   QualType returnType;
492   QualType ReceiverCType =
493     Context.getCanonicalType(RExpr->getType()).getUnqualifiedType();
494 
495   // Handle messages to 'super'.
496   if (isa<ObjCSuperExpr>(RExpr)) {
497     ObjCMethodDecl *Method = 0;
498     if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
499       // If we have an interface in scope, check 'super' methods.
500       if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
501         if (ObjCInterfaceDecl *SuperDecl = ClassDecl->getSuperClass()) {
502           Method = SuperDecl->lookupInstanceMethod(Context, Sel);
503 
504           if (!Method)
505             // If we have implementations in scope, check "private" methods.
506             Method = LookupPrivateInstanceMethod(Sel, SuperDecl);
507         }
508     }
509 
510     if (Method && DiagnoseUseOfDecl(Method, receiverLoc))
511       return true;
512 
513     if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, false,
514                                   lbrac, rbrac, returnType))
515       return true;
516 
517     returnType = returnType.getNonReferenceType();
518     return new (Context) ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac,
519                                          rbrac, ArgExprs, NumArgs);
520   }
521 
522   // Handle messages to id.
523   if (ReceiverCType == Context.getCanonicalType(Context.getObjCIdType()) ||
524       ReceiverCType->isBlockPointerType() ||
525       Context.isObjCNSObjectType(RExpr->getType())) {
526     ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(
527                                Sel, SourceRange(lbrac,rbrac));
528     if (!Method)
529       Method = LookupFactoryMethodInGlobalPool(Sel, SourceRange(lbrac, rbrac));
530     if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, false,
531                                   lbrac, rbrac, returnType))
532       return true;
533     returnType = returnType.getNonReferenceType();
534     return new (Context) ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac,
535                                          rbrac, ArgExprs, NumArgs);
536   }
537 
538   // Handle messages to Class.
539   if (ReceiverCType == Context.getCanonicalType(Context.getObjCClassType())) {
540     ObjCMethodDecl *Method = 0;
541 
542     if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
543       if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
544         // First check the public methods in the class interface.
545         Method = ClassDecl->lookupClassMethod(Context, Sel);
546 
547         if (!Method)
548           Method = LookupPrivateClassMethod(Sel, ClassDecl);
549       }
550       if (Method && DiagnoseUseOfDecl(Method, receiverLoc))
551         return true;
552     }
553     if (!Method) {
554       // If not messaging 'self', look for any factory method named 'Sel'.
555       if (!isSelfExpr(RExpr)) {
556         Method = LookupFactoryMethodInGlobalPool(Sel, SourceRange(lbrac,rbrac));
557         if (!Method) {
558           // If no class (factory) method was found, check if an _instance_
559           // method of the same name exists in the root class only.
560           Method = LookupInstanceMethodInGlobalPool(
561                                    Sel, SourceRange(lbrac,rbrac));
562           if (Method)
563               if (const ObjCInterfaceDecl *ID =
564                 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
565               if (ID->getSuperClass())
566                 Diag(lbrac, diag::warn_root_inst_method_not_found)
567                   << Sel << SourceRange(lbrac, rbrac);
568             }
569         }
570       }
571     }
572     if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, false,
573                                   lbrac, rbrac, returnType))
574       return true;
575     returnType = returnType.getNonReferenceType();
576     return new (Context) ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac,
577                                          rbrac, ArgExprs, NumArgs);
578   }
579 
580   ObjCMethodDecl *Method = 0;
581   ObjCInterfaceDecl* ClassDecl = 0;
582 
583   // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
584   // long as one of the protocols implements the selector (if not, warn).
585   if (ObjCQualifiedIdType *QIdTy = dyn_cast<ObjCQualifiedIdType>(ReceiverCType)) {
586     // Search protocols for instance methods.
587     for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
588          E = QIdTy->qual_end(); I != E; ++I) {
589       ObjCProtocolDecl *PDecl = *I;
590       if (PDecl && (Method = PDecl->lookupInstanceMethod(Context, Sel)))
591         break;
592       // Since we aren't supporting "Class<foo>", look for a class method.
593       if (PDecl && (Method = PDecl->lookupClassMethod(Context, Sel)))
594         break;
595     }
596   } else if (const ObjCInterfaceType *OCIType =
597                 ReceiverCType->getAsPointerToObjCInterfaceType()) {
598     // We allow sending a message to a pointer to an interface (an object).
599 
600     ClassDecl = OCIType->getDecl();
601     // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
602     // faster than the following method (which can do *many* linear searches).
603     // The idea is to add class info to InstanceMethodPool.
604     Method = ClassDecl->lookupInstanceMethod(Context, Sel);
605 
606     if (!Method) {
607       // Search protocol qualifiers.
608       for (ObjCQualifiedInterfaceType::qual_iterator QI = OCIType->qual_begin(),
609            E = OCIType->qual_end(); QI != E; ++QI) {
610         if ((Method = (*QI)->lookupInstanceMethod(Context, Sel)))
611           break;
612       }
613     }
614     if (!Method) {
615       // If we have implementations in scope, check "private" methods.
616       Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
617 
618       if (!Method && !isSelfExpr(RExpr)) {
619         // If we still haven't found a method, look in the global pool. This
620         // behavior isn't very desirable, however we need it for GCC
621         // compatibility. FIXME: should we deviate??
622         if (OCIType->qual_empty()) {
623           Method = LookupInstanceMethodInGlobalPool(
624                                Sel, SourceRange(lbrac,rbrac));
625           if (Method && !OCIType->getDecl()->isForwardDecl())
626             Diag(lbrac, diag::warn_maynot_respond)
627               << OCIType->getDecl()->getIdentifier()->getName() << Sel;
628         }
629       }
630     }
631     if (Method && DiagnoseUseOfDecl(Method, receiverLoc))
632       return true;
633   } else if (!Context.getObjCIdType().isNull() &&
634              (ReceiverCType->isPointerType() ||
635               (ReceiverCType->isIntegerType() &&
636                ReceiverCType->isScalarType()))) {
637     // Implicitly convert integers and pointers to 'id' but emit a warning.
638     Diag(lbrac, diag::warn_bad_receiver_type)
639       << RExpr->getType() << RExpr->getSourceRange();
640     ImpCastExprToType(RExpr, Context.getObjCIdType());
641   } else {
642     // Reject other random receiver types (e.g. structs).
643     Diag(lbrac, diag::err_bad_receiver_type)
644       << RExpr->getType() << RExpr->getSourceRange();
645     return true;
646   }
647 
648   if (Method)
649     DiagnoseSentinelCalls(Method, receiverLoc, ArgExprs, NumArgs);
650   if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, false,
651                                 lbrac, rbrac, returnType))
652     return true;
653   returnType = returnType.getNonReferenceType();
654   return new (Context) ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac,
655                                        rbrac, ArgExprs, NumArgs);
656 }
657 
658 //===----------------------------------------------------------------------===//
659 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
660 //===----------------------------------------------------------------------===//
661 
662 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
663 /// inheritance hierarchy of 'rProto'.
664 static bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
665                                            ObjCProtocolDecl *rProto) {
666   if (lProto == rProto)
667     return true;
668   for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
669        E = rProto->protocol_end(); PI != E; ++PI)
670     if (ProtocolCompatibleWithProtocol(lProto, *PI))
671       return true;
672   return false;
673 }
674 
675 /// ClassImplementsProtocol - Checks that 'lProto' protocol
676 /// has been implemented in IDecl class, its super class or categories (if
677 /// lookupCategory is true).
678 static bool ClassImplementsProtocol(ObjCProtocolDecl *lProto,
679                                     ObjCInterfaceDecl *IDecl,
680                                     bool lookupCategory,
681                                     bool RHSIsQualifiedID = false) {
682 
683   // 1st, look up the class.
684   const ObjCList<ObjCProtocolDecl> &Protocols =
685     IDecl->getReferencedProtocols();
686 
687   for (ObjCList<ObjCProtocolDecl>::iterator PI = Protocols.begin(),
688        E = Protocols.end(); PI != E; ++PI) {
689     if (ProtocolCompatibleWithProtocol(lProto, *PI))
690       return true;
691     // This is dubious and is added to be compatible with gcc.  In gcc, it is
692     // also allowed assigning a protocol-qualified 'id' type to a LHS object
693     // when protocol in qualified LHS is in list of protocols in the rhs 'id'
694     // object. This IMO, should be a bug.
695     // FIXME: Treat this as an extension, and flag this as an error when GCC
696     // extensions are not enabled.
697     if (RHSIsQualifiedID && ProtocolCompatibleWithProtocol(*PI, lProto))
698       return true;
699   }
700 
701   // 2nd, look up the category.
702   if (lookupCategory)
703     for (ObjCCategoryDecl *CDecl = IDecl->getCategoryList(); CDecl;
704          CDecl = CDecl->getNextClassCategory()) {
705       for (ObjCCategoryDecl::protocol_iterator PI = CDecl->protocol_begin(),
706            E = CDecl->protocol_end(); PI != E; ++PI)
707         if (ProtocolCompatibleWithProtocol(lProto, *PI))
708           return true;
709     }
710 
711   // 3rd, look up the super class(s)
712   if (IDecl->getSuperClass())
713     return
714       ClassImplementsProtocol(lProto, IDecl->getSuperClass(), lookupCategory,
715                               RHSIsQualifiedID);
716 
717   return false;
718 }
719 
720 /// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
721 /// return true if lhs's protocols conform to rhs's protocol; false
722 /// otherwise.
723 bool Sema::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
724   if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
725     return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
726   return false;
727 }
728 
729 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
730 /// ObjCQualifiedIDType.
731 /// FIXME: Move to ASTContext::typesAreCompatible() and friends.
732 bool Sema::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
733                                              bool compare) {
734   // Allow id<P..> and an 'id' or void* type in all cases.
735   if (const PointerType *PT = lhs->getAsPointerType()) {
736     QualType PointeeTy = PT->getPointeeType();
737     if (PointeeTy->isVoidType() ||
738         Context.isObjCIdStructType(PointeeTy) ||
739         Context.isObjCClassStructType(PointeeTy))
740       return true;
741   } else if (const PointerType *PT = rhs->getAsPointerType()) {
742     QualType PointeeTy = PT->getPointeeType();
743     if (PointeeTy->isVoidType() ||
744         Context.isObjCIdStructType(PointeeTy) ||
745         Context.isObjCClassStructType(PointeeTy))
746       return true;
747   }
748 
749   if (const ObjCQualifiedIdType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
750     const ObjCQualifiedIdType *rhsQID = rhs->getAsObjCQualifiedIdType();
751     const ObjCQualifiedInterfaceType *rhsQI = 0;
752     QualType rtype;
753 
754     if (!rhsQID) {
755       // Not comparing two ObjCQualifiedIdType's?
756       if (!rhs->isPointerType()) return false;
757 
758       rtype = rhs->getAsPointerType()->getPointeeType();
759       rhsQI = rtype->getAsObjCQualifiedInterfaceType();
760       if (rhsQI == 0) {
761         // If the RHS is a unqualified interface pointer "NSString*",
762         // make sure we check the class hierarchy.
763         if (const ObjCInterfaceType *IT = rtype->getAsObjCInterfaceType()) {
764           ObjCInterfaceDecl *rhsID = IT->getDecl();
765           for (ObjCQualifiedIdType::qual_iterator I = lhsQID->qual_begin(),
766                E = lhsQID->qual_end(); I != E; ++I) {
767             // when comparing an id<P> on lhs with a static type on rhs,
768             // see if static class implements all of id's protocols, directly or
769             // through its super class and categories.
770             if (!ClassImplementsProtocol(*I, rhsID, true))
771               return false;
772           }
773           return true;
774         }
775       }
776     }
777 
778     ObjCQualifiedIdType::qual_iterator RHSProtoI, RHSProtoE;
779     if (rhsQI) { // We have a qualified interface (e.g. "NSObject<Proto> *").
780       RHSProtoI = rhsQI->qual_begin();
781       RHSProtoE = rhsQI->qual_end();
782     } else if (rhsQID) { // We have a qualified id (e.g. "id<Proto> *").
783       RHSProtoI = rhsQID->qual_begin();
784       RHSProtoE = rhsQID->qual_end();
785     } else {
786       return false;
787     }
788 
789     for (ObjCQualifiedIdType::qual_iterator I = lhsQID->qual_begin(),
790          E = lhsQID->qual_end(); I != E; ++I) {
791       ObjCProtocolDecl *lhsProto = *I;
792       bool match = false;
793 
794       // when comparing an id<P> on lhs with a static type on rhs,
795       // see if static class implements all of id's protocols, directly or
796       // through its super class and categories.
797       for (; RHSProtoI != RHSProtoE; ++RHSProtoI) {
798         ObjCProtocolDecl *rhsProto = *RHSProtoI;
799         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
800             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
801           match = true;
802           break;
803         }
804       }
805       if (rhsQI) {
806         // If the RHS is a qualified interface pointer "NSString<P>*",
807         // make sure we check the class hierarchy.
808         if (const ObjCInterfaceType *IT = rtype->getAsObjCInterfaceType()) {
809           ObjCInterfaceDecl *rhsID = IT->getDecl();
810           for (ObjCQualifiedIdType::qual_iterator I = lhsQID->qual_begin(),
811                E = lhsQID->qual_end(); I != E; ++I) {
812             // when comparing an id<P> on lhs with a static type on rhs,
813             // see if static class implements all of id's protocols, directly or
814             // through its super class and categories.
815             if (ClassImplementsProtocol(*I, rhsID, true)) {
816               match = true;
817               break;
818             }
819           }
820         }
821       }
822       if (!match)
823         return false;
824     }
825 
826     return true;
827   }
828 
829   const ObjCQualifiedIdType *rhsQID = rhs->getAsObjCQualifiedIdType();
830   assert(rhsQID && "One of the LHS/RHS should be id<x>");
831 
832   if (!lhs->isPointerType())
833     return false;
834 
835   QualType ltype = lhs->getAsPointerType()->getPointeeType();
836   if (const ObjCQualifiedInterfaceType *lhsQI =
837          ltype->getAsObjCQualifiedInterfaceType()) {
838     ObjCQualifiedIdType::qual_iterator LHSProtoI = lhsQI->qual_begin();
839     ObjCQualifiedIdType::qual_iterator LHSProtoE = lhsQI->qual_end();
840     for (; LHSProtoI != LHSProtoE; ++LHSProtoI) {
841       bool match = false;
842       ObjCProtocolDecl *lhsProto = *LHSProtoI;
843       for (ObjCQualifiedIdType::qual_iterator I = rhsQID->qual_begin(),
844            E = rhsQID->qual_end(); I != E; ++I) {
845         ObjCProtocolDecl *rhsProto = *I;
846         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
847             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
848           match = true;
849           break;
850         }
851       }
852       if (!match)
853         return false;
854     }
855     return true;
856   }
857 
858   if (const ObjCInterfaceType *IT = ltype->getAsObjCInterfaceType()) {
859     // for static type vs. qualified 'id' type, check that class implements
860     // all of 'id's protocols.
861     ObjCInterfaceDecl *lhsID = IT->getDecl();
862     for (ObjCQualifiedIdType::qual_iterator I = rhsQID->qual_begin(),
863          E = rhsQID->qual_end(); I != E; ++I) {
864       if (!ClassImplementsProtocol(*I, lhsID, compare, true))
865         return false;
866     }
867     return true;
868   }
869   return false;
870 }
871 
872