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/Edit/Rewriters.h"
21 #include "clang/Edit/Commit.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "clang/Lex/Preprocessor.h"
29 
30 using namespace clang;
31 using namespace sema;
32 using llvm::makeArrayRef;
33 
34 ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
35                                         Expr **strings,
36                                         unsigned NumStrings) {
37   StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
38 
39   // Most ObjC strings are formed out of a single piece.  However, we *can*
40   // have strings formed out of multiple @ strings with multiple pptokens in
41   // each one, e.g. @"foo" "bar" @"baz" "qux"   which need to be turned into one
42   // StringLiteral for ObjCStringLiteral to hold onto.
43   StringLiteral *S = Strings[0];
44 
45   // If we have a multi-part string, merge it all together.
46   if (NumStrings != 1) {
47     // Concatenate objc strings.
48     SmallString<128> StrBuf;
49     SmallVector<SourceLocation, 8> StrLocs;
50 
51     for (unsigned i = 0; i != NumStrings; ++i) {
52       S = Strings[i];
53 
54       // ObjC strings can't be wide or UTF.
55       if (!S->isAscii()) {
56         Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
57           << S->getSourceRange();
58         return true;
59       }
60 
61       // Append the string.
62       StrBuf += S->getString();
63 
64       // Get the locations of the string tokens.
65       StrLocs.append(S->tokloc_begin(), S->tokloc_end());
66     }
67 
68     // Create the aggregate string with the appropriate content and location
69     // information.
70     S = StringLiteral::Create(Context, StrBuf,
71                               StringLiteral::Ascii, /*Pascal=*/false,
72                               Context.getPointerType(Context.CharTy),
73                               &StrLocs[0], StrLocs.size());
74   }
75 
76   return BuildObjCStringLiteral(AtLocs[0], S);
77 }
78 
79 ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
80   // Verify that this composite string is acceptable for ObjC strings.
81   if (CheckObjCString(S))
82     return true;
83 
84   // Initialize the constant string interface lazily. This assumes
85   // the NSString interface is seen in this translation unit. Note: We
86   // don't use NSConstantString, since the runtime team considers this
87   // interface private (even though it appears in the header files).
88   QualType Ty = Context.getObjCConstantStringInterface();
89   if (!Ty.isNull()) {
90     Ty = Context.getObjCObjectPointerType(Ty);
91   } else if (getLangOpts().NoConstantCFStrings) {
92     IdentifierInfo *NSIdent=0;
93     std::string StringClass(getLangOpts().ObjCConstantStringClass);
94 
95     if (StringClass.empty())
96       NSIdent = &Context.Idents.get("NSConstantString");
97     else
98       NSIdent = &Context.Idents.get(StringClass);
99 
100     NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
101                                      LookupOrdinaryName);
102     if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
103       Context.setObjCConstantStringInterface(StrIF);
104       Ty = Context.getObjCConstantStringInterface();
105       Ty = Context.getObjCObjectPointerType(Ty);
106     } else {
107       // If there is no NSConstantString interface defined then treat this
108       // as error and recover from it.
109       Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
110         << S->getSourceRange();
111       Ty = Context.getObjCIdType();
112     }
113   } else {
114     IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
115     NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
116                                      LookupOrdinaryName);
117     if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
118       Context.setObjCConstantStringInterface(StrIF);
119       Ty = Context.getObjCConstantStringInterface();
120       Ty = Context.getObjCObjectPointerType(Ty);
121     } else {
122       // If there is no NSString interface defined, implicitly declare
123       // a @class NSString; and use that instead. This is to make sure
124       // type of an NSString literal is represented correctly, instead of
125       // being an 'id' type.
126       Ty = Context.getObjCNSStringType();
127       if (Ty.isNull()) {
128         ObjCInterfaceDecl *NSStringIDecl =
129           ObjCInterfaceDecl::Create (Context,
130                                      Context.getTranslationUnitDecl(),
131                                      SourceLocation(), NSIdent,
132                                      0, SourceLocation());
133         Ty = Context.getObjCInterfaceType(NSStringIDecl);
134         Context.setObjCNSStringType(Ty);
135       }
136       Ty = Context.getObjCObjectPointerType(Ty);
137     }
138   }
139 
140   return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
141 }
142 
143 /// \brief Emits an error if the given method does not exist, or if the return
144 /// type is not an Objective-C object.
145 static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
146                                  const ObjCInterfaceDecl *Class,
147                                  Selector Sel, const ObjCMethodDecl *Method) {
148   if (!Method) {
149     // FIXME: Is there a better way to avoid quotes than using getName()?
150     S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
151     return false;
152   }
153 
154   // Make sure the return type is reasonable.
155   QualType ReturnType = Method->getResultType();
156   if (!ReturnType->isObjCObjectPointerType()) {
157     S.Diag(Loc, diag::err_objc_literal_method_sig)
158       << Sel;
159     S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
160       << ReturnType;
161     return false;
162   }
163 
164   return true;
165 }
166 
167 /// \brief Retrieve the NSNumber factory method that should be used to create
168 /// an Objective-C literal for the given type.
169 static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
170                                                 QualType NumberType,
171                                                 bool isLiteral = false,
172                                                 SourceRange R = SourceRange()) {
173   llvm::Optional<NSAPI::NSNumberLiteralMethodKind> Kind
174     = S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
175 
176   if (!Kind) {
177     if (isLiteral) {
178       S.Diag(Loc, diag::err_invalid_nsnumber_type)
179         << NumberType << R;
180     }
181     return 0;
182   }
183 
184   // If we already looked up this method, we're done.
185   if (S.NSNumberLiteralMethods[*Kind])
186     return S.NSNumberLiteralMethods[*Kind];
187 
188   Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
189                                                         /*Instance=*/false);
190 
191   ASTContext &CX = S.Context;
192 
193   // Look up the NSNumber class, if we haven't done so already. It's cached
194   // in the Sema instance.
195   if (!S.NSNumberDecl) {
196     IdentifierInfo *NSNumberId =
197       S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber);
198     NamedDecl *IF = S.LookupSingleName(S.TUScope, NSNumberId,
199                                        Loc, Sema::LookupOrdinaryName);
200     S.NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
201     if (!S.NSNumberDecl) {
202       if (S.getLangOpts().DebuggerObjCLiteral) {
203         // Create a stub definition of NSNumber.
204         S.NSNumberDecl = ObjCInterfaceDecl::Create(CX,
205                                                    CX.getTranslationUnitDecl(),
206                                                    SourceLocation(), NSNumberId,
207                                                    0, SourceLocation());
208       } else {
209         // Otherwise, require a declaration of NSNumber.
210         S.Diag(Loc, diag::err_undeclared_nsnumber);
211         return 0;
212       }
213     } else if (!S.NSNumberDecl->hasDefinition()) {
214       S.Diag(Loc, diag::err_undeclared_nsnumber);
215       return 0;
216     }
217 
218     // generate the pointer to NSNumber type.
219     QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
220     S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
221   }
222 
223   // Look for the appropriate method within NSNumber.
224   ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
225   if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
226     // create a stub definition this NSNumber factory method.
227     TypeSourceInfo *ResultTInfo = 0;
228     Method = ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
229                                     S.NSNumberPointer, ResultTInfo,
230                                     S.NSNumberDecl,
231                                     /*isInstance=*/false, /*isVariadic=*/false,
232                                     /*isSynthesized=*/false,
233                                     /*isImplicitlyDeclared=*/true,
234                                     /*isDefined=*/false,
235                                     ObjCMethodDecl::Required,
236                                     /*HasRelatedResultType=*/false);
237     ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
238                                              SourceLocation(), SourceLocation(),
239                                              &CX.Idents.get("value"),
240                                              NumberType, /*TInfo=*/0, SC_None,
241                                              SC_None, 0);
242     Method->setMethodParams(S.Context, value, ArrayRef<SourceLocation>());
243   }
244 
245   if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
246     return 0;
247 
248   // Note: if the parameter type is out-of-line, we'll catch it later in the
249   // implicit conversion.
250 
251   S.NSNumberLiteralMethods[*Kind] = Method;
252   return Method;
253 }
254 
255 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
256 /// numeric literal expression. Type of the expression will be "NSNumber *".
257 ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
258   // Determine the type of the literal.
259   QualType NumberType = Number->getType();
260   if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
261     // In C, character literals have type 'int'. That's not the type we want
262     // to use to determine the Objective-c literal kind.
263     switch (Char->getKind()) {
264     case CharacterLiteral::Ascii:
265       NumberType = Context.CharTy;
266       break;
267 
268     case CharacterLiteral::Wide:
269       NumberType = Context.getWCharType();
270       break;
271 
272     case CharacterLiteral::UTF16:
273       NumberType = Context.Char16Ty;
274       break;
275 
276     case CharacterLiteral::UTF32:
277       NumberType = Context.Char32Ty;
278       break;
279     }
280   }
281 
282   // Look for the appropriate method within NSNumber.
283   // Construct the literal.
284   SourceRange NR(Number->getSourceRange());
285   ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
286                                                     true, NR);
287   if (!Method)
288     return ExprError();
289 
290   // Convert the number to the type that the parameter expects.
291   ParmVarDecl *ParamDecl = Method->param_begin()[0];
292   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
293                                                                     ParamDecl);
294   ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
295                                                          SourceLocation(),
296                                                          Owned(Number));
297   if (ConvertedNumber.isInvalid())
298     return ExprError();
299   Number = ConvertedNumber.get();
300 
301   // Use the effective source range of the literal, including the leading '@'.
302   return MaybeBindToTemporary(
303            new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
304                                        SourceRange(AtLoc, NR.getEnd())));
305 }
306 
307 ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
308                                       SourceLocation ValueLoc,
309                                       bool Value) {
310   ExprResult Inner;
311   if (getLangOpts().CPlusPlus) {
312     Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
313   } else {
314     // C doesn't actually have a way to represent literal values of type
315     // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
316     Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
317     Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
318                               CK_IntegralToBoolean);
319   }
320 
321   return BuildObjCNumericLiteral(AtLoc, Inner.get());
322 }
323 
324 /// \brief Check that the given expression is a valid element of an Objective-C
325 /// collection literal.
326 static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
327                                                     QualType T) {
328   // If the expression is type-dependent, there's nothing for us to do.
329   if (Element->isTypeDependent())
330     return Element;
331 
332   ExprResult Result = S.CheckPlaceholderExpr(Element);
333   if (Result.isInvalid())
334     return ExprError();
335   Element = Result.get();
336 
337   // In C++, check for an implicit conversion to an Objective-C object pointer
338   // type.
339   if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
340     InitializedEntity Entity
341       = InitializedEntity::InitializeParameter(S.Context, T,
342                                                /*Consumed=*/false);
343     InitializationKind Kind
344       = InitializationKind::CreateCopy(Element->getLocStart(),
345                                        SourceLocation());
346     InitializationSequence Seq(S, Entity, Kind, &Element, 1);
347     if (!Seq.Failed())
348       return Seq.Perform(S, Entity, Kind, MultiExprArg(S, &Element, 1));
349   }
350 
351   Expr *OrigElement = Element;
352 
353   // Perform lvalue-to-rvalue conversion.
354   Result = S.DefaultLvalueConversion(Element);
355   if (Result.isInvalid())
356     return ExprError();
357   Element = Result.get();
358 
359   // Make sure that we have an Objective-C pointer type or block.
360   if (!Element->getType()->isObjCObjectPointerType() &&
361       !Element->getType()->isBlockPointerType()) {
362     bool Recovered = false;
363 
364     // If this is potentially an Objective-C numeric literal, add the '@'.
365     if (isa<IntegerLiteral>(OrigElement) ||
366         isa<CharacterLiteral>(OrigElement) ||
367         isa<FloatingLiteral>(OrigElement) ||
368         isa<ObjCBoolLiteralExpr>(OrigElement) ||
369         isa<CXXBoolLiteralExpr>(OrigElement)) {
370       if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
371         int Which = isa<CharacterLiteral>(OrigElement) ? 1
372                   : (isa<CXXBoolLiteralExpr>(OrigElement) ||
373                      isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
374                   : 3;
375 
376         S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
377           << Which << OrigElement->getSourceRange()
378           << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
379 
380         Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
381                                            OrigElement);
382         if (Result.isInvalid())
383           return ExprError();
384 
385         Element = Result.get();
386         Recovered = true;
387       }
388     }
389     // If this is potentially an Objective-C string literal, add the '@'.
390     else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
391       if (String->isAscii()) {
392         S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
393           << 0 << OrigElement->getSourceRange()
394           << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
395 
396         Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
397         if (Result.isInvalid())
398           return ExprError();
399 
400         Element = Result.get();
401         Recovered = true;
402       }
403     }
404 
405     if (!Recovered) {
406       S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
407         << Element->getType();
408       return ExprError();
409     }
410   }
411 
412   // Make sure that the element has the type that the container factory
413   // function expects.
414   return S.PerformCopyInitialization(
415            InitializedEntity::InitializeParameter(S.Context, T,
416                                                   /*Consumed=*/false),
417            Element->getLocStart(), Element);
418 }
419 
420 ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
421   if (ValueExpr->isTypeDependent()) {
422     ObjCBoxedExpr *BoxedExpr =
423       new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, NULL, SR);
424     return Owned(BoxedExpr);
425   }
426   ObjCMethodDecl *BoxingMethod = NULL;
427   QualType BoxedType;
428   // Convert the expression to an RValue, so we can check for pointer types...
429   ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
430   if (RValue.isInvalid()) {
431     return ExprError();
432   }
433   ValueExpr = RValue.get();
434   QualType ValueType(ValueExpr->getType());
435   if (const PointerType *PT = ValueType->getAs<PointerType>()) {
436     QualType PointeeType = PT->getPointeeType();
437     if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
438 
439       if (!NSStringDecl) {
440         IdentifierInfo *NSStringId =
441           NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
442         NamedDecl *Decl = LookupSingleName(TUScope, NSStringId,
443                                            SR.getBegin(), LookupOrdinaryName);
444         NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl);
445         if (!NSStringDecl) {
446           if (getLangOpts().DebuggerObjCLiteral) {
447             // Support boxed expressions in the debugger w/o NSString declaration.
448             DeclContext *TU = Context.getTranslationUnitDecl();
449             NSStringDecl = ObjCInterfaceDecl::Create(Context, TU,
450                                                      SourceLocation(),
451                                                      NSStringId,
452                                                      0, SourceLocation());
453           } else {
454             Diag(SR.getBegin(), diag::err_undeclared_nsstring);
455             return ExprError();
456           }
457         } else if (!NSStringDecl->hasDefinition()) {
458           Diag(SR.getBegin(), diag::err_undeclared_nsstring);
459           return ExprError();
460         }
461         assert(NSStringDecl && "NSStringDecl should not be NULL");
462         QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
463         NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
464       }
465 
466       if (!StringWithUTF8StringMethod) {
467         IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
468         Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
469 
470         // Look for the appropriate method within NSString.
471         BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
472         if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
473           // Debugger needs to work even if NSString hasn't been defined.
474           TypeSourceInfo *ResultTInfo = 0;
475           ObjCMethodDecl *M =
476             ObjCMethodDecl::Create(Context, SourceLocation(), SourceLocation(),
477                                    stringWithUTF8String, NSStringPointer,
478                                    ResultTInfo, NSStringDecl,
479                                    /*isInstance=*/false, /*isVariadic=*/false,
480                                    /*isSynthesized=*/false,
481                                    /*isImplicitlyDeclared=*/true,
482                                    /*isDefined=*/false,
483                                    ObjCMethodDecl::Required,
484                                    /*HasRelatedResultType=*/false);
485           QualType ConstCharType = Context.CharTy.withConst();
486           ParmVarDecl *value =
487             ParmVarDecl::Create(Context, M,
488                                 SourceLocation(), SourceLocation(),
489                                 &Context.Idents.get("value"),
490                                 Context.getPointerType(ConstCharType),
491                                 /*TInfo=*/0,
492                                 SC_None, SC_None, 0);
493           M->setMethodParams(Context, value, ArrayRef<SourceLocation>());
494           BoxingMethod = M;
495         }
496 
497         if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl,
498                                   stringWithUTF8String, BoxingMethod))
499            return ExprError();
500 
501         StringWithUTF8StringMethod = BoxingMethod;
502       }
503 
504       BoxingMethod = StringWithUTF8StringMethod;
505       BoxedType = NSStringPointer;
506     }
507   } else if (ValueType->isBuiltinType()) {
508     // The other types we support are numeric, char and BOOL/bool. We could also
509     // provide limited support for structure types, such as NSRange, NSRect, and
510     // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
511     // for more details.
512 
513     // Check for a top-level character literal.
514     if (const CharacterLiteral *Char =
515         dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
516       // In C, character literals have type 'int'. That's not the type we want
517       // to use to determine the Objective-c literal kind.
518       switch (Char->getKind()) {
519       case CharacterLiteral::Ascii:
520         ValueType = Context.CharTy;
521         break;
522 
523       case CharacterLiteral::Wide:
524         ValueType = Context.getWCharType();
525         break;
526 
527       case CharacterLiteral::UTF16:
528         ValueType = Context.Char16Ty;
529         break;
530 
531       case CharacterLiteral::UTF32:
532         ValueType = Context.Char32Ty;
533         break;
534       }
535     }
536 
537     // FIXME:  Do I need to do anything special with BoolTy expressions?
538 
539     // Look for the appropriate method within NSNumber.
540     BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType);
541     BoxedType = NSNumberPointer;
542 
543   } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
544     if (!ET->getDecl()->isComplete()) {
545       Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type)
546         << ValueType << ValueExpr->getSourceRange();
547       return ExprError();
548     }
549 
550     BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(),
551                                             ET->getDecl()->getIntegerType());
552     BoxedType = NSNumberPointer;
553   }
554 
555   if (!BoxingMethod) {
556     Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type)
557       << ValueType << ValueExpr->getSourceRange();
558     return ExprError();
559   }
560 
561   // Convert the expression to the type that the parameter requires.
562   ParmVarDecl *ParamDecl = BoxingMethod->param_begin()[0];
563   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
564                                                                     ParamDecl);
565   ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity,
566                                                             SourceLocation(),
567                                                             Owned(ValueExpr));
568   if (ConvertedValueExpr.isInvalid())
569     return ExprError();
570   ValueExpr = ConvertedValueExpr.get();
571 
572   ObjCBoxedExpr *BoxedExpr =
573     new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
574                                       BoxingMethod, SR);
575   return MaybeBindToTemporary(BoxedExpr);
576 }
577 
578 /// Build an ObjC subscript pseudo-object expression, given that
579 /// that's supported by the runtime.
580 ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
581                                         Expr *IndexExpr,
582                                         ObjCMethodDecl *getterMethod,
583                                         ObjCMethodDecl *setterMethod) {
584   assert(!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic());
585 
586   // We can't get dependent types here; our callers should have
587   // filtered them out.
588   assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
589          "base or index cannot have dependent type here");
590 
591   // Filter out placeholders in the index.  In theory, overloads could
592   // be preserved here, although that might not actually work correctly.
593   ExprResult Result = CheckPlaceholderExpr(IndexExpr);
594   if (Result.isInvalid())
595     return ExprError();
596   IndexExpr = Result.get();
597 
598   // Perform lvalue-to-rvalue conversion on the base.
599   Result = DefaultLvalueConversion(BaseExpr);
600   if (Result.isInvalid())
601     return ExprError();
602   BaseExpr = Result.get();
603 
604   // Build the pseudo-object expression.
605   return Owned(ObjCSubscriptRefExpr::Create(Context,
606                                             BaseExpr,
607                                             IndexExpr,
608                                             Context.PseudoObjectTy,
609                                             getterMethod,
610                                             setterMethod, RB));
611 
612 }
613 
614 ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
615   // Look up the NSArray class, if we haven't done so already.
616   if (!NSArrayDecl) {
617     NamedDecl *IF = LookupSingleName(TUScope,
618                                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
619                                  SR.getBegin(),
620                                  LookupOrdinaryName);
621     NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
622     if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
623       NSArrayDecl =  ObjCInterfaceDecl::Create (Context,
624                             Context.getTranslationUnitDecl(),
625                             SourceLocation(),
626                             NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
627                             0, SourceLocation());
628 
629     if (!NSArrayDecl) {
630       Diag(SR.getBegin(), diag::err_undeclared_nsarray);
631       return ExprError();
632     }
633   }
634 
635   // Find the arrayWithObjects:count: method, if we haven't done so already.
636   QualType IdT = Context.getObjCIdType();
637   if (!ArrayWithObjectsMethod) {
638     Selector
639       Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
640     ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
641     if (!Method && getLangOpts().DebuggerObjCLiteral) {
642       TypeSourceInfo *ResultTInfo = 0;
643       Method = ObjCMethodDecl::Create(Context,
644                            SourceLocation(), SourceLocation(), Sel,
645                            IdT,
646                            ResultTInfo,
647                            Context.getTranslationUnitDecl(),
648                            false /*Instance*/, false/*isVariadic*/,
649                            /*isSynthesized=*/false,
650                            /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
651                            ObjCMethodDecl::Required,
652                            false);
653       SmallVector<ParmVarDecl *, 2> Params;
654       ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
655                                                  SourceLocation(),
656                                                  SourceLocation(),
657                                                  &Context.Idents.get("objects"),
658                                                  Context.getPointerType(IdT),
659                                                  /*TInfo=*/0, SC_None, SC_None,
660                                                  0);
661       Params.push_back(objects);
662       ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
663                                              SourceLocation(),
664                                              SourceLocation(),
665                                              &Context.Idents.get("cnt"),
666                                              Context.UnsignedLongTy,
667                                              /*TInfo=*/0, SC_None, SC_None,
668                                              0);
669       Params.push_back(cnt);
670       Method->setMethodParams(Context, Params, ArrayRef<SourceLocation>());
671     }
672 
673     if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method))
674       return ExprError();
675 
676     // Dig out the type that all elements should be converted to.
677     QualType T = Method->param_begin()[0]->getType();
678     const PointerType *PtrT = T->getAs<PointerType>();
679     if (!PtrT ||
680         !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
681       Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
682         << Sel;
683       Diag(Method->param_begin()[0]->getLocation(),
684            diag::note_objc_literal_method_param)
685         << 0 << T
686         << Context.getPointerType(IdT.withConst());
687       return ExprError();
688     }
689 
690     // Check that the 'count' parameter is integral.
691     if (!Method->param_begin()[1]->getType()->isIntegerType()) {
692       Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
693         << Sel;
694       Diag(Method->param_begin()[1]->getLocation(),
695            diag::note_objc_literal_method_param)
696         << 1
697         << Method->param_begin()[1]->getType()
698         << "integral";
699       return ExprError();
700     }
701 
702     // We've found a good +arrayWithObjects:count: method. Save it!
703     ArrayWithObjectsMethod = Method;
704   }
705 
706   QualType ObjectsType = ArrayWithObjectsMethod->param_begin()[0]->getType();
707   QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
708 
709   // Check that each of the elements provided is valid in a collection literal,
710   // performing conversions as necessary.
711   Expr **ElementsBuffer = Elements.get();
712   for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
713     ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
714                                                              ElementsBuffer[I],
715                                                              RequiredType);
716     if (Converted.isInvalid())
717       return ExprError();
718 
719     ElementsBuffer[I] = Converted.get();
720   }
721 
722   QualType Ty
723     = Context.getObjCObjectPointerType(
724                                     Context.getObjCInterfaceType(NSArrayDecl));
725 
726   return MaybeBindToTemporary(
727            ObjCArrayLiteral::Create(Context,
728                                     llvm::makeArrayRef(Elements.get(),
729                                                        Elements.size()),
730                                     Ty, ArrayWithObjectsMethod, SR));
731 }
732 
733 ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
734                                             ObjCDictionaryElement *Elements,
735                                             unsigned NumElements) {
736   // Look up the NSDictionary class, if we haven't done so already.
737   if (!NSDictionaryDecl) {
738     NamedDecl *IF = LookupSingleName(TUScope,
739                             NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
740                             SR.getBegin(), LookupOrdinaryName);
741     NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
742     if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
743       NSDictionaryDecl =  ObjCInterfaceDecl::Create (Context,
744                             Context.getTranslationUnitDecl(),
745                             SourceLocation(),
746                             NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
747                             0, SourceLocation());
748 
749     if (!NSDictionaryDecl) {
750       Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
751       return ExprError();
752     }
753   }
754 
755   // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
756   // so already.
757   QualType IdT = Context.getObjCIdType();
758   if (!DictionaryWithObjectsMethod) {
759     Selector Sel = NSAPIObj->getNSDictionarySelector(
760                                NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
761     ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
762     if (!Method && getLangOpts().DebuggerObjCLiteral) {
763       Method = ObjCMethodDecl::Create(Context,
764                            SourceLocation(), SourceLocation(), Sel,
765                            IdT,
766                            0 /*TypeSourceInfo */,
767                            Context.getTranslationUnitDecl(),
768                            false /*Instance*/, false/*isVariadic*/,
769                            /*isSynthesized=*/false,
770                            /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
771                            ObjCMethodDecl::Required,
772                            false);
773       SmallVector<ParmVarDecl *, 3> Params;
774       ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
775                                                  SourceLocation(),
776                                                  SourceLocation(),
777                                                  &Context.Idents.get("objects"),
778                                                  Context.getPointerType(IdT),
779                                                  /*TInfo=*/0, SC_None, SC_None,
780                                                  0);
781       Params.push_back(objects);
782       ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
783                                               SourceLocation(),
784                                               SourceLocation(),
785                                               &Context.Idents.get("keys"),
786                                               Context.getPointerType(IdT),
787                                               /*TInfo=*/0, SC_None, SC_None,
788                                               0);
789       Params.push_back(keys);
790       ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
791                                              SourceLocation(),
792                                              SourceLocation(),
793                                              &Context.Idents.get("cnt"),
794                                              Context.UnsignedLongTy,
795                                              /*TInfo=*/0, SC_None, SC_None,
796                                              0);
797       Params.push_back(cnt);
798       Method->setMethodParams(Context, Params, ArrayRef<SourceLocation>());
799     }
800 
801     if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
802                               Method))
803        return ExprError();
804 
805     // Dig out the type that all values should be converted to.
806     QualType ValueT = Method->param_begin()[0]->getType();
807     const PointerType *PtrValue = ValueT->getAs<PointerType>();
808     if (!PtrValue ||
809         !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
810       Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
811         << Sel;
812       Diag(Method->param_begin()[0]->getLocation(),
813            diag::note_objc_literal_method_param)
814         << 0 << ValueT
815         << Context.getPointerType(IdT.withConst());
816       return ExprError();
817     }
818 
819     // Dig out the type that all keys should be converted to.
820     QualType KeyT = Method->param_begin()[1]->getType();
821     const PointerType *PtrKey = KeyT->getAs<PointerType>();
822     if (!PtrKey ||
823         !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
824                                         IdT)) {
825       bool err = true;
826       if (PtrKey) {
827         if (QIDNSCopying.isNull()) {
828           // key argument of selector is id<NSCopying>?
829           if (ObjCProtocolDecl *NSCopyingPDecl =
830               LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
831             ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
832             QIDNSCopying =
833               Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
834                                         (ObjCProtocolDecl**) PQ,1);
835             QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
836           }
837         }
838         if (!QIDNSCopying.isNull())
839           err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
840                                                 QIDNSCopying);
841       }
842 
843       if (err) {
844         Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
845           << Sel;
846         Diag(Method->param_begin()[1]->getLocation(),
847              diag::note_objc_literal_method_param)
848           << 1 << KeyT
849           << Context.getPointerType(IdT.withConst());
850         return ExprError();
851       }
852     }
853 
854     // Check that the 'count' parameter is integral.
855     QualType CountType = Method->param_begin()[2]->getType();
856     if (!CountType->isIntegerType()) {
857       Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
858         << Sel;
859       Diag(Method->param_begin()[2]->getLocation(),
860            diag::note_objc_literal_method_param)
861         << 2 << CountType
862         << "integral";
863       return ExprError();
864     }
865 
866     // We've found a good +dictionaryWithObjects:keys:count: method; save it!
867     DictionaryWithObjectsMethod = Method;
868   }
869 
870   QualType ValuesT = DictionaryWithObjectsMethod->param_begin()[0]->getType();
871   QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
872   QualType KeysT = DictionaryWithObjectsMethod->param_begin()[1]->getType();
873   QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
874 
875   // Check that each of the keys and values provided is valid in a collection
876   // literal, performing conversions as necessary.
877   bool HasPackExpansions = false;
878   for (unsigned I = 0, N = NumElements; I != N; ++I) {
879     // Check the key.
880     ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
881                                                        KeyT);
882     if (Key.isInvalid())
883       return ExprError();
884 
885     // Check the value.
886     ExprResult Value
887       = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
888     if (Value.isInvalid())
889       return ExprError();
890 
891     Elements[I].Key = Key.get();
892     Elements[I].Value = Value.get();
893 
894     if (Elements[I].EllipsisLoc.isInvalid())
895       continue;
896 
897     if (!Elements[I].Key->containsUnexpandedParameterPack() &&
898         !Elements[I].Value->containsUnexpandedParameterPack()) {
899       Diag(Elements[I].EllipsisLoc,
900            diag::err_pack_expansion_without_parameter_packs)
901         << SourceRange(Elements[I].Key->getLocStart(),
902                        Elements[I].Value->getLocEnd());
903       return ExprError();
904     }
905 
906     HasPackExpansions = true;
907   }
908 
909 
910   QualType Ty
911     = Context.getObjCObjectPointerType(
912                                 Context.getObjCInterfaceType(NSDictionaryDecl));
913   return MaybeBindToTemporary(
914            ObjCDictionaryLiteral::Create(Context,
915                                          llvm::makeArrayRef(Elements,
916                                                             NumElements),
917                                          HasPackExpansions,
918                                          Ty,
919                                          DictionaryWithObjectsMethod, SR));
920 }
921 
922 ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
923                                       TypeSourceInfo *EncodedTypeInfo,
924                                       SourceLocation RParenLoc) {
925   QualType EncodedType = EncodedTypeInfo->getType();
926   QualType StrTy;
927   if (EncodedType->isDependentType())
928     StrTy = Context.DependentTy;
929   else {
930     if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
931         !EncodedType->isVoidType()) // void is handled too.
932       if (RequireCompleteType(AtLoc, EncodedType,
933                               diag::err_incomplete_type_objc_at_encode,
934                               EncodedTypeInfo->getTypeLoc()))
935         return ExprError();
936 
937     std::string Str;
938     Context.getObjCEncodingForType(EncodedType, Str);
939 
940     // The type of @encode is the same as the type of the corresponding string,
941     // which is an array type.
942     StrTy = Context.CharTy;
943     // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
944     if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
945       StrTy.addConst();
946     StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
947                                          ArrayType::Normal, 0);
948   }
949 
950   return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
951 }
952 
953 ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
954                                            SourceLocation EncodeLoc,
955                                            SourceLocation LParenLoc,
956                                            ParsedType ty,
957                                            SourceLocation RParenLoc) {
958   // FIXME: Preserve type source info ?
959   TypeSourceInfo *TInfo;
960   QualType EncodedType = GetTypeFromParser(ty, &TInfo);
961   if (!TInfo)
962     TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
963                                              PP.getLocForEndOfToken(LParenLoc));
964 
965   return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
966 }
967 
968 ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
969                                              SourceLocation AtLoc,
970                                              SourceLocation SelLoc,
971                                              SourceLocation LParenLoc,
972                                              SourceLocation RParenLoc) {
973   ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
974                              SourceRange(LParenLoc, RParenLoc), false, false);
975   if (!Method)
976     Method = LookupFactoryMethodInGlobalPool(Sel,
977                                           SourceRange(LParenLoc, RParenLoc));
978   if (!Method)
979     Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
980 
981   if (!Method ||
982       Method->getImplementationControl() != ObjCMethodDecl::Optional) {
983     llvm::DenseMap<Selector, SourceLocation>::iterator Pos
984       = ReferencedSelectors.find(Sel);
985     if (Pos == ReferencedSelectors.end())
986       ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
987   }
988 
989   // In ARC, forbid the user from using @selector for
990   // retain/release/autorelease/dealloc/retainCount.
991   if (getLangOpts().ObjCAutoRefCount) {
992     switch (Sel.getMethodFamily()) {
993     case OMF_retain:
994     case OMF_release:
995     case OMF_autorelease:
996     case OMF_retainCount:
997     case OMF_dealloc:
998       Diag(AtLoc, diag::err_arc_illegal_selector) <<
999         Sel << SourceRange(LParenLoc, RParenLoc);
1000       break;
1001 
1002     case OMF_None:
1003     case OMF_alloc:
1004     case OMF_copy:
1005     case OMF_finalize:
1006     case OMF_init:
1007     case OMF_mutableCopy:
1008     case OMF_new:
1009     case OMF_self:
1010     case OMF_performSelector:
1011       break;
1012     }
1013   }
1014   QualType Ty = Context.getObjCSelType();
1015   return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
1016 }
1017 
1018 ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1019                                              SourceLocation AtLoc,
1020                                              SourceLocation ProtoLoc,
1021                                              SourceLocation LParenLoc,
1022                                              SourceLocation ProtoIdLoc,
1023                                              SourceLocation RParenLoc) {
1024   ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
1025   if (!PDecl) {
1026     Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
1027     return true;
1028   }
1029 
1030   QualType Ty = Context.getObjCProtoType();
1031   if (Ty.isNull())
1032     return true;
1033   Ty = Context.getObjCObjectPointerType(Ty);
1034   return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
1035 }
1036 
1037 /// Try to capture an implicit reference to 'self'.
1038 ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1039   DeclContext *DC = getFunctionLevelDeclContext();
1040 
1041   // If we're not in an ObjC method, error out.  Note that, unlike the
1042   // C++ case, we don't require an instance method --- class methods
1043   // still have a 'self', and we really do still need to capture it!
1044   ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1045   if (!method)
1046     return 0;
1047 
1048   tryCaptureVariable(method->getSelfDecl(), Loc);
1049 
1050   return method;
1051 }
1052 
1053 static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1054   if (T == Context.getObjCInstanceType())
1055     return Context.getObjCIdType();
1056 
1057   return T;
1058 }
1059 
1060 QualType Sema::getMessageSendResultType(QualType ReceiverType,
1061                                         ObjCMethodDecl *Method,
1062                                     bool isClassMessage, bool isSuperMessage) {
1063   assert(Method && "Must have a method");
1064   if (!Method->hasRelatedResultType())
1065     return Method->getSendResultType();
1066 
1067   // If a method has a related return type:
1068   //   - if the method found is an instance method, but the message send
1069   //     was a class message send, T is the declared return type of the method
1070   //     found
1071   if (Method->isInstanceMethod() && isClassMessage)
1072     return stripObjCInstanceType(Context, Method->getSendResultType());
1073 
1074   //   - if the receiver is super, T is a pointer to the class of the
1075   //     enclosing method definition
1076   if (isSuperMessage) {
1077     if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
1078       if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
1079         return Context.getObjCObjectPointerType(
1080                                         Context.getObjCInterfaceType(Class));
1081   }
1082 
1083   //   - if the receiver is the name of a class U, T is a pointer to U
1084   if (ReceiverType->getAs<ObjCInterfaceType>() ||
1085       ReceiverType->isObjCQualifiedInterfaceType())
1086     return Context.getObjCObjectPointerType(ReceiverType);
1087   //   - if the receiver is of type Class or qualified Class type,
1088   //     T is the declared return type of the method.
1089   if (ReceiverType->isObjCClassType() ||
1090       ReceiverType->isObjCQualifiedClassType())
1091     return stripObjCInstanceType(Context, Method->getSendResultType());
1092 
1093   //   - if the receiver is id, qualified id, Class, or qualified Class, T
1094   //     is the receiver type, otherwise
1095   //   - T is the type of the receiver expression.
1096   return ReceiverType;
1097 }
1098 
1099 void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1100   E = E->IgnoreParenImpCasts();
1101   const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1102   if (!MsgSend)
1103     return;
1104 
1105   const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1106   if (!Method)
1107     return;
1108 
1109   if (!Method->hasRelatedResultType())
1110     return;
1111 
1112   if (Context.hasSameUnqualifiedType(Method->getResultType()
1113                                                         .getNonReferenceType(),
1114                                      MsgSend->getType()))
1115     return;
1116 
1117   if (!Context.hasSameUnqualifiedType(Method->getResultType(),
1118                                       Context.getObjCInstanceType()))
1119     return;
1120 
1121   Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1122     << Method->isInstanceMethod() << Method->getSelector()
1123     << MsgSend->getType();
1124 }
1125 
1126 bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
1127                                      Expr **Args, unsigned NumArgs,
1128                                      Selector Sel, ObjCMethodDecl *Method,
1129                                      bool isClassMessage, bool isSuperMessage,
1130                                      SourceLocation lbrac, SourceLocation rbrac,
1131                                      QualType &ReturnType, ExprValueKind &VK) {
1132   if (!Method) {
1133     // Apply default argument promotion as for (C99 6.5.2.2p6).
1134     for (unsigned i = 0; i != NumArgs; i++) {
1135       if (Args[i]->isTypeDependent())
1136         continue;
1137 
1138       ExprResult Result = DefaultArgumentPromotion(Args[i]);
1139       if (Result.isInvalid())
1140         return true;
1141       Args[i] = Result.take();
1142     }
1143 
1144     unsigned DiagID;
1145     if (getLangOpts().ObjCAutoRefCount)
1146       DiagID = diag::err_arc_method_not_found;
1147     else
1148       DiagID = isClassMessage ? diag::warn_class_method_not_found
1149                               : diag::warn_inst_method_not_found;
1150     if (!getLangOpts().DebuggerSupport)
1151       Diag(lbrac, DiagID)
1152         << Sel << isClassMessage << SourceRange(lbrac, rbrac);
1153 
1154     // In debuggers, we want to use __unknown_anytype for these
1155     // results so that clients can cast them.
1156     if (getLangOpts().DebuggerSupport) {
1157       ReturnType = Context.UnknownAnyTy;
1158     } else {
1159       ReturnType = Context.getObjCIdType();
1160     }
1161     VK = VK_RValue;
1162     return false;
1163   }
1164 
1165   ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1166                                         isSuperMessage);
1167   VK = Expr::getValueKindForType(Method->getResultType());
1168 
1169   unsigned NumNamedArgs = Sel.getNumArgs();
1170   // Method might have more arguments than selector indicates. This is due
1171   // to addition of c-style arguments in method.
1172   if (Method->param_size() > Sel.getNumArgs())
1173     NumNamedArgs = Method->param_size();
1174   // FIXME. This need be cleaned up.
1175   if (NumArgs < NumNamedArgs) {
1176     Diag(lbrac, diag::err_typecheck_call_too_few_args)
1177       << 2 << NumNamedArgs << NumArgs;
1178     return false;
1179   }
1180 
1181   bool IsError = false;
1182   for (unsigned i = 0; i < NumNamedArgs; i++) {
1183     // We can't do any type-checking on a type-dependent argument.
1184     if (Args[i]->isTypeDependent())
1185       continue;
1186 
1187     Expr *argExpr = Args[i];
1188 
1189     ParmVarDecl *param = Method->param_begin()[i];
1190     assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
1191 
1192     // Strip the unbridged-cast placeholder expression off unless it's
1193     // a consumed argument.
1194     if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1195         !param->hasAttr<CFConsumedAttr>())
1196       argExpr = stripARCUnbridgedCast(argExpr);
1197 
1198     if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
1199                             param->getType(),
1200                             diag::err_call_incomplete_argument, argExpr))
1201       return true;
1202 
1203     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1204                                                                       param);
1205     ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
1206     if (ArgE.isInvalid())
1207       IsError = true;
1208     else
1209       Args[i] = ArgE.takeAs<Expr>();
1210   }
1211 
1212   // Promote additional arguments to variadic methods.
1213   if (Method->isVariadic()) {
1214     for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
1215       if (Args[i]->isTypeDependent())
1216         continue;
1217 
1218       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
1219                                                         0);
1220       IsError |= Arg.isInvalid();
1221       Args[i] = Arg.take();
1222     }
1223   } else {
1224     // Check for extra arguments to non-variadic methods.
1225     if (NumArgs != NumNamedArgs) {
1226       Diag(Args[NumNamedArgs]->getLocStart(),
1227            diag::err_typecheck_call_too_many_args)
1228         << 2 /*method*/ << NumNamedArgs << NumArgs
1229         << Method->getSourceRange()
1230         << SourceRange(Args[NumNamedArgs]->getLocStart(),
1231                        Args[NumArgs-1]->getLocEnd());
1232     }
1233   }
1234 
1235   DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
1236 
1237   // Do additional checkings on method.
1238   IsError |= CheckObjCMethodCall(Method, lbrac, Args, NumArgs);
1239 
1240   return IsError;
1241 }
1242 
1243 bool Sema::isSelfExpr(Expr *receiver) {
1244   // 'self' is objc 'self' in an objc method only.
1245   ObjCMethodDecl *method =
1246     dyn_cast<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1247   if (!method) return false;
1248 
1249   receiver = receiver->IgnoreParenLValueCasts();
1250   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
1251     if (DRE->getDecl() == method->getSelfDecl())
1252       return true;
1253   return false;
1254 }
1255 
1256 /// LookupMethodInType - Look up a method in an ObjCObjectType.
1257 ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1258                                                bool isInstance) {
1259   const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1260   if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1261     // Look it up in the main interface (and categories, etc.)
1262     if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1263       return method;
1264 
1265     // Okay, look for "private" methods declared in any
1266     // @implementations we've seen.
1267     if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1268       return method;
1269   }
1270 
1271   // Check qualifiers.
1272   for (ObjCObjectType::qual_iterator
1273          i = objType->qual_begin(), e = objType->qual_end(); i != e; ++i)
1274     if (ObjCMethodDecl *method = (*i)->lookupMethod(sel, isInstance))
1275       return method;
1276 
1277   return 0;
1278 }
1279 
1280 /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1281 /// list of a qualified objective pointer type.
1282 ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1283                                               const ObjCObjectPointerType *OPT,
1284                                               bool Instance)
1285 {
1286   ObjCMethodDecl *MD = 0;
1287   for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1288        E = OPT->qual_end(); I != E; ++I) {
1289     ObjCProtocolDecl *PROTO = (*I);
1290     if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1291       return MD;
1292     }
1293   }
1294   return 0;
1295 }
1296 
1297 static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) {
1298   if (!Receiver)
1299     return;
1300 
1301   if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Receiver))
1302     Receiver = OVE->getSourceExpr();
1303 
1304   Expr *RExpr = Receiver->IgnoreParenImpCasts();
1305   SourceLocation Loc = RExpr->getLocStart();
1306   QualType T = RExpr->getType();
1307   ObjCPropertyDecl *PDecl = 0;
1308   ObjCMethodDecl *GDecl = 0;
1309   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) {
1310     RExpr = POE->getSyntacticForm();
1311     if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) {
1312       if (PRE->isImplicitProperty()) {
1313         GDecl = PRE->getImplicitPropertyGetter();
1314         if (GDecl) {
1315           T = GDecl->getResultType();
1316         }
1317       }
1318       else {
1319         PDecl = PRE->getExplicitProperty();
1320         if (PDecl) {
1321           T = PDecl->getType();
1322         }
1323       }
1324     }
1325   }
1326   else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RExpr)) {
1327     // See if receiver is a method which envokes a synthesized getter
1328     // backing a 'weak' property.
1329     ObjCMethodDecl *Method = ME->getMethodDecl();
1330     if (Method && Method->isSynthesized()) {
1331       Selector Sel = Method->getSelector();
1332       if (Sel.getNumArgs() == 0) {
1333         const DeclContext *Container = Method->getDeclContext();
1334         PDecl =
1335           S.LookupPropertyDecl(cast<ObjCContainerDecl>(Container),
1336                                Sel.getIdentifierInfoForSlot(0));
1337       }
1338       if (PDecl)
1339         T = PDecl->getType();
1340     }
1341   }
1342 
1343   if (T.getObjCLifetime() == Qualifiers::OCL_Weak) {
1344     S.Diag(Loc, diag::warn_receiver_is_weak)
1345       << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2));
1346     if (PDecl)
1347       S.Diag(PDecl->getLocation(), diag::note_property_declare);
1348     else if (GDecl)
1349       S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl;
1350     return;
1351   }
1352 
1353   if (PDecl &&
1354       (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)) {
1355     S.Diag(Loc, diag::warn_receiver_is_weak) << 1;
1356     S.Diag(PDecl->getLocation(), diag::note_property_declare);
1357   }
1358 }
1359 
1360 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1361 /// objective C interface.  This is a property reference expression.
1362 ExprResult Sema::
1363 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
1364                           Expr *BaseExpr, SourceLocation OpLoc,
1365                           DeclarationName MemberName,
1366                           SourceLocation MemberLoc,
1367                           SourceLocation SuperLoc, QualType SuperType,
1368                           bool Super) {
1369   const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1370   ObjCInterfaceDecl *IFace = IFaceT->getDecl();
1371 
1372   if (!MemberName.isIdentifier()) {
1373     Diag(MemberLoc, diag::err_invalid_property_name)
1374       << MemberName << QualType(OPT, 0);
1375     return ExprError();
1376   }
1377 
1378   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1379 
1380   SourceRange BaseRange = Super? SourceRange(SuperLoc)
1381                                : BaseExpr->getSourceRange();
1382   if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
1383                           diag::err_property_not_found_forward_class,
1384                           MemberName, BaseRange))
1385     return ExprError();
1386 
1387   // Search for a declared property first.
1388   if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
1389     // Check whether we can reference this property.
1390     if (DiagnoseUseOfDecl(PD, MemberLoc))
1391       return ExprError();
1392     if (Super)
1393       return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
1394                                                      VK_LValue, OK_ObjCProperty,
1395                                                      MemberLoc,
1396                                                      SuperLoc, SuperType));
1397     else
1398       return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
1399                                                      VK_LValue, OK_ObjCProperty,
1400                                                      MemberLoc, BaseExpr));
1401   }
1402   // Check protocols on qualified interfaces.
1403   for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1404        E = OPT->qual_end(); I != E; ++I)
1405     if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
1406       // Check whether we can reference this property.
1407       if (DiagnoseUseOfDecl(PD, MemberLoc))
1408         return ExprError();
1409 
1410       if (Super)
1411         return Owned(new (Context) ObjCPropertyRefExpr(PD,
1412                                                        Context.PseudoObjectTy,
1413                                                        VK_LValue,
1414                                                        OK_ObjCProperty,
1415                                                        MemberLoc,
1416                                                        SuperLoc, SuperType));
1417       else
1418         return Owned(new (Context) ObjCPropertyRefExpr(PD,
1419                                                        Context.PseudoObjectTy,
1420                                                        VK_LValue,
1421                                                        OK_ObjCProperty,
1422                                                        MemberLoc,
1423                                                        BaseExpr));
1424     }
1425   // If that failed, look for an "implicit" property by seeing if the nullary
1426   // selector is implemented.
1427 
1428   // FIXME: The logic for looking up nullary and unary selectors should be
1429   // shared with the code in ActOnInstanceMessage.
1430 
1431   Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1432   ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1433 
1434   // May be founf in property's qualified list.
1435   if (!Getter)
1436     Getter = LookupMethodInQualifiedType(Sel, OPT, true);
1437 
1438   // If this reference is in an @implementation, check for 'private' methods.
1439   if (!Getter)
1440     Getter = IFace->lookupPrivateMethod(Sel);
1441 
1442   if (Getter) {
1443     // Check if we can reference this property.
1444     if (DiagnoseUseOfDecl(Getter, MemberLoc))
1445       return ExprError();
1446   }
1447   // If we found a getter then this may be a valid dot-reference, we
1448   // will look for the matching setter, in case it is needed.
1449   Selector SetterSel =
1450     SelectorTable::constructSetterName(PP.getIdentifierTable(),
1451                                        PP.getSelectorTable(), Member);
1452   ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1453 
1454   // May be founf in property's qualified list.
1455   if (!Setter)
1456     Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1457 
1458   if (!Setter) {
1459     // If this reference is in an @implementation, also check for 'private'
1460     // methods.
1461     Setter = IFace->lookupPrivateMethod(SetterSel);
1462   }
1463 
1464   if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1465     return ExprError();
1466 
1467   if (Getter || Setter) {
1468     if (Super)
1469       return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1470                                                      Context.PseudoObjectTy,
1471                                                      VK_LValue, OK_ObjCProperty,
1472                                                      MemberLoc,
1473                                                      SuperLoc, SuperType));
1474     else
1475       return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1476                                                      Context.PseudoObjectTy,
1477                                                      VK_LValue, OK_ObjCProperty,
1478                                                      MemberLoc, BaseExpr));
1479 
1480   }
1481 
1482   // Attempt to correct for typos in property names.
1483   DeclFilterCCC<ObjCPropertyDecl> Validator;
1484   if (TypoCorrection Corrected = CorrectTypo(
1485       DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
1486       NULL, Validator, IFace, false, OPT)) {
1487     ObjCPropertyDecl *Property =
1488         Corrected.getCorrectionDeclAs<ObjCPropertyDecl>();
1489     DeclarationName TypoResult = Corrected.getCorrection();
1490     Diag(MemberLoc, diag::err_property_not_found_suggest)
1491       << MemberName << QualType(OPT, 0) << TypoResult
1492       << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
1493     Diag(Property->getLocation(), diag::note_previous_decl)
1494       << Property->getDeclName();
1495     return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1496                                      TypoResult, MemberLoc,
1497                                      SuperLoc, SuperType, Super);
1498   }
1499   ObjCInterfaceDecl *ClassDeclared;
1500   if (ObjCIvarDecl *Ivar =
1501       IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1502     QualType T = Ivar->getType();
1503     if (const ObjCObjectPointerType * OBJPT =
1504         T->getAsObjCInterfacePointerType()) {
1505       if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
1506                               diag::err_property_not_as_forward_class,
1507                               MemberName, BaseExpr))
1508         return ExprError();
1509     }
1510     Diag(MemberLoc,
1511          diag::err_ivar_access_using_property_syntax_suggest)
1512     << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1513     << FixItHint::CreateReplacement(OpLoc, "->");
1514     return ExprError();
1515   }
1516 
1517   Diag(MemberLoc, diag::err_property_not_found)
1518     << MemberName << QualType(OPT, 0);
1519   if (Setter)
1520     Diag(Setter->getLocation(), diag::note_getter_unavailable)
1521           << MemberName << BaseExpr->getSourceRange();
1522   return ExprError();
1523 }
1524 
1525 
1526 
1527 ExprResult Sema::
1528 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1529                           IdentifierInfo &propertyName,
1530                           SourceLocation receiverNameLoc,
1531                           SourceLocation propertyNameLoc) {
1532 
1533   IdentifierInfo *receiverNamePtr = &receiverName;
1534   ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1535                                                   receiverNameLoc);
1536 
1537   bool IsSuper = false;
1538   if (IFace == 0) {
1539     // If the "receiver" is 'super' in a method, handle it as an expression-like
1540     // property reference.
1541     if (receiverNamePtr->isStr("super")) {
1542       IsSuper = true;
1543 
1544       if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
1545         if (CurMethod->isInstanceMethod()) {
1546           QualType T =
1547             Context.getObjCInterfaceType(CurMethod->getClassInterface());
1548           T = Context.getObjCObjectPointerType(T);
1549 
1550           return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
1551                                            /*BaseExpr*/0,
1552                                            SourceLocation()/*OpLoc*/,
1553                                            &propertyName,
1554                                            propertyNameLoc,
1555                                            receiverNameLoc, T, true);
1556         }
1557 
1558         // Otherwise, if this is a class method, try dispatching to our
1559         // superclass.
1560         IFace = CurMethod->getClassInterface()->getSuperClass();
1561       }
1562     }
1563 
1564     if (IFace == 0) {
1565       Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
1566       return ExprError();
1567     }
1568   }
1569 
1570   // Search for a declared property first.
1571   Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
1572   ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
1573 
1574   // If this reference is in an @implementation, check for 'private' methods.
1575   if (!Getter)
1576     if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1577       if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1578         if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
1579           Getter = ImpDecl->getClassMethod(Sel);
1580 
1581   if (Getter) {
1582     // FIXME: refactor/share with ActOnMemberReference().
1583     // Check if we can reference this property.
1584     if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1585       return ExprError();
1586   }
1587 
1588   // Look for the matching setter, in case it is needed.
1589   Selector SetterSel =
1590     SelectorTable::constructSetterName(PP.getIdentifierTable(),
1591                                        PP.getSelectorTable(), &propertyName);
1592 
1593   ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1594   if (!Setter) {
1595     // If this reference is in an @implementation, also check for 'private'
1596     // methods.
1597     if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1598       if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1599         if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
1600           Setter = ImpDecl->getClassMethod(SetterSel);
1601   }
1602   // Look through local category implementations associated with the class.
1603   if (!Setter)
1604     Setter = IFace->getCategoryClassMethod(SetterSel);
1605 
1606   if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1607     return ExprError();
1608 
1609   if (Getter || Setter) {
1610     if (IsSuper)
1611     return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1612                                                    Context.PseudoObjectTy,
1613                                                    VK_LValue, OK_ObjCProperty,
1614                                                    propertyNameLoc,
1615                                                    receiverNameLoc,
1616                                           Context.getObjCInterfaceType(IFace)));
1617 
1618     return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1619                                                    Context.PseudoObjectTy,
1620                                                    VK_LValue, OK_ObjCProperty,
1621                                                    propertyNameLoc,
1622                                                    receiverNameLoc, IFace));
1623   }
1624   return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1625                      << &propertyName << Context.getObjCInterfaceType(IFace));
1626 }
1627 
1628 namespace {
1629 
1630 class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1631  public:
1632   ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1633     // Determine whether "super" is acceptable in the current context.
1634     if (Method && Method->getClassInterface())
1635       WantObjCSuper = Method->getClassInterface()->getSuperClass();
1636   }
1637 
1638   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1639     return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1640         candidate.isKeyword("super");
1641   }
1642 };
1643 
1644 }
1645 
1646 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
1647                                                IdentifierInfo *Name,
1648                                                SourceLocation NameLoc,
1649                                                bool IsSuper,
1650                                                bool HasTrailingDot,
1651                                                ParsedType &ReceiverType) {
1652   ReceiverType = ParsedType();
1653 
1654   // If the identifier is "super" and there is no trailing dot, we're
1655   // messaging super. If the identifier is "super" and there is a
1656   // trailing dot, it's an instance message.
1657   if (IsSuper && S->isInObjcMethodScope())
1658     return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
1659 
1660   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1661   LookupName(Result, S);
1662 
1663   switch (Result.getResultKind()) {
1664   case LookupResult::NotFound:
1665     // Normal name lookup didn't find anything. If we're in an
1666     // Objective-C method, look for ivars. If we find one, we're done!
1667     // FIXME: This is a hack. Ivar lookup should be part of normal
1668     // lookup.
1669     if (ObjCMethodDecl *Method = getCurMethodDecl()) {
1670       if (!Method->getClassInterface()) {
1671         // Fall back: let the parser try to parse it as an instance message.
1672         return ObjCInstanceMessage;
1673       }
1674 
1675       ObjCInterfaceDecl *ClassDeclared;
1676       if (Method->getClassInterface()->lookupInstanceVariable(Name,
1677                                                               ClassDeclared))
1678         return ObjCInstanceMessage;
1679     }
1680 
1681     // Break out; we'll perform typo correction below.
1682     break;
1683 
1684   case LookupResult::NotFoundInCurrentInstantiation:
1685   case LookupResult::FoundOverloaded:
1686   case LookupResult::FoundUnresolvedValue:
1687   case LookupResult::Ambiguous:
1688     Result.suppressDiagnostics();
1689     return ObjCInstanceMessage;
1690 
1691   case LookupResult::Found: {
1692     // If the identifier is a class or not, and there is a trailing dot,
1693     // it's an instance message.
1694     if (HasTrailingDot)
1695       return ObjCInstanceMessage;
1696     // We found something. If it's a type, then we have a class
1697     // message. Otherwise, it's an instance message.
1698     NamedDecl *ND = Result.getFoundDecl();
1699     QualType T;
1700     if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1701       T = Context.getObjCInterfaceType(Class);
1702     else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
1703       T = Context.getTypeDeclType(Type);
1704     else
1705       return ObjCInstanceMessage;
1706 
1707     //  We have a class message, and T is the type we're
1708     //  messaging. Build source-location information for it.
1709     TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1710     ReceiverType = CreateParsedType(T, TSInfo);
1711     return ObjCClassMessage;
1712   }
1713   }
1714 
1715   ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
1716   if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
1717                                              Result.getLookupKind(), S, NULL,
1718                                              Validator)) {
1719     if (Corrected.isKeyword()) {
1720       // If we've found the keyword "super" (the only keyword that would be
1721       // returned by CorrectTypo), this is a send to super.
1722       Diag(NameLoc, diag::err_unknown_receiver_suggest)
1723         << Name << Corrected.getCorrection()
1724         << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
1725       return ObjCSuperMessage;
1726     } else if (ObjCInterfaceDecl *Class =
1727                Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1728       // If we found a declaration, correct when it refers to an Objective-C
1729       // class.
1730       Diag(NameLoc, diag::err_unknown_receiver_suggest)
1731         << Name << Corrected.getCorrection()
1732         << FixItHint::CreateReplacement(SourceRange(NameLoc),
1733                                         Class->getNameAsString());
1734       Diag(Class->getLocation(), diag::note_previous_decl)
1735         << Corrected.getCorrection();
1736 
1737       QualType T = Context.getObjCInterfaceType(Class);
1738       TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1739       ReceiverType = CreateParsedType(T, TSInfo);
1740       return ObjCClassMessage;
1741     }
1742   }
1743 
1744   // Fall back: let the parser try to parse it as an instance message.
1745   return ObjCInstanceMessage;
1746 }
1747 
1748 ExprResult Sema::ActOnSuperMessage(Scope *S,
1749                                    SourceLocation SuperLoc,
1750                                    Selector Sel,
1751                                    SourceLocation LBracLoc,
1752                                    ArrayRef<SourceLocation> SelectorLocs,
1753                                    SourceLocation RBracLoc,
1754                                    MultiExprArg Args) {
1755   // Determine whether we are inside a method or not.
1756   ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
1757   if (!Method) {
1758     Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1759     return ExprError();
1760   }
1761 
1762   ObjCInterfaceDecl *Class = Method->getClassInterface();
1763   if (!Class) {
1764     Diag(SuperLoc, diag::error_no_super_class_message)
1765       << Method->getDeclName();
1766     return ExprError();
1767   }
1768 
1769   ObjCInterfaceDecl *Super = Class->getSuperClass();
1770   if (!Super) {
1771     // The current class does not have a superclass.
1772     Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1773       << Class->getIdentifier();
1774     return ExprError();
1775   }
1776 
1777   // We are in a method whose class has a superclass, so 'super'
1778   // is acting as a keyword.
1779   if (Method->isInstanceMethod()) {
1780     if (Sel.getMethodFamily() == OMF_dealloc)
1781       getCurFunction()->ObjCShouldCallSuperDealloc = false;
1782     if (Sel.getMethodFamily() == OMF_finalize)
1783       getCurFunction()->ObjCShouldCallSuperFinalize = false;
1784 
1785     // Since we are in an instance method, this is an instance
1786     // message to the superclass instance.
1787     QualType SuperTy = Context.getObjCInterfaceType(Super);
1788     SuperTy = Context.getObjCObjectPointerType(SuperTy);
1789     return BuildInstanceMessage(0, SuperTy, SuperLoc,
1790                                 Sel, /*Method=*/0,
1791                                 LBracLoc, SelectorLocs, RBracLoc, move(Args));
1792   }
1793 
1794   // Since we are in a class method, this is a class message to
1795   // the superclass.
1796   return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1797                            Context.getObjCInterfaceType(Super),
1798                            SuperLoc, Sel, /*Method=*/0,
1799                            LBracLoc, SelectorLocs, RBracLoc, move(Args));
1800 }
1801 
1802 
1803 ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
1804                                            bool isSuperReceiver,
1805                                            SourceLocation Loc,
1806                                            Selector Sel,
1807                                            ObjCMethodDecl *Method,
1808                                            MultiExprArg Args) {
1809   TypeSourceInfo *receiverTypeInfo = 0;
1810   if (!ReceiverType.isNull())
1811     receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
1812 
1813   return BuildClassMessage(receiverTypeInfo, ReceiverType,
1814                           /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
1815                            Sel, Method, Loc, Loc, Loc, Args,
1816                            /*isImplicit=*/true);
1817 
1818 }
1819 
1820 static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
1821                                unsigned DiagID,
1822                                bool (*refactor)(const ObjCMessageExpr *,
1823                                               const NSAPI &, edit::Commit &)) {
1824   SourceLocation MsgLoc = Msg->getExprLoc();
1825   if (S.Diags.getDiagnosticLevel(DiagID, MsgLoc) == DiagnosticsEngine::Ignored)
1826     return;
1827 
1828   SourceManager &SM = S.SourceMgr;
1829   edit::Commit ECommit(SM, S.LangOpts);
1830   if (refactor(Msg,*S.NSAPIObj, ECommit)) {
1831     DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
1832                         << Msg->getSelector() << Msg->getSourceRange();
1833     // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
1834     if (!ECommit.isCommitable())
1835       return;
1836     for (edit::Commit::edit_iterator
1837            I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
1838       const edit::Commit::Edit &Edit = *I;
1839       switch (Edit.Kind) {
1840       case edit::Commit::Act_Insert:
1841         Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
1842                                                         Edit.Text,
1843                                                         Edit.BeforePrev));
1844         break;
1845       case edit::Commit::Act_InsertFromRange:
1846         Builder.AddFixItHint(
1847             FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
1848                                                 Edit.getInsertFromRange(SM),
1849                                                 Edit.BeforePrev));
1850         break;
1851       case edit::Commit::Act_Remove:
1852         Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
1853         break;
1854       }
1855     }
1856   }
1857 }
1858 
1859 static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
1860   applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
1861                      edit::rewriteObjCRedundantCallWithLiteral);
1862 }
1863 
1864 /// \brief Build an Objective-C class message expression.
1865 ///
1866 /// This routine takes care of both normal class messages and
1867 /// class messages to the superclass.
1868 ///
1869 /// \param ReceiverTypeInfo Type source information that describes the
1870 /// receiver of this message. This may be NULL, in which case we are
1871 /// sending to the superclass and \p SuperLoc must be a valid source
1872 /// location.
1873 
1874 /// \param ReceiverType The type of the object receiving the
1875 /// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1876 /// type as that refers to. For a superclass send, this is the type of
1877 /// the superclass.
1878 ///
1879 /// \param SuperLoc The location of the "super" keyword in a
1880 /// superclass message.
1881 ///
1882 /// \param Sel The selector to which the message is being sent.
1883 ///
1884 /// \param Method The method that this class message is invoking, if
1885 /// already known.
1886 ///
1887 /// \param LBracLoc The location of the opening square bracket ']'.
1888 ///
1889 /// \param RBracLoc The location of the closing square bracket ']'.
1890 ///
1891 /// \param ArgsIn The message arguments.
1892 ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
1893                                    QualType ReceiverType,
1894                                    SourceLocation SuperLoc,
1895                                    Selector Sel,
1896                                    ObjCMethodDecl *Method,
1897                                    SourceLocation LBracLoc,
1898                                    ArrayRef<SourceLocation> SelectorLocs,
1899                                    SourceLocation RBracLoc,
1900                                    MultiExprArg ArgsIn,
1901                                    bool isImplicit) {
1902   SourceLocation Loc = SuperLoc.isValid()? SuperLoc
1903     : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
1904   if (LBracLoc.isInvalid()) {
1905     Diag(Loc, diag::err_missing_open_square_message_send)
1906       << FixItHint::CreateInsertion(Loc, "[");
1907     LBracLoc = Loc;
1908   }
1909 
1910   if (ReceiverType->isDependentType()) {
1911     // If the receiver type is dependent, we can't type-check anything
1912     // at this point. Build a dependent expression.
1913     unsigned NumArgs = ArgsIn.size();
1914     Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1915     assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1916     return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1917                                          VK_RValue, LBracLoc, ReceiverTypeInfo,
1918                                          Sel, SelectorLocs, /*Method=*/0,
1919                                          makeArrayRef(Args, NumArgs),RBracLoc,
1920                                          isImplicit));
1921   }
1922 
1923   // Find the class to which we are sending this message.
1924   ObjCInterfaceDecl *Class = 0;
1925   const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1926   if (!ClassType || !(Class = ClassType->getInterface())) {
1927     Diag(Loc, diag::err_invalid_receiver_class_message)
1928       << ReceiverType;
1929     return ExprError();
1930   }
1931   assert(Class && "We don't know which class we're messaging?");
1932   // objc++ diagnoses during typename annotation.
1933   if (!getLangOpts().CPlusPlus)
1934     (void)DiagnoseUseOfDecl(Class, Loc);
1935   // Find the method we are messaging.
1936   if (!Method) {
1937     SourceRange TypeRange
1938       = SuperLoc.isValid()? SourceRange(SuperLoc)
1939                           : ReceiverTypeInfo->getTypeLoc().getSourceRange();
1940     if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
1941                             (getLangOpts().ObjCAutoRefCount
1942                                ? diag::err_arc_receiver_forward_class
1943                                : diag::warn_receiver_forward_class),
1944                             TypeRange)) {
1945       // A forward class used in messaging is treated as a 'Class'
1946       Method = LookupFactoryMethodInGlobalPool(Sel,
1947                                                SourceRange(LBracLoc, RBracLoc));
1948       if (Method && !getLangOpts().ObjCAutoRefCount)
1949         Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1950           << Method->getDeclName();
1951     }
1952     if (!Method)
1953       Method = Class->lookupClassMethod(Sel);
1954 
1955     // If we have an implementation in scope, check "private" methods.
1956     if (!Method)
1957       Method = Class->lookupPrivateClassMethod(Sel);
1958 
1959     if (Method && DiagnoseUseOfDecl(Method, Loc))
1960       return ExprError();
1961   }
1962 
1963   // Check the argument types and determine the result type.
1964   QualType ReturnType;
1965   ExprValueKind VK = VK_RValue;
1966 
1967   unsigned NumArgs = ArgsIn.size();
1968   Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1969   if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1970                                 SuperLoc.isValid(), LBracLoc, RBracLoc,
1971                                 ReturnType, VK))
1972     return ExprError();
1973 
1974   if (Method && !Method->getResultType()->isVoidType() &&
1975       RequireCompleteType(LBracLoc, Method->getResultType(),
1976                           diag::err_illegal_message_expr_incomplete_type))
1977     return ExprError();
1978 
1979   // Construct the appropriate ObjCMessageExpr.
1980   ObjCMessageExpr *Result;
1981   if (SuperLoc.isValid())
1982     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
1983                                      SuperLoc, /*IsInstanceSuper=*/false,
1984                                      ReceiverType, Sel, SelectorLocs,
1985                                      Method, makeArrayRef(Args, NumArgs),
1986                                      RBracLoc, isImplicit);
1987   else {
1988     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
1989                                      ReceiverTypeInfo, Sel, SelectorLocs,
1990                                      Method, makeArrayRef(Args, NumArgs),
1991                                      RBracLoc, isImplicit);
1992     if (!isImplicit)
1993       checkCocoaAPI(*this, Result);
1994   }
1995   return MaybeBindToTemporary(Result);
1996 }
1997 
1998 // ActOnClassMessage - used for both unary and keyword messages.
1999 // ArgExprs is optional - if it is present, the number of expressions
2000 // is obtained from Sel.getNumArgs().
2001 ExprResult Sema::ActOnClassMessage(Scope *S,
2002                                    ParsedType Receiver,
2003                                    Selector Sel,
2004                                    SourceLocation LBracLoc,
2005                                    ArrayRef<SourceLocation> SelectorLocs,
2006                                    SourceLocation RBracLoc,
2007                                    MultiExprArg Args) {
2008   TypeSourceInfo *ReceiverTypeInfo;
2009   QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2010   if (ReceiverType.isNull())
2011     return ExprError();
2012 
2013 
2014   if (!ReceiverTypeInfo)
2015     ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2016 
2017   return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
2018                            /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
2019                            LBracLoc, SelectorLocs, RBracLoc, move(Args));
2020 }
2021 
2022 ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2023                                               QualType ReceiverType,
2024                                               SourceLocation Loc,
2025                                               Selector Sel,
2026                                               ObjCMethodDecl *Method,
2027                                               MultiExprArg Args) {
2028   return BuildInstanceMessage(Receiver, ReceiverType,
2029                               /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2030                               Sel, Method, Loc, Loc, Loc, Args,
2031                               /*isImplicit=*/true);
2032 }
2033 
2034 /// \brief Build an Objective-C instance message expression.
2035 ///
2036 /// This routine takes care of both normal instance messages and
2037 /// instance messages to the superclass instance.
2038 ///
2039 /// \param Receiver The expression that computes the object that will
2040 /// receive this message. This may be empty, in which case we are
2041 /// sending to the superclass instance and \p SuperLoc must be a valid
2042 /// source location.
2043 ///
2044 /// \param ReceiverType The (static) type of the object receiving the
2045 /// message. When a \p Receiver expression is provided, this is the
2046 /// same type as that expression. For a superclass instance send, this
2047 /// is a pointer to the type of the superclass.
2048 ///
2049 /// \param SuperLoc The location of the "super" keyword in a
2050 /// superclass instance message.
2051 ///
2052 /// \param Sel The selector to which the message is being sent.
2053 ///
2054 /// \param Method The method that this instance message is invoking, if
2055 /// already known.
2056 ///
2057 /// \param LBracLoc The location of the opening square bracket ']'.
2058 ///
2059 /// \param RBracLoc The location of the closing square bracket ']'.
2060 ///
2061 /// \param ArgsIn The message arguments.
2062 ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
2063                                       QualType ReceiverType,
2064                                       SourceLocation SuperLoc,
2065                                       Selector Sel,
2066                                       ObjCMethodDecl *Method,
2067                                       SourceLocation LBracLoc,
2068                                       ArrayRef<SourceLocation> SelectorLocs,
2069                                       SourceLocation RBracLoc,
2070                                       MultiExprArg ArgsIn,
2071                                       bool isImplicit) {
2072   // The location of the receiver.
2073   SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
2074 
2075   if (LBracLoc.isInvalid()) {
2076     Diag(Loc, diag::err_missing_open_square_message_send)
2077       << FixItHint::CreateInsertion(Loc, "[");
2078     LBracLoc = Loc;
2079   }
2080 
2081   // If we have a receiver expression, perform appropriate promotions
2082   // and determine receiver type.
2083   if (Receiver) {
2084     if (Receiver->hasPlaceholderType()) {
2085       ExprResult Result;
2086       if (Receiver->getType() == Context.UnknownAnyTy)
2087         Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2088       else
2089         Result = CheckPlaceholderExpr(Receiver);
2090       if (Result.isInvalid()) return ExprError();
2091       Receiver = Result.take();
2092     }
2093 
2094     if (Receiver->isTypeDependent()) {
2095       // If the receiver is type-dependent, we can't type-check anything
2096       // at this point. Build a dependent expression.
2097       unsigned NumArgs = ArgsIn.size();
2098       Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
2099       assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2100       return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
2101                                            VK_RValue, LBracLoc, Receiver, Sel,
2102                                            SelectorLocs, /*Method=*/0,
2103                                            makeArrayRef(Args, NumArgs),
2104                                            RBracLoc, isImplicit));
2105     }
2106 
2107     // If necessary, apply function/array conversion to the receiver.
2108     // C99 6.7.5.3p[7,8].
2109     ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2110     if (Result.isInvalid())
2111       return ExprError();
2112     Receiver = Result.take();
2113     ReceiverType = Receiver->getType();
2114   }
2115 
2116   if (!Method) {
2117     // Handle messages to id.
2118     bool receiverIsId = ReceiverType->isObjCIdType();
2119     if (receiverIsId || ReceiverType->isBlockPointerType() ||
2120         (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2121       Method = LookupInstanceMethodInGlobalPool(Sel,
2122                                                 SourceRange(LBracLoc, RBracLoc),
2123                                                 receiverIsId);
2124       if (!Method)
2125         Method = LookupFactoryMethodInGlobalPool(Sel,
2126                                                  SourceRange(LBracLoc,RBracLoc),
2127                                                  receiverIsId);
2128     } else if (ReceiverType->isObjCClassType() ||
2129                ReceiverType->isObjCQualifiedClassType()) {
2130       // Handle messages to Class.
2131       // We allow sending a message to a qualified Class ("Class<foo>"), which
2132       // is ok as long as one of the protocols implements the selector (if not, warn).
2133       if (const ObjCObjectPointerType *QClassTy
2134             = ReceiverType->getAsObjCQualifiedClassType()) {
2135         // Search protocols for class methods.
2136         Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2137         if (!Method) {
2138           Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2139           // warn if instance method found for a Class message.
2140           if (Method) {
2141             Diag(Loc, diag::warn_instance_method_on_class_found)
2142               << Method->getSelector() << Sel;
2143             Diag(Method->getLocation(), diag::note_method_declared_at)
2144               << Method->getDeclName();
2145           }
2146         }
2147       } else {
2148         if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2149           if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2150             // First check the public methods in the class interface.
2151             Method = ClassDecl->lookupClassMethod(Sel);
2152 
2153             if (!Method)
2154               Method = ClassDecl->lookupPrivateClassMethod(Sel);
2155           }
2156           if (Method && DiagnoseUseOfDecl(Method, Loc))
2157             return ExprError();
2158         }
2159         if (!Method) {
2160           // If not messaging 'self', look for any factory method named 'Sel'.
2161           if (!Receiver || !isSelfExpr(Receiver)) {
2162             Method = LookupFactoryMethodInGlobalPool(Sel,
2163                                                 SourceRange(LBracLoc, RBracLoc),
2164                                                      true);
2165             if (!Method) {
2166               // If no class (factory) method was found, check if an _instance_
2167               // method of the same name exists in the root class only.
2168               Method = LookupInstanceMethodInGlobalPool(Sel,
2169                                                SourceRange(LBracLoc, RBracLoc),
2170                                                         true);
2171               if (Method)
2172                   if (const ObjCInterfaceDecl *ID =
2173                       dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2174                     if (ID->getSuperClass())
2175                       Diag(Loc, diag::warn_root_inst_method_not_found)
2176                       << Sel << SourceRange(LBracLoc, RBracLoc);
2177                   }
2178             }
2179           }
2180         }
2181       }
2182     } else {
2183       ObjCInterfaceDecl* ClassDecl = 0;
2184 
2185       // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2186       // long as one of the protocols implements the selector (if not, warn).
2187       // And as long as message is not deprecated/unavailable (warn if it is).
2188       if (const ObjCObjectPointerType *QIdTy
2189                                    = ReceiverType->getAsObjCQualifiedIdType()) {
2190         // Search protocols for instance methods.
2191         Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2192         if (!Method)
2193           Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
2194         if (Method && DiagnoseUseOfDecl(Method, Loc))
2195           return ExprError();
2196       } else if (const ObjCObjectPointerType *OCIType
2197                    = ReceiverType->getAsObjCInterfacePointerType()) {
2198         // We allow sending a message to a pointer to an interface (an object).
2199         ClassDecl = OCIType->getInterfaceDecl();
2200 
2201         // Try to complete the type. Under ARC, this is a hard error from which
2202         // we don't try to recover.
2203         const ObjCInterfaceDecl *forwardClass = 0;
2204         if (RequireCompleteType(Loc, OCIType->getPointeeType(),
2205               getLangOpts().ObjCAutoRefCount
2206                 ? diag::err_arc_receiver_forward_instance
2207                 : diag::warn_receiver_forward_instance,
2208                                 Receiver? Receiver->getSourceRange()
2209                                         : SourceRange(SuperLoc))) {
2210           if (getLangOpts().ObjCAutoRefCount)
2211             return ExprError();
2212 
2213           forwardClass = OCIType->getInterfaceDecl();
2214           Diag(Receiver ? Receiver->getLocStart()
2215                         : SuperLoc, diag::note_receiver_is_id);
2216           Method = 0;
2217         } else {
2218           Method = ClassDecl->lookupInstanceMethod(Sel);
2219         }
2220 
2221         if (!Method)
2222           // Search protocol qualifiers.
2223           Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2224 
2225         if (!Method) {
2226           // If we have implementations in scope, check "private" methods.
2227           Method = ClassDecl->lookupPrivateMethod(Sel);
2228 
2229           if (!Method && getLangOpts().ObjCAutoRefCount) {
2230             Diag(Loc, diag::err_arc_may_not_respond)
2231               << OCIType->getPointeeType() << Sel;
2232             return ExprError();
2233           }
2234 
2235           if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
2236             // If we still haven't found a method, look in the global pool. This
2237             // behavior isn't very desirable, however we need it for GCC
2238             // compatibility. FIXME: should we deviate??
2239             if (OCIType->qual_empty()) {
2240               Method = LookupInstanceMethodInGlobalPool(Sel,
2241                                               SourceRange(LBracLoc, RBracLoc));
2242               if (Method && !forwardClass)
2243                 Diag(Loc, diag::warn_maynot_respond)
2244                   << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
2245             }
2246           }
2247         }
2248         if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
2249           return ExprError();
2250       } else if (!getLangOpts().ObjCAutoRefCount &&
2251                  !Context.getObjCIdType().isNull() &&
2252                  (ReceiverType->isPointerType() ||
2253                   ReceiverType->isIntegerType())) {
2254         // Implicitly convert integers and pointers to 'id' but emit a warning.
2255         // But not in ARC.
2256         Diag(Loc, diag::warn_bad_receiver_type)
2257           << ReceiverType
2258           << Receiver->getSourceRange();
2259         if (ReceiverType->isPointerType())
2260           Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2261                             CK_CPointerToObjCPointerCast).take();
2262         else {
2263           // TODO: specialized warning on null receivers?
2264           bool IsNull = Receiver->isNullPointerConstant(Context,
2265                                               Expr::NPC_ValueDependentIsNull);
2266           CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2267           Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2268                                        Kind).take();
2269         }
2270         ReceiverType = Receiver->getType();
2271       } else {
2272         ExprResult ReceiverRes;
2273         if (getLangOpts().CPlusPlus)
2274           ReceiverRes = PerformContextuallyConvertToObjCPointer(Receiver);
2275         if (ReceiverRes.isUsable()) {
2276           Receiver = ReceiverRes.take();
2277           return BuildInstanceMessage(Receiver,
2278                                       ReceiverType,
2279                                       SuperLoc,
2280                                       Sel,
2281                                       Method,
2282                                       LBracLoc,
2283                                       SelectorLocs,
2284                                       RBracLoc,
2285                                       move(ArgsIn));
2286         } else {
2287           // Reject other random receiver types (e.g. structs).
2288           Diag(Loc, diag::err_bad_receiver_type)
2289             << ReceiverType << Receiver->getSourceRange();
2290           return ExprError();
2291         }
2292       }
2293     }
2294   }
2295 
2296   // Check the message arguments.
2297   unsigned NumArgs = ArgsIn.size();
2298   Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
2299   QualType ReturnType;
2300   ExprValueKind VK = VK_RValue;
2301   bool ClassMessage = (ReceiverType->isObjCClassType() ||
2302                        ReceiverType->isObjCQualifiedClassType());
2303   if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
2304                                 ClassMessage, SuperLoc.isValid(),
2305                                 LBracLoc, RBracLoc, ReturnType, VK))
2306     return ExprError();
2307 
2308   if (Method && !Method->getResultType()->isVoidType() &&
2309       RequireCompleteType(LBracLoc, Method->getResultType(),
2310                           diag::err_illegal_message_expr_incomplete_type))
2311     return ExprError();
2312 
2313   SourceLocation SelLoc = SelectorLocs.front();
2314 
2315   // In ARC, forbid the user from sending messages to
2316   // retain/release/autorelease/dealloc/retainCount explicitly.
2317   if (getLangOpts().ObjCAutoRefCount) {
2318     ObjCMethodFamily family =
2319       (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2320     switch (family) {
2321     case OMF_init:
2322       if (Method)
2323         checkInitMethod(Method, ReceiverType);
2324 
2325     case OMF_None:
2326     case OMF_alloc:
2327     case OMF_copy:
2328     case OMF_finalize:
2329     case OMF_mutableCopy:
2330     case OMF_new:
2331     case OMF_self:
2332       break;
2333 
2334     case OMF_dealloc:
2335     case OMF_retain:
2336     case OMF_release:
2337     case OMF_autorelease:
2338     case OMF_retainCount:
2339       Diag(Loc, diag::err_arc_illegal_explicit_message)
2340         << Sel << SelLoc;
2341       break;
2342 
2343     case OMF_performSelector:
2344       if (Method && NumArgs >= 1) {
2345         if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2346           Selector ArgSel = SelExp->getSelector();
2347           ObjCMethodDecl *SelMethod =
2348             LookupInstanceMethodInGlobalPool(ArgSel,
2349                                              SelExp->getSourceRange());
2350           if (!SelMethod)
2351             SelMethod =
2352               LookupFactoryMethodInGlobalPool(ArgSel,
2353                                               SelExp->getSourceRange());
2354           if (SelMethod) {
2355             ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2356             switch (SelFamily) {
2357               case OMF_alloc:
2358               case OMF_copy:
2359               case OMF_mutableCopy:
2360               case OMF_new:
2361               case OMF_self:
2362               case OMF_init:
2363                 // Issue error, unless ns_returns_not_retained.
2364                 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2365                   // selector names a +1 method
2366                   Diag(SelLoc,
2367                        diag::err_arc_perform_selector_retains);
2368                   Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2369                     << SelMethod->getDeclName();
2370                 }
2371                 break;
2372               default:
2373                 // +0 call. OK. unless ns_returns_retained.
2374                 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2375                   // selector names a +1 method
2376                   Diag(SelLoc,
2377                        diag::err_arc_perform_selector_retains);
2378                   Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2379                     << SelMethod->getDeclName();
2380                 }
2381                 break;
2382             }
2383           }
2384         } else {
2385           // error (may leak).
2386           Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
2387           Diag(Args[0]->getExprLoc(), diag::note_used_here);
2388         }
2389       }
2390       break;
2391     }
2392   }
2393 
2394   // Construct the appropriate ObjCMessageExpr instance.
2395   ObjCMessageExpr *Result;
2396   if (SuperLoc.isValid())
2397     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2398                                      SuperLoc,  /*IsInstanceSuper=*/true,
2399                                      ReceiverType, Sel, SelectorLocs, Method,
2400                                      makeArrayRef(Args, NumArgs), RBracLoc,
2401                                      isImplicit);
2402   else {
2403     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2404                                      Receiver, Sel, SelectorLocs, Method,
2405                                      makeArrayRef(Args, NumArgs), RBracLoc,
2406                                      isImplicit);
2407     if (!isImplicit)
2408       checkCocoaAPI(*this, Result);
2409   }
2410 
2411   if (getLangOpts().ObjCAutoRefCount) {
2412     DiagnoseARCUseOfWeakReceiver(*this, Receiver);
2413 
2414     // In ARC, annotate delegate init calls.
2415     if (Result->getMethodFamily() == OMF_init &&
2416         (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2417       // Only consider init calls *directly* in init implementations,
2418       // not within blocks.
2419       ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2420       if (method && method->getMethodFamily() == OMF_init) {
2421         // The implicit assignment to self means we also don't want to
2422         // consume the result.
2423         Result->setDelegateInitCall(true);
2424         return Owned(Result);
2425       }
2426     }
2427 
2428     // In ARC, check for message sends which are likely to introduce
2429     // retain cycles.
2430     checkRetainCycles(Result);
2431   }
2432 
2433   return MaybeBindToTemporary(Result);
2434 }
2435 
2436 // ActOnInstanceMessage - used for both unary and keyword messages.
2437 // ArgExprs is optional - if it is present, the number of expressions
2438 // is obtained from Sel.getNumArgs().
2439 ExprResult Sema::ActOnInstanceMessage(Scope *S,
2440                                       Expr *Receiver,
2441                                       Selector Sel,
2442                                       SourceLocation LBracLoc,
2443                                       ArrayRef<SourceLocation> SelectorLocs,
2444                                       SourceLocation RBracLoc,
2445                                       MultiExprArg Args) {
2446   if (!Receiver)
2447     return ExprError();
2448 
2449   return BuildInstanceMessage(Receiver, Receiver->getType(),
2450                               /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
2451                               LBracLoc, SelectorLocs, RBracLoc, move(Args));
2452 }
2453 
2454 enum ARCConversionTypeClass {
2455   /// int, void, struct A
2456   ACTC_none,
2457 
2458   /// id, void (^)()
2459   ACTC_retainable,
2460 
2461   /// id*, id***, void (^*)(),
2462   ACTC_indirectRetainable,
2463 
2464   /// void* might be a normal C type, or it might a CF type.
2465   ACTC_voidPtr,
2466 
2467   /// struct A*
2468   ACTC_coreFoundation
2469 };
2470 static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2471   return (ACTC == ACTC_retainable ||
2472           ACTC == ACTC_coreFoundation ||
2473           ACTC == ACTC_voidPtr);
2474 }
2475 static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2476   return ACTC == ACTC_none ||
2477          ACTC == ACTC_voidPtr ||
2478          ACTC == ACTC_coreFoundation;
2479 }
2480 
2481 static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
2482   bool isIndirect = false;
2483 
2484   // Ignore an outermost reference type.
2485   if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
2486     type = ref->getPointeeType();
2487     isIndirect = true;
2488   }
2489 
2490   // Drill through pointers and arrays recursively.
2491   while (true) {
2492     if (const PointerType *ptr = type->getAs<PointerType>()) {
2493       type = ptr->getPointeeType();
2494 
2495       // The first level of pointer may be the innermost pointer on a CF type.
2496       if (!isIndirect) {
2497         if (type->isVoidType()) return ACTC_voidPtr;
2498         if (type->isRecordType()) return ACTC_coreFoundation;
2499       }
2500     } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2501       type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2502     } else {
2503       break;
2504     }
2505     isIndirect = true;
2506   }
2507 
2508   if (isIndirect) {
2509     if (type->isObjCARCBridgableType())
2510       return ACTC_indirectRetainable;
2511     return ACTC_none;
2512   }
2513 
2514   if (type->isObjCARCBridgableType())
2515     return ACTC_retainable;
2516 
2517   return ACTC_none;
2518 }
2519 
2520 namespace {
2521   /// A result from the cast checker.
2522   enum ACCResult {
2523     /// Cannot be casted.
2524     ACC_invalid,
2525 
2526     /// Can be safely retained or not retained.
2527     ACC_bottom,
2528 
2529     /// Can be casted at +0.
2530     ACC_plusZero,
2531 
2532     /// Can be casted at +1.
2533     ACC_plusOne
2534   };
2535   ACCResult merge(ACCResult left, ACCResult right) {
2536     if (left == right) return left;
2537     if (left == ACC_bottom) return right;
2538     if (right == ACC_bottom) return left;
2539     return ACC_invalid;
2540   }
2541 
2542   /// A checker which white-lists certain expressions whose conversion
2543   /// to or from retainable type would otherwise be forbidden in ARC.
2544   class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2545     typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2546 
2547     ASTContext &Context;
2548     ARCConversionTypeClass SourceClass;
2549     ARCConversionTypeClass TargetClass;
2550     bool Diagnose;
2551 
2552     static bool isCFType(QualType type) {
2553       // Someday this can use ns_bridged.  For now, it has to do this.
2554       return type->isCARCBridgableType();
2555     }
2556 
2557   public:
2558     ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
2559                    ARCConversionTypeClass target, bool diagnose)
2560       : Context(Context), SourceClass(source), TargetClass(target),
2561         Diagnose(diagnose) {}
2562 
2563     using super::Visit;
2564     ACCResult Visit(Expr *e) {
2565       return super::Visit(e->IgnoreParens());
2566     }
2567 
2568     ACCResult VisitStmt(Stmt *s) {
2569       return ACC_invalid;
2570     }
2571 
2572     /// Null pointer constants can be casted however you please.
2573     ACCResult VisitExpr(Expr *e) {
2574       if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2575         return ACC_bottom;
2576       return ACC_invalid;
2577     }
2578 
2579     /// Objective-C string literals can be safely casted.
2580     ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2581       // If we're casting to any retainable type, go ahead.  Global
2582       // strings are immune to retains, so this is bottom.
2583       if (isAnyRetainable(TargetClass)) return ACC_bottom;
2584 
2585       return ACC_invalid;
2586     }
2587 
2588     /// Look through certain implicit and explicit casts.
2589     ACCResult VisitCastExpr(CastExpr *e) {
2590       switch (e->getCastKind()) {
2591         case CK_NullToPointer:
2592           return ACC_bottom;
2593 
2594         case CK_NoOp:
2595         case CK_LValueToRValue:
2596         case CK_BitCast:
2597         case CK_CPointerToObjCPointerCast:
2598         case CK_BlockPointerToObjCPointerCast:
2599         case CK_AnyPointerToBlockPointerCast:
2600           return Visit(e->getSubExpr());
2601 
2602         default:
2603           return ACC_invalid;
2604       }
2605     }
2606 
2607     /// Look through unary extension.
2608     ACCResult VisitUnaryExtension(UnaryOperator *e) {
2609       return Visit(e->getSubExpr());
2610     }
2611 
2612     /// Ignore the LHS of a comma operator.
2613     ACCResult VisitBinComma(BinaryOperator *e) {
2614       return Visit(e->getRHS());
2615     }
2616 
2617     /// Conditional operators are okay if both sides are okay.
2618     ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2619       ACCResult left = Visit(e->getTrueExpr());
2620       if (left == ACC_invalid) return ACC_invalid;
2621       return merge(left, Visit(e->getFalseExpr()));
2622     }
2623 
2624     /// Look through pseudo-objects.
2625     ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2626       // If we're getting here, we should always have a result.
2627       return Visit(e->getResultExpr());
2628     }
2629 
2630     /// Statement expressions are okay if their result expression is okay.
2631     ACCResult VisitStmtExpr(StmtExpr *e) {
2632       return Visit(e->getSubStmt()->body_back());
2633     }
2634 
2635     /// Some declaration references are okay.
2636     ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
2637       // References to global constants from system headers are okay.
2638       // These are things like 'kCFStringTransformToLatin'.  They are
2639       // can also be assumed to be immune to retains.
2640       VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
2641       if (isAnyRetainable(TargetClass) &&
2642           isAnyRetainable(SourceClass) &&
2643           var &&
2644           var->getStorageClass() == SC_Extern &&
2645           var->getType().isConstQualified() &&
2646           Context.getSourceManager().isInSystemHeader(var->getLocation())) {
2647         return ACC_bottom;
2648       }
2649 
2650       // Nothing else.
2651       return ACC_invalid;
2652     }
2653 
2654     /// Some calls are okay.
2655     ACCResult VisitCallExpr(CallExpr *e) {
2656       if (FunctionDecl *fn = e->getDirectCallee())
2657         if (ACCResult result = checkCallToFunction(fn))
2658           return result;
2659 
2660       return super::VisitCallExpr(e);
2661     }
2662 
2663     ACCResult checkCallToFunction(FunctionDecl *fn) {
2664       // Require a CF*Ref return type.
2665       if (!isCFType(fn->getResultType()))
2666         return ACC_invalid;
2667 
2668       if (!isAnyRetainable(TargetClass))
2669         return ACC_invalid;
2670 
2671       // Honor an explicit 'not retained' attribute.
2672       if (fn->hasAttr<CFReturnsNotRetainedAttr>())
2673         return ACC_plusZero;
2674 
2675       // Honor an explicit 'retained' attribute, except that for
2676       // now we're not going to permit implicit handling of +1 results,
2677       // because it's a bit frightening.
2678       if (fn->hasAttr<CFReturnsRetainedAttr>())
2679         return Diagnose ? ACC_plusOne
2680                         : ACC_invalid; // ACC_plusOne if we start accepting this
2681 
2682       // Recognize this specific builtin function, which is used by CFSTR.
2683       unsigned builtinID = fn->getBuiltinID();
2684       if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
2685         return ACC_bottom;
2686 
2687       // Otherwise, don't do anything implicit with an unaudited function.
2688       if (!fn->hasAttr<CFAuditedTransferAttr>())
2689         return ACC_invalid;
2690 
2691       // Otherwise, it's +0 unless it follows the create convention.
2692       if (ento::coreFoundation::followsCreateRule(fn))
2693         return Diagnose ? ACC_plusOne
2694                         : ACC_invalid; // ACC_plusOne if we start accepting this
2695 
2696       return ACC_plusZero;
2697     }
2698 
2699     ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
2700       return checkCallToMethod(e->getMethodDecl());
2701     }
2702 
2703     ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
2704       ObjCMethodDecl *method;
2705       if (e->isExplicitProperty())
2706         method = e->getExplicitProperty()->getGetterMethodDecl();
2707       else
2708         method = e->getImplicitPropertyGetter();
2709       return checkCallToMethod(method);
2710     }
2711 
2712     ACCResult checkCallToMethod(ObjCMethodDecl *method) {
2713       if (!method) return ACC_invalid;
2714 
2715       // Check for message sends to functions returning CF types.  We
2716       // just obey the Cocoa conventions with these, even though the
2717       // return type is CF.
2718       if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType()))
2719         return ACC_invalid;
2720 
2721       // If the method is explicitly marked not-retained, it's +0.
2722       if (method->hasAttr<CFReturnsNotRetainedAttr>())
2723         return ACC_plusZero;
2724 
2725       // If the method is explicitly marked as returning retained, or its
2726       // selector follows a +1 Cocoa convention, treat it as +1.
2727       if (method->hasAttr<CFReturnsRetainedAttr>())
2728         return ACC_plusOne;
2729 
2730       switch (method->getSelector().getMethodFamily()) {
2731       case OMF_alloc:
2732       case OMF_copy:
2733       case OMF_mutableCopy:
2734       case OMF_new:
2735         return ACC_plusOne;
2736 
2737       default:
2738         // Otherwise, treat it as +0.
2739         return ACC_plusZero;
2740       }
2741     }
2742   };
2743 }
2744 
2745 bool Sema::isKnownName(StringRef name) {
2746   if (name.empty())
2747     return false;
2748   LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
2749                  Sema::LookupOrdinaryName);
2750   return LookupName(R, TUScope, false);
2751 }
2752 
2753 static void addFixitForObjCARCConversion(Sema &S,
2754                                          DiagnosticBuilder &DiagB,
2755                                          Sema::CheckedConversionKind CCK,
2756                                          SourceLocation afterLParen,
2757                                          QualType castType,
2758                                          Expr *castExpr,
2759                                          const char *bridgeKeyword,
2760                                          const char *CFBridgeName) {
2761   // We handle C-style and implicit casts here.
2762   switch (CCK) {
2763   case Sema::CCK_ImplicitConversion:
2764   case Sema::CCK_CStyleCast:
2765     break;
2766   case Sema::CCK_FunctionalCast:
2767   case Sema::CCK_OtherCast:
2768     return;
2769   }
2770 
2771   if (CFBridgeName) {
2772     Expr *castedE = castExpr;
2773     if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
2774       castedE = CCE->getSubExpr();
2775     castedE = castedE->IgnoreImpCasts();
2776     SourceRange range = castedE->getSourceRange();
2777 
2778     SmallString<32> BridgeCall;
2779 
2780     SourceManager &SM = S.getSourceManager();
2781     char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
2782     if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
2783       BridgeCall += ' ';
2784 
2785     BridgeCall += CFBridgeName;
2786 
2787     if (isa<ParenExpr>(castedE)) {
2788       DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2789                          BridgeCall));
2790     } else {
2791       BridgeCall += '(';
2792       DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2793                                                     BridgeCall));
2794       DiagB.AddFixItHint(FixItHint::CreateInsertion(
2795                                        S.PP.getLocForEndOfToken(range.getEnd()),
2796                                        ")"));
2797     }
2798     return;
2799   }
2800 
2801   if (CCK == Sema::CCK_CStyleCast) {
2802     DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
2803   } else {
2804     std::string castCode = "(";
2805     castCode += bridgeKeyword;
2806     castCode += castType.getAsString();
2807     castCode += ")";
2808     Expr *castedE = castExpr->IgnoreImpCasts();
2809     SourceRange range = castedE->getSourceRange();
2810     if (isa<ParenExpr>(castedE)) {
2811       DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2812                          castCode));
2813     } else {
2814       castCode += "(";
2815       DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2816                                                     castCode));
2817       DiagB.AddFixItHint(FixItHint::CreateInsertion(
2818                                        S.PP.getLocForEndOfToken(range.getEnd()),
2819                                        ")"));
2820     }
2821   }
2822 }
2823 
2824 static void
2825 diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
2826                           QualType castType, ARCConversionTypeClass castACTC,
2827                           Expr *castExpr, ARCConversionTypeClass exprACTC,
2828                           Sema::CheckedConversionKind CCK) {
2829   SourceLocation loc =
2830     (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
2831 
2832   if (S.makeUnavailableInSystemHeader(loc,
2833                 "converts between Objective-C and C pointers in -fobjc-arc"))
2834     return;
2835 
2836   QualType castExprType = castExpr->getType();
2837 
2838   unsigned srcKind = 0;
2839   switch (exprACTC) {
2840   case ACTC_none:
2841   case ACTC_coreFoundation:
2842   case ACTC_voidPtr:
2843     srcKind = (castExprType->isPointerType() ? 1 : 0);
2844     break;
2845   case ACTC_retainable:
2846     srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
2847     break;
2848   case ACTC_indirectRetainable:
2849     srcKind = 4;
2850     break;
2851   }
2852 
2853   // Check whether this could be fixed with a bridge cast.
2854   SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
2855   SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
2856 
2857   // Bridge from an ARC type to a CF type.
2858   if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
2859 
2860     S.Diag(loc, diag::err_arc_cast_requires_bridge)
2861       << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
2862       << 2 // of C pointer type
2863       << castExprType
2864       << unsigned(castType->isBlockPointerType()) // to ObjC|block type
2865       << castType
2866       << castRange
2867       << castExpr->getSourceRange();
2868     bool br = S.isKnownName("CFBridgingRelease");
2869     ACCResult CreateRule =
2870       ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
2871     assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
2872     if (CreateRule != ACC_plusOne)
2873     {
2874       DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge);
2875       addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2876                                    castType, castExpr, "__bridge ", 0);
2877     }
2878     if (CreateRule != ACC_plusZero)
2879     {
2880       DiagnosticBuilder DiagB = S.Diag(br ? castExpr->getExprLoc() : noteLoc,
2881                                        diag::note_arc_bridge_transfer)
2882         << castExprType << br;
2883       addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2884                                    castType, castExpr, "__bridge_transfer ",
2885                                    br ? "CFBridgingRelease" : 0);
2886     }
2887 
2888     return;
2889   }
2890 
2891   // Bridge from a CF type to an ARC type.
2892   if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
2893     bool br = S.isKnownName("CFBridgingRetain");
2894     S.Diag(loc, diag::err_arc_cast_requires_bridge)
2895       << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
2896       << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
2897       << castExprType
2898       << 2 // to C pointer type
2899       << castType
2900       << castRange
2901       << castExpr->getSourceRange();
2902     ACCResult CreateRule =
2903       ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
2904     assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
2905     if (CreateRule != ACC_plusOne)
2906     {
2907       DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge);
2908       addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2909                                    castType, castExpr, "__bridge ", 0);
2910     }
2911     if (CreateRule != ACC_plusZero)
2912     {
2913       DiagnosticBuilder DiagB = S.Diag(br ? castExpr->getExprLoc() : noteLoc,
2914                                        diag::note_arc_bridge_retained)
2915         << castType << br;
2916       addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2917                                    castType, castExpr, "__bridge_retained ",
2918                                    br ? "CFBridgingRetain" : 0);
2919     }
2920 
2921     return;
2922   }
2923 
2924   S.Diag(loc, diag::err_arc_mismatched_cast)
2925     << (CCK != Sema::CCK_ImplicitConversion)
2926     << srcKind << castExprType << castType
2927     << castRange << castExpr->getSourceRange();
2928 }
2929 
2930 Sema::ARCConversionResult
2931 Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
2932                              Expr *&castExpr, CheckedConversionKind CCK) {
2933   QualType castExprType = castExpr->getType();
2934 
2935   // For the purposes of the classification, we assume reference types
2936   // will bind to temporaries.
2937   QualType effCastType = castType;
2938   if (const ReferenceType *ref = castType->getAs<ReferenceType>())
2939     effCastType = ref->getPointeeType();
2940 
2941   ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
2942   ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
2943   if (exprACTC == castACTC) {
2944     // check for viablity and report error if casting an rvalue to a
2945     // life-time qualifier.
2946     if ((castACTC == ACTC_retainable) &&
2947         (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
2948         (castType != castExprType)) {
2949       const Type *DT = castType.getTypePtr();
2950       QualType QDT = castType;
2951       // We desugar some types but not others. We ignore those
2952       // that cannot happen in a cast; i.e. auto, and those which
2953       // should not be de-sugared; i.e typedef.
2954       if (const ParenType *PT = dyn_cast<ParenType>(DT))
2955         QDT = PT->desugar();
2956       else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
2957         QDT = TP->desugar();
2958       else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
2959         QDT = AT->desugar();
2960       if (QDT != castType &&
2961           QDT.getObjCLifetime() !=  Qualifiers::OCL_None) {
2962         SourceLocation loc =
2963           (castRange.isValid() ? castRange.getBegin()
2964                               : castExpr->getExprLoc());
2965         Diag(loc, diag::err_arc_nolifetime_behavior);
2966       }
2967     }
2968     return ACR_okay;
2969   }
2970 
2971   if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
2972 
2973   // Allow all of these types to be cast to integer types (but not
2974   // vice-versa).
2975   if (castACTC == ACTC_none && castType->isIntegralType(Context))
2976     return ACR_okay;
2977 
2978   // Allow casts between pointers to lifetime types (e.g., __strong id*)
2979   // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
2980   // must be explicit.
2981   if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
2982     return ACR_okay;
2983   if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
2984       CCK != CCK_ImplicitConversion)
2985     return ACR_okay;
2986 
2987   switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
2988   // For invalid casts, fall through.
2989   case ACC_invalid:
2990     break;
2991 
2992   // Do nothing for both bottom and +0.
2993   case ACC_bottom:
2994   case ACC_plusZero:
2995     return ACR_okay;
2996 
2997   // If the result is +1, consume it here.
2998   case ACC_plusOne:
2999     castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
3000                                         CK_ARCConsumeObject, castExpr,
3001                                         0, VK_RValue);
3002     ExprNeedsCleanups = true;
3003     return ACR_okay;
3004   }
3005 
3006   // If this is a non-implicit cast from id or block type to a
3007   // CoreFoundation type, delay complaining in case the cast is used
3008   // in an acceptable context.
3009   if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
3010       CCK != CCK_ImplicitConversion)
3011     return ACR_unbridged;
3012 
3013   diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3014                             castExpr, exprACTC, CCK);
3015   return ACR_okay;
3016 }
3017 
3018 /// Given that we saw an expression with the ARCUnbridgedCastTy
3019 /// placeholder type, complain bitterly.
3020 void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3021   // We expect the spurious ImplicitCastExpr to already have been stripped.
3022   assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3023   CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3024 
3025   SourceRange castRange;
3026   QualType castType;
3027   CheckedConversionKind CCK;
3028 
3029   if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3030     castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3031     castType = cast->getTypeAsWritten();
3032     CCK = CCK_CStyleCast;
3033   } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3034     castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3035     castType = cast->getTypeAsWritten();
3036     CCK = CCK_OtherCast;
3037   } else {
3038     castType = cast->getType();
3039     CCK = CCK_ImplicitConversion;
3040   }
3041 
3042   ARCConversionTypeClass castACTC =
3043     classifyTypeForARCConversion(castType.getNonReferenceType());
3044 
3045   Expr *castExpr = realCast->getSubExpr();
3046   assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3047 
3048   diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3049                             castExpr, ACTC_retainable, CCK);
3050 }
3051 
3052 /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3053 /// type, remove the placeholder cast.
3054 Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3055   assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3056 
3057   if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3058     Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3059     return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3060   } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3061     assert(uo->getOpcode() == UO_Extension);
3062     Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3063     return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3064                                    sub->getValueKind(), sub->getObjectKind(),
3065                                        uo->getOperatorLoc());
3066   } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3067     assert(!gse->isResultDependent());
3068 
3069     unsigned n = gse->getNumAssocs();
3070     SmallVector<Expr*, 4> subExprs(n);
3071     SmallVector<TypeSourceInfo*, 4> subTypes(n);
3072     for (unsigned i = 0; i != n; ++i) {
3073       subTypes[i] = gse->getAssocTypeSourceInfo(i);
3074       Expr *sub = gse->getAssocExpr(i);
3075       if (i == gse->getResultIndex())
3076         sub = stripARCUnbridgedCast(sub);
3077       subExprs[i] = sub;
3078     }
3079 
3080     return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3081                                               gse->getControllingExpr(),
3082                                               subTypes.data(), subExprs.data(),
3083                                               n, gse->getDefaultLoc(),
3084                                               gse->getRParenLoc(),
3085                                        gse->containsUnexpandedParameterPack(),
3086                                               gse->getResultIndex());
3087   } else {
3088     assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3089     return cast<ImplicitCastExpr>(e)->getSubExpr();
3090   }
3091 }
3092 
3093 bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3094                                                  QualType exprType) {
3095   QualType canCastType =
3096     Context.getCanonicalType(castType).getUnqualifiedType();
3097   QualType canExprType =
3098     Context.getCanonicalType(exprType).getUnqualifiedType();
3099   if (isa<ObjCObjectPointerType>(canCastType) &&
3100       castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3101       canExprType->isObjCObjectPointerType()) {
3102     if (const ObjCObjectPointerType *ObjT =
3103         canExprType->getAs<ObjCObjectPointerType>())
3104       if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
3105         return false;
3106   }
3107   return true;
3108 }
3109 
3110 /// Look for an ObjCReclaimReturnedObject cast and destroy it.
3111 static Expr *maybeUndoReclaimObject(Expr *e) {
3112   // For now, we just undo operands that are *immediately* reclaim
3113   // expressions, which prevents the vast majority of potential
3114   // problems here.  To catch them all, we'd need to rebuild arbitrary
3115   // value-propagating subexpressions --- we can't reliably rebuild
3116   // in-place because of expression sharing.
3117   if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
3118     if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
3119       return ice->getSubExpr();
3120 
3121   return e;
3122 }
3123 
3124 ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
3125                                       ObjCBridgeCastKind Kind,
3126                                       SourceLocation BridgeKeywordLoc,
3127                                       TypeSourceInfo *TSInfo,
3128                                       Expr *SubExpr) {
3129   ExprResult SubResult = UsualUnaryConversions(SubExpr);
3130   if (SubResult.isInvalid()) return ExprError();
3131   SubExpr = SubResult.take();
3132 
3133   QualType T = TSInfo->getType();
3134   QualType FromType = SubExpr->getType();
3135 
3136   CastKind CK;
3137 
3138   bool MustConsume = false;
3139   if (T->isDependentType() || SubExpr->isTypeDependent()) {
3140     // Okay: we'll build a dependent expression type.
3141     CK = CK_Dependent;
3142   } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
3143     // Casting CF -> id
3144     CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
3145                                   : CK_CPointerToObjCPointerCast);
3146     switch (Kind) {
3147     case OBC_Bridge:
3148       break;
3149 
3150     case OBC_BridgeRetained: {
3151       bool br = isKnownName("CFBridgingRelease");
3152       Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3153         << 2
3154         << FromType
3155         << (T->isBlockPointerType()? 1 : 0)
3156         << T
3157         << SubExpr->getSourceRange()
3158         << Kind;
3159       Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3160         << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
3161       Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
3162         << FromType << br
3163         << FixItHint::CreateReplacement(BridgeKeywordLoc,
3164                                         br ? "CFBridgingRelease "
3165                                            : "__bridge_transfer ");
3166 
3167       Kind = OBC_Bridge;
3168       break;
3169     }
3170 
3171     case OBC_BridgeTransfer:
3172       // We must consume the Objective-C object produced by the cast.
3173       MustConsume = true;
3174       break;
3175     }
3176   } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
3177     // Okay: id -> CF
3178     CK = CK_BitCast;
3179     switch (Kind) {
3180     case OBC_Bridge:
3181       // Reclaiming a value that's going to be __bridge-casted to CF
3182       // is very dangerous, so we don't do it.
3183       SubExpr = maybeUndoReclaimObject(SubExpr);
3184       break;
3185 
3186     case OBC_BridgeRetained:
3187       // Produce the object before casting it.
3188       SubExpr = ImplicitCastExpr::Create(Context, FromType,
3189                                          CK_ARCProduceObject,
3190                                          SubExpr, 0, VK_RValue);
3191       break;
3192 
3193     case OBC_BridgeTransfer: {
3194       bool br = isKnownName("CFBridgingRetain");
3195       Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3196         << (FromType->isBlockPointerType()? 1 : 0)
3197         << FromType
3198         << 2
3199         << T
3200         << SubExpr->getSourceRange()
3201         << Kind;
3202 
3203       Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3204         << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
3205       Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
3206         << T << br
3207         << FixItHint::CreateReplacement(BridgeKeywordLoc,
3208                           br ? "CFBridgingRetain " : "__bridge_retained");
3209 
3210       Kind = OBC_Bridge;
3211       break;
3212     }
3213     }
3214   } else {
3215     Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
3216       << FromType << T << Kind
3217       << SubExpr->getSourceRange()
3218       << TSInfo->getTypeLoc().getSourceRange();
3219     return ExprError();
3220   }
3221 
3222   Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
3223                                                    BridgeKeywordLoc,
3224                                                    TSInfo, SubExpr);
3225 
3226   if (MustConsume) {
3227     ExprNeedsCleanups = true;
3228     Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
3229                                       0, VK_RValue);
3230   }
3231 
3232   return Result;
3233 }
3234 
3235 ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
3236                                       SourceLocation LParenLoc,
3237                                       ObjCBridgeCastKind Kind,
3238                                       SourceLocation BridgeKeywordLoc,
3239                                       ParsedType Type,
3240                                       SourceLocation RParenLoc,
3241                                       Expr *SubExpr) {
3242   TypeSourceInfo *TSInfo = 0;
3243   QualType T = GetTypeFromParser(Type, &TSInfo);
3244   if (!TSInfo)
3245     TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
3246   return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
3247                               SubExpr);
3248 }
3249