1 //===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for Objective-C expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/ExprObjC.h"
18 #include "clang/AST/StmtVisitor.h"
19 #include "clang/AST/TypeLoc.h"
20 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
21 #include "clang/Edit/Commit.h"
22 #include "clang/Edit/Rewriters.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "clang/Sema/Initialization.h"
25 #include "clang/Sema/Lookup.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/ScopeInfo.h"
28 #include "llvm/ADT/SmallString.h"
29 
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   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                                     /*isPropertyAccessor=*/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, Element);
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                                    /*isPropertyAccessor=*/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                            /*isPropertyAccessor=*/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.data();
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, Elements, Ty,
728                                     ArrayWithObjectsMethod, SR));
729 }
730 
731 ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
732                                             ObjCDictionaryElement *Elements,
733                                             unsigned NumElements) {
734   // Look up the NSDictionary class, if we haven't done so already.
735   if (!NSDictionaryDecl) {
736     NamedDecl *IF = LookupSingleName(TUScope,
737                             NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
738                             SR.getBegin(), LookupOrdinaryName);
739     NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
740     if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
741       NSDictionaryDecl =  ObjCInterfaceDecl::Create (Context,
742                             Context.getTranslationUnitDecl(),
743                             SourceLocation(),
744                             NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
745                             0, SourceLocation());
746 
747     if (!NSDictionaryDecl) {
748       Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
749       return ExprError();
750     }
751   }
752 
753   // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
754   // so already.
755   QualType IdT = Context.getObjCIdType();
756   if (!DictionaryWithObjectsMethod) {
757     Selector Sel = NSAPIObj->getNSDictionarySelector(
758                                NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
759     ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
760     if (!Method && getLangOpts().DebuggerObjCLiteral) {
761       Method = ObjCMethodDecl::Create(Context,
762                            SourceLocation(), SourceLocation(), Sel,
763                            IdT,
764                            0 /*TypeSourceInfo */,
765                            Context.getTranslationUnitDecl(),
766                            false /*Instance*/, false/*isVariadic*/,
767                            /*isPropertyAccessor=*/false,
768                            /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
769                            ObjCMethodDecl::Required,
770                            false);
771       SmallVector<ParmVarDecl *, 3> Params;
772       ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
773                                                  SourceLocation(),
774                                                  SourceLocation(),
775                                                  &Context.Idents.get("objects"),
776                                                  Context.getPointerType(IdT),
777                                                  /*TInfo=*/0, SC_None, SC_None,
778                                                  0);
779       Params.push_back(objects);
780       ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
781                                               SourceLocation(),
782                                               SourceLocation(),
783                                               &Context.Idents.get("keys"),
784                                               Context.getPointerType(IdT),
785                                               /*TInfo=*/0, SC_None, SC_None,
786                                               0);
787       Params.push_back(keys);
788       ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
789                                              SourceLocation(),
790                                              SourceLocation(),
791                                              &Context.Idents.get("cnt"),
792                                              Context.UnsignedLongTy,
793                                              /*TInfo=*/0, SC_None, SC_None,
794                                              0);
795       Params.push_back(cnt);
796       Method->setMethodParams(Context, Params, ArrayRef<SourceLocation>());
797     }
798 
799     if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
800                               Method))
801        return ExprError();
802 
803     // Dig out the type that all values should be converted to.
804     QualType ValueT = Method->param_begin()[0]->getType();
805     const PointerType *PtrValue = ValueT->getAs<PointerType>();
806     if (!PtrValue ||
807         !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
808       Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
809         << Sel;
810       Diag(Method->param_begin()[0]->getLocation(),
811            diag::note_objc_literal_method_param)
812         << 0 << ValueT
813         << Context.getPointerType(IdT.withConst());
814       return ExprError();
815     }
816 
817     // Dig out the type that all keys should be converted to.
818     QualType KeyT = Method->param_begin()[1]->getType();
819     const PointerType *PtrKey = KeyT->getAs<PointerType>();
820     if (!PtrKey ||
821         !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
822                                         IdT)) {
823       bool err = true;
824       if (PtrKey) {
825         if (QIDNSCopying.isNull()) {
826           // key argument of selector is id<NSCopying>?
827           if (ObjCProtocolDecl *NSCopyingPDecl =
828               LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
829             ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
830             QIDNSCopying =
831               Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
832                                         (ObjCProtocolDecl**) PQ,1);
833             QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
834           }
835         }
836         if (!QIDNSCopying.isNull())
837           err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
838                                                 QIDNSCopying);
839       }
840 
841       if (err) {
842         Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
843           << Sel;
844         Diag(Method->param_begin()[1]->getLocation(),
845              diag::note_objc_literal_method_param)
846           << 1 << KeyT
847           << Context.getPointerType(IdT.withConst());
848         return ExprError();
849       }
850     }
851 
852     // Check that the 'count' parameter is integral.
853     QualType CountType = Method->param_begin()[2]->getType();
854     if (!CountType->isIntegerType()) {
855       Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
856         << Sel;
857       Diag(Method->param_begin()[2]->getLocation(),
858            diag::note_objc_literal_method_param)
859         << 2 << CountType
860         << "integral";
861       return ExprError();
862     }
863 
864     // We've found a good +dictionaryWithObjects:keys:count: method; save it!
865     DictionaryWithObjectsMethod = Method;
866   }
867 
868   QualType ValuesT = DictionaryWithObjectsMethod->param_begin()[0]->getType();
869   QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
870   QualType KeysT = DictionaryWithObjectsMethod->param_begin()[1]->getType();
871   QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
872 
873   // Check that each of the keys and values provided is valid in a collection
874   // literal, performing conversions as necessary.
875   bool HasPackExpansions = false;
876   for (unsigned I = 0, N = NumElements; I != N; ++I) {
877     // Check the key.
878     ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
879                                                        KeyT);
880     if (Key.isInvalid())
881       return ExprError();
882 
883     // Check the value.
884     ExprResult Value
885       = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
886     if (Value.isInvalid())
887       return ExprError();
888 
889     Elements[I].Key = Key.get();
890     Elements[I].Value = Value.get();
891 
892     if (Elements[I].EllipsisLoc.isInvalid())
893       continue;
894 
895     if (!Elements[I].Key->containsUnexpandedParameterPack() &&
896         !Elements[I].Value->containsUnexpandedParameterPack()) {
897       Diag(Elements[I].EllipsisLoc,
898            diag::err_pack_expansion_without_parameter_packs)
899         << SourceRange(Elements[I].Key->getLocStart(),
900                        Elements[I].Value->getLocEnd());
901       return ExprError();
902     }
903 
904     HasPackExpansions = true;
905   }
906 
907 
908   QualType Ty
909     = Context.getObjCObjectPointerType(
910                                 Context.getObjCInterfaceType(NSDictionaryDecl));
911   return MaybeBindToTemporary(
912            ObjCDictionaryLiteral::Create(Context,
913                                          llvm::makeArrayRef(Elements,
914                                                             NumElements),
915                                          HasPackExpansions,
916                                          Ty,
917                                          DictionaryWithObjectsMethod, SR));
918 }
919 
920 ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
921                                       TypeSourceInfo *EncodedTypeInfo,
922                                       SourceLocation RParenLoc) {
923   QualType EncodedType = EncodedTypeInfo->getType();
924   QualType StrTy;
925   if (EncodedType->isDependentType())
926     StrTy = Context.DependentTy;
927   else {
928     if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
929         !EncodedType->isVoidType()) // void is handled too.
930       if (RequireCompleteType(AtLoc, EncodedType,
931                               diag::err_incomplete_type_objc_at_encode,
932                               EncodedTypeInfo->getTypeLoc()))
933         return ExprError();
934 
935     std::string Str;
936     Context.getObjCEncodingForType(EncodedType, Str);
937 
938     // The type of @encode is the same as the type of the corresponding string,
939     // which is an array type.
940     StrTy = Context.CharTy;
941     // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
942     if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
943       StrTy.addConst();
944     StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
945                                          ArrayType::Normal, 0);
946   }
947 
948   return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
949 }
950 
951 ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
952                                            SourceLocation EncodeLoc,
953                                            SourceLocation LParenLoc,
954                                            ParsedType ty,
955                                            SourceLocation RParenLoc) {
956   // FIXME: Preserve type source info ?
957   TypeSourceInfo *TInfo;
958   QualType EncodedType = GetTypeFromParser(ty, &TInfo);
959   if (!TInfo)
960     TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
961                                              PP.getLocForEndOfToken(LParenLoc));
962 
963   return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
964 }
965 
966 ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
967                                              SourceLocation AtLoc,
968                                              SourceLocation SelLoc,
969                                              SourceLocation LParenLoc,
970                                              SourceLocation RParenLoc) {
971   ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
972                              SourceRange(LParenLoc, RParenLoc), false, false);
973   if (!Method)
974     Method = LookupFactoryMethodInGlobalPool(Sel,
975                                           SourceRange(LParenLoc, RParenLoc));
976   if (!Method)
977     Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
978 
979   if (!Method ||
980       Method->getImplementationControl() != ObjCMethodDecl::Optional) {
981     llvm::DenseMap<Selector, SourceLocation>::iterator Pos
982       = ReferencedSelectors.find(Sel);
983     if (Pos == ReferencedSelectors.end())
984       ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
985   }
986 
987   // In ARC, forbid the user from using @selector for
988   // retain/release/autorelease/dealloc/retainCount.
989   if (getLangOpts().ObjCAutoRefCount) {
990     switch (Sel.getMethodFamily()) {
991     case OMF_retain:
992     case OMF_release:
993     case OMF_autorelease:
994     case OMF_retainCount:
995     case OMF_dealloc:
996       Diag(AtLoc, diag::err_arc_illegal_selector) <<
997         Sel << SourceRange(LParenLoc, RParenLoc);
998       break;
999 
1000     case OMF_None:
1001     case OMF_alloc:
1002     case OMF_copy:
1003     case OMF_finalize:
1004     case OMF_init:
1005     case OMF_mutableCopy:
1006     case OMF_new:
1007     case OMF_self:
1008     case OMF_performSelector:
1009       break;
1010     }
1011   }
1012   QualType Ty = Context.getObjCSelType();
1013   return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
1014 }
1015 
1016 ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1017                                              SourceLocation AtLoc,
1018                                              SourceLocation ProtoLoc,
1019                                              SourceLocation LParenLoc,
1020                                              SourceLocation ProtoIdLoc,
1021                                              SourceLocation RParenLoc) {
1022   ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
1023   if (!PDecl) {
1024     Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
1025     return true;
1026   }
1027 
1028   QualType Ty = Context.getObjCProtoType();
1029   if (Ty.isNull())
1030     return true;
1031   Ty = Context.getObjCObjectPointerType(Ty);
1032   return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
1033 }
1034 
1035 /// Try to capture an implicit reference to 'self'.
1036 ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1037   DeclContext *DC = getFunctionLevelDeclContext();
1038 
1039   // If we're not in an ObjC method, error out.  Note that, unlike the
1040   // C++ case, we don't require an instance method --- class methods
1041   // still have a 'self', and we really do still need to capture it!
1042   ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1043   if (!method)
1044     return 0;
1045 
1046   tryCaptureVariable(method->getSelfDecl(), Loc);
1047 
1048   return method;
1049 }
1050 
1051 static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1052   if (T == Context.getObjCInstanceType())
1053     return Context.getObjCIdType();
1054 
1055   return T;
1056 }
1057 
1058 QualType Sema::getMessageSendResultType(QualType ReceiverType,
1059                                         ObjCMethodDecl *Method,
1060                                     bool isClassMessage, bool isSuperMessage) {
1061   assert(Method && "Must have a method");
1062   if (!Method->hasRelatedResultType())
1063     return Method->getSendResultType();
1064 
1065   // If a method has a related return type:
1066   //   - if the method found is an instance method, but the message send
1067   //     was a class message send, T is the declared return type of the method
1068   //     found
1069   if (Method->isInstanceMethod() && isClassMessage)
1070     return stripObjCInstanceType(Context, Method->getSendResultType());
1071 
1072   //   - if the receiver is super, T is a pointer to the class of the
1073   //     enclosing method definition
1074   if (isSuperMessage) {
1075     if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
1076       if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
1077         return Context.getObjCObjectPointerType(
1078                                         Context.getObjCInterfaceType(Class));
1079   }
1080 
1081   //   - if the receiver is the name of a class U, T is a pointer to U
1082   if (ReceiverType->getAs<ObjCInterfaceType>() ||
1083       ReceiverType->isObjCQualifiedInterfaceType())
1084     return Context.getObjCObjectPointerType(ReceiverType);
1085   //   - if the receiver is of type Class or qualified Class type,
1086   //     T is the declared return type of the method.
1087   if (ReceiverType->isObjCClassType() ||
1088       ReceiverType->isObjCQualifiedClassType())
1089     return stripObjCInstanceType(Context, Method->getSendResultType());
1090 
1091   //   - if the receiver is id, qualified id, Class, or qualified Class, T
1092   //     is the receiver type, otherwise
1093   //   - T is the type of the receiver expression.
1094   return ReceiverType;
1095 }
1096 
1097 /// Look for an ObjC method whose result type exactly matches the given type.
1098 static const ObjCMethodDecl *
1099 findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1100                                  QualType instancetype) {
1101   if (MD->getResultType() == instancetype) return MD;
1102 
1103   // For these purposes, a method in an @implementation overrides a
1104   // declaration in the @interface.
1105   if (const ObjCImplDecl *impl =
1106         dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1107     const ObjCContainerDecl *iface;
1108     if (const ObjCCategoryImplDecl *catImpl =
1109           dyn_cast<ObjCCategoryImplDecl>(impl)) {
1110       iface = catImpl->getCategoryDecl();
1111     } else {
1112       iface = impl->getClassInterface();
1113     }
1114 
1115     const ObjCMethodDecl *ifaceMD =
1116       iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1117     if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1118   }
1119 
1120   SmallVector<const ObjCMethodDecl *, 4> overrides;
1121   MD->getOverriddenMethods(overrides);
1122   for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1123     if (const ObjCMethodDecl *result =
1124           findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1125       return result;
1126   }
1127 
1128   return 0;
1129 }
1130 
1131 void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1132   // Only complain if we're in an ObjC method and the required return
1133   // type doesn't match the method's declared return type.
1134   ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1135   if (!MD || !MD->hasRelatedResultType() ||
1136       Context.hasSameUnqualifiedType(destType, MD->getResultType()))
1137     return;
1138 
1139   // Look for a method overridden by this method which explicitly uses
1140   // 'instancetype'.
1141   if (const ObjCMethodDecl *overridden =
1142         findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
1143     SourceLocation loc;
1144     SourceRange range;
1145     if (TypeSourceInfo *TSI = overridden->getResultTypeSourceInfo()) {
1146       range = TSI->getTypeLoc().getSourceRange();
1147       loc = range.getBegin();
1148     }
1149     if (loc.isInvalid())
1150       loc = overridden->getLocation();
1151     Diag(loc, diag::note_related_result_type_explicit)
1152       << /*current method*/ 1 << range;
1153     return;
1154   }
1155 
1156   // Otherwise, if we have an interesting method family, note that.
1157   // This should always trigger if the above didn't.
1158   if (ObjCMethodFamily family = MD->getMethodFamily())
1159     Diag(MD->getLocation(), diag::note_related_result_type_family)
1160       << /*current method*/ 1
1161       << family;
1162 }
1163 
1164 void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1165   E = E->IgnoreParenImpCasts();
1166   const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1167   if (!MsgSend)
1168     return;
1169 
1170   const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1171   if (!Method)
1172     return;
1173 
1174   if (!Method->hasRelatedResultType())
1175     return;
1176 
1177   if (Context.hasSameUnqualifiedType(Method->getResultType()
1178                                                         .getNonReferenceType(),
1179                                      MsgSend->getType()))
1180     return;
1181 
1182   if (!Context.hasSameUnqualifiedType(Method->getResultType(),
1183                                       Context.getObjCInstanceType()))
1184     return;
1185 
1186   Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1187     << Method->isInstanceMethod() << Method->getSelector()
1188     << MsgSend->getType();
1189 }
1190 
1191 bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
1192                                      Expr **Args, unsigned NumArgs,
1193                                      Selector Sel,
1194                                      ArrayRef<SourceLocation> SelectorLocs,
1195                                      ObjCMethodDecl *Method,
1196                                      bool isClassMessage, bool isSuperMessage,
1197                                      SourceLocation lbrac, SourceLocation rbrac,
1198                                      QualType &ReturnType, ExprValueKind &VK) {
1199   if (!Method) {
1200     // Apply default argument promotion as for (C99 6.5.2.2p6).
1201     for (unsigned i = 0; i != NumArgs; i++) {
1202       if (Args[i]->isTypeDependent())
1203         continue;
1204 
1205       ExprResult result;
1206       if (getLangOpts().DebuggerSupport) {
1207         QualType paramTy; // ignored
1208         result = checkUnknownAnyArg(lbrac, Args[i], paramTy);
1209       } else {
1210         result = DefaultArgumentPromotion(Args[i]);
1211       }
1212       if (result.isInvalid())
1213         return true;
1214       Args[i] = result.take();
1215     }
1216 
1217     unsigned DiagID;
1218     if (getLangOpts().ObjCAutoRefCount)
1219       DiagID = diag::err_arc_method_not_found;
1220     else
1221       DiagID = isClassMessage ? diag::warn_class_method_not_found
1222                               : diag::warn_inst_method_not_found;
1223     if (!getLangOpts().DebuggerSupport)
1224       Diag(lbrac, DiagID)
1225         << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
1226                                                 SelectorLocs.back());
1227 
1228     // In debuggers, we want to use __unknown_anytype for these
1229     // results so that clients can cast them.
1230     if (getLangOpts().DebuggerSupport) {
1231       ReturnType = Context.UnknownAnyTy;
1232     } else {
1233       ReturnType = Context.getObjCIdType();
1234     }
1235     VK = VK_RValue;
1236     return false;
1237   }
1238 
1239   ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1240                                         isSuperMessage);
1241   VK = Expr::getValueKindForType(Method->getResultType());
1242 
1243   unsigned NumNamedArgs = Sel.getNumArgs();
1244   // Method might have more arguments than selector indicates. This is due
1245   // to addition of c-style arguments in method.
1246   if (Method->param_size() > Sel.getNumArgs())
1247     NumNamedArgs = Method->param_size();
1248   // FIXME. This need be cleaned up.
1249   if (NumArgs < NumNamedArgs) {
1250     Diag(lbrac, diag::err_typecheck_call_too_few_args)
1251       << 2 << NumNamedArgs << NumArgs;
1252     return false;
1253   }
1254 
1255   bool IsError = false;
1256   for (unsigned i = 0; i < NumNamedArgs; i++) {
1257     // We can't do any type-checking on a type-dependent argument.
1258     if (Args[i]->isTypeDependent())
1259       continue;
1260 
1261     Expr *argExpr = Args[i];
1262 
1263     ParmVarDecl *param = Method->param_begin()[i];
1264     assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
1265 
1266     // Strip the unbridged-cast placeholder expression off unless it's
1267     // a consumed argument.
1268     if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1269         !param->hasAttr<CFConsumedAttr>())
1270       argExpr = stripARCUnbridgedCast(argExpr);
1271 
1272     // If the parameter is __unknown_anytype, infer its type
1273     // from the argument.
1274     if (param->getType() == Context.UnknownAnyTy) {
1275       QualType paramType;
1276       ExprResult argE = checkUnknownAnyArg(lbrac, argExpr, paramType);
1277       if (argE.isInvalid()) {
1278         IsError = true;
1279       } else {
1280         Args[i] = argE.take();
1281 
1282         // Update the parameter type in-place.
1283         param->setType(paramType);
1284       }
1285       continue;
1286     }
1287 
1288     if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
1289                             param->getType(),
1290                             diag::err_call_incomplete_argument, argExpr))
1291       return true;
1292 
1293     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1294                                                                       param);
1295     ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
1296     if (ArgE.isInvalid())
1297       IsError = true;
1298     else
1299       Args[i] = ArgE.takeAs<Expr>();
1300   }
1301 
1302   // Promote additional arguments to variadic methods.
1303   if (Method->isVariadic()) {
1304     for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
1305       if (Args[i]->isTypeDependent())
1306         continue;
1307 
1308       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
1309                                                         0);
1310       IsError |= Arg.isInvalid();
1311       Args[i] = Arg.take();
1312     }
1313   } else {
1314     // Check for extra arguments to non-variadic methods.
1315     if (NumArgs != NumNamedArgs) {
1316       Diag(Args[NumNamedArgs]->getLocStart(),
1317            diag::err_typecheck_call_too_many_args)
1318         << 2 /*method*/ << NumNamedArgs << NumArgs
1319         << Method->getSourceRange()
1320         << SourceRange(Args[NumNamedArgs]->getLocStart(),
1321                        Args[NumArgs-1]->getLocEnd());
1322     }
1323   }
1324 
1325   DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
1326 
1327   // Do additional checkings on method.
1328   IsError |= CheckObjCMethodCall(Method, lbrac, Args, NumArgs);
1329 
1330   return IsError;
1331 }
1332 
1333 bool Sema::isSelfExpr(Expr *receiver) {
1334   // 'self' is objc 'self' in an objc method only.
1335   ObjCMethodDecl *method =
1336     dyn_cast<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1337   if (!method) return false;
1338 
1339   receiver = receiver->IgnoreParenLValueCasts();
1340   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
1341     if (DRE->getDecl() == method->getSelfDecl())
1342       return true;
1343   return false;
1344 }
1345 
1346 /// LookupMethodInType - Look up a method in an ObjCObjectType.
1347 ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1348                                                bool isInstance) {
1349   const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1350   if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1351     // Look it up in the main interface (and categories, etc.)
1352     if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1353       return method;
1354 
1355     // Okay, look for "private" methods declared in any
1356     // @implementations we've seen.
1357     if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1358       return method;
1359   }
1360 
1361   // Check qualifiers.
1362   for (ObjCObjectType::qual_iterator
1363          i = objType->qual_begin(), e = objType->qual_end(); i != e; ++i)
1364     if (ObjCMethodDecl *method = (*i)->lookupMethod(sel, isInstance))
1365       return method;
1366 
1367   return 0;
1368 }
1369 
1370 /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1371 /// list of a qualified objective pointer type.
1372 ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1373                                               const ObjCObjectPointerType *OPT,
1374                                               bool Instance)
1375 {
1376   ObjCMethodDecl *MD = 0;
1377   for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1378        E = OPT->qual_end(); I != E; ++I) {
1379     ObjCProtocolDecl *PROTO = (*I);
1380     if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1381       return MD;
1382     }
1383   }
1384   return 0;
1385 }
1386 
1387 static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) {
1388   if (!Receiver)
1389     return;
1390 
1391   if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Receiver))
1392     Receiver = OVE->getSourceExpr();
1393 
1394   Expr *RExpr = Receiver->IgnoreParenImpCasts();
1395   SourceLocation Loc = RExpr->getLocStart();
1396   QualType T = RExpr->getType();
1397   const ObjCPropertyDecl *PDecl = 0;
1398   const ObjCMethodDecl *GDecl = 0;
1399   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) {
1400     RExpr = POE->getSyntacticForm();
1401     if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) {
1402       if (PRE->isImplicitProperty()) {
1403         GDecl = PRE->getImplicitPropertyGetter();
1404         if (GDecl) {
1405           T = GDecl->getResultType();
1406         }
1407       }
1408       else {
1409         PDecl = PRE->getExplicitProperty();
1410         if (PDecl) {
1411           T = PDecl->getType();
1412         }
1413       }
1414     }
1415   }
1416   else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RExpr)) {
1417     // See if receiver is a method which envokes a synthesized getter
1418     // backing a 'weak' property.
1419     ObjCMethodDecl *Method = ME->getMethodDecl();
1420     if (Method && Method->getSelector().getNumArgs() == 0) {
1421       PDecl = Method->findPropertyDecl();
1422       if (PDecl)
1423         T = PDecl->getType();
1424     }
1425   }
1426 
1427   if (T.getObjCLifetime() != Qualifiers::OCL_Weak) {
1428     if (!PDecl)
1429       return;
1430     if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak))
1431       return;
1432   }
1433 
1434   S.Diag(Loc, diag::warn_receiver_is_weak)
1435     << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2));
1436 
1437   if (PDecl)
1438     S.Diag(PDecl->getLocation(), diag::note_property_declare);
1439   else if (GDecl)
1440     S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl;
1441 
1442   S.Diag(Loc, diag::note_arc_assign_to_strong);
1443 }
1444 
1445 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1446 /// objective C interface.  This is a property reference expression.
1447 ExprResult Sema::
1448 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
1449                           Expr *BaseExpr, SourceLocation OpLoc,
1450                           DeclarationName MemberName,
1451                           SourceLocation MemberLoc,
1452                           SourceLocation SuperLoc, QualType SuperType,
1453                           bool Super) {
1454   const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1455   ObjCInterfaceDecl *IFace = IFaceT->getDecl();
1456 
1457   if (!MemberName.isIdentifier()) {
1458     Diag(MemberLoc, diag::err_invalid_property_name)
1459       << MemberName << QualType(OPT, 0);
1460     return ExprError();
1461   }
1462 
1463   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1464 
1465   SourceRange BaseRange = Super? SourceRange(SuperLoc)
1466                                : BaseExpr->getSourceRange();
1467   if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
1468                           diag::err_property_not_found_forward_class,
1469                           MemberName, BaseRange))
1470     return ExprError();
1471 
1472   // Search for a declared property first.
1473   if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
1474     // Check whether we can reference this property.
1475     if (DiagnoseUseOfDecl(PD, MemberLoc))
1476       return ExprError();
1477     if (Super)
1478       return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
1479                                                      VK_LValue, OK_ObjCProperty,
1480                                                      MemberLoc,
1481                                                      SuperLoc, SuperType));
1482     else
1483       return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
1484                                                      VK_LValue, OK_ObjCProperty,
1485                                                      MemberLoc, BaseExpr));
1486   }
1487   // Check protocols on qualified interfaces.
1488   for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1489        E = OPT->qual_end(); I != E; ++I)
1490     if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
1491       // Check whether we can reference this property.
1492       if (DiagnoseUseOfDecl(PD, MemberLoc))
1493         return ExprError();
1494 
1495       if (Super)
1496         return Owned(new (Context) ObjCPropertyRefExpr(PD,
1497                                                        Context.PseudoObjectTy,
1498                                                        VK_LValue,
1499                                                        OK_ObjCProperty,
1500                                                        MemberLoc,
1501                                                        SuperLoc, SuperType));
1502       else
1503         return Owned(new (Context) ObjCPropertyRefExpr(PD,
1504                                                        Context.PseudoObjectTy,
1505                                                        VK_LValue,
1506                                                        OK_ObjCProperty,
1507                                                        MemberLoc,
1508                                                        BaseExpr));
1509     }
1510   // If that failed, look for an "implicit" property by seeing if the nullary
1511   // selector is implemented.
1512 
1513   // FIXME: The logic for looking up nullary and unary selectors should be
1514   // shared with the code in ActOnInstanceMessage.
1515 
1516   Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1517   ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1518 
1519   // May be founf in property's qualified list.
1520   if (!Getter)
1521     Getter = LookupMethodInQualifiedType(Sel, OPT, true);
1522 
1523   // If this reference is in an @implementation, check for 'private' methods.
1524   if (!Getter)
1525     Getter = IFace->lookupPrivateMethod(Sel);
1526 
1527   if (Getter) {
1528     // Check if we can reference this property.
1529     if (DiagnoseUseOfDecl(Getter, MemberLoc))
1530       return ExprError();
1531   }
1532   // If we found a getter then this may be a valid dot-reference, we
1533   // will look for the matching setter, in case it is needed.
1534   Selector SetterSel =
1535     SelectorTable::constructSetterName(PP.getIdentifierTable(),
1536                                        PP.getSelectorTable(), Member);
1537   ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1538 
1539   // May be founf in property's qualified list.
1540   if (!Setter)
1541     Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1542 
1543   if (!Setter) {
1544     // If this reference is in an @implementation, also check for 'private'
1545     // methods.
1546     Setter = IFace->lookupPrivateMethod(SetterSel);
1547   }
1548 
1549   if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1550     return ExprError();
1551 
1552   if (Getter || Setter) {
1553     if (Super)
1554       return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1555                                                      Context.PseudoObjectTy,
1556                                                      VK_LValue, OK_ObjCProperty,
1557                                                      MemberLoc,
1558                                                      SuperLoc, SuperType));
1559     else
1560       return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1561                                                      Context.PseudoObjectTy,
1562                                                      VK_LValue, OK_ObjCProperty,
1563                                                      MemberLoc, BaseExpr));
1564 
1565   }
1566 
1567   // Attempt to correct for typos in property names.
1568   DeclFilterCCC<ObjCPropertyDecl> Validator;
1569   if (TypoCorrection Corrected = CorrectTypo(
1570       DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
1571       NULL, Validator, IFace, false, OPT)) {
1572     ObjCPropertyDecl *Property =
1573         Corrected.getCorrectionDeclAs<ObjCPropertyDecl>();
1574     DeclarationName TypoResult = Corrected.getCorrection();
1575     Diag(MemberLoc, diag::err_property_not_found_suggest)
1576       << MemberName << QualType(OPT, 0) << TypoResult
1577       << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
1578     Diag(Property->getLocation(), diag::note_previous_decl)
1579       << Property->getDeclName();
1580     return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1581                                      TypoResult, MemberLoc,
1582                                      SuperLoc, SuperType, Super);
1583   }
1584   ObjCInterfaceDecl *ClassDeclared;
1585   if (ObjCIvarDecl *Ivar =
1586       IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1587     QualType T = Ivar->getType();
1588     if (const ObjCObjectPointerType * OBJPT =
1589         T->getAsObjCInterfacePointerType()) {
1590       if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
1591                               diag::err_property_not_as_forward_class,
1592                               MemberName, BaseExpr))
1593         return ExprError();
1594     }
1595     Diag(MemberLoc,
1596          diag::err_ivar_access_using_property_syntax_suggest)
1597     << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1598     << FixItHint::CreateReplacement(OpLoc, "->");
1599     return ExprError();
1600   }
1601 
1602   Diag(MemberLoc, diag::err_property_not_found)
1603     << MemberName << QualType(OPT, 0);
1604   if (Setter)
1605     Diag(Setter->getLocation(), diag::note_getter_unavailable)
1606           << MemberName << BaseExpr->getSourceRange();
1607   return ExprError();
1608 }
1609 
1610 
1611 
1612 ExprResult Sema::
1613 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1614                           IdentifierInfo &propertyName,
1615                           SourceLocation receiverNameLoc,
1616                           SourceLocation propertyNameLoc) {
1617 
1618   IdentifierInfo *receiverNamePtr = &receiverName;
1619   ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1620                                                   receiverNameLoc);
1621 
1622   bool IsSuper = false;
1623   if (IFace == 0) {
1624     // If the "receiver" is 'super' in a method, handle it as an expression-like
1625     // property reference.
1626     if (receiverNamePtr->isStr("super")) {
1627       IsSuper = true;
1628 
1629       if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
1630         if (CurMethod->isInstanceMethod()) {
1631           ObjCInterfaceDecl *Super =
1632             CurMethod->getClassInterface()->getSuperClass();
1633           if (!Super) {
1634             // The current class does not have a superclass.
1635             Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
1636             << CurMethod->getClassInterface()->getIdentifier();
1637             return ExprError();
1638           }
1639           QualType T = Context.getObjCInterfaceType(Super);
1640           T = Context.getObjCObjectPointerType(T);
1641 
1642           return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
1643                                            /*BaseExpr*/0,
1644                                            SourceLocation()/*OpLoc*/,
1645                                            &propertyName,
1646                                            propertyNameLoc,
1647                                            receiverNameLoc, T, true);
1648         }
1649 
1650         // Otherwise, if this is a class method, try dispatching to our
1651         // superclass.
1652         IFace = CurMethod->getClassInterface()->getSuperClass();
1653       }
1654     }
1655 
1656     if (IFace == 0) {
1657       Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
1658       return ExprError();
1659     }
1660   }
1661 
1662   // Search for a declared property first.
1663   Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
1664   ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
1665 
1666   // If this reference is in an @implementation, check for 'private' methods.
1667   if (!Getter)
1668     if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1669       if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1670         if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
1671           Getter = ImpDecl->getClassMethod(Sel);
1672 
1673   if (Getter) {
1674     // FIXME: refactor/share with ActOnMemberReference().
1675     // Check if we can reference this property.
1676     if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1677       return ExprError();
1678   }
1679 
1680   // Look for the matching setter, in case it is needed.
1681   Selector SetterSel =
1682     SelectorTable::constructSetterName(PP.getIdentifierTable(),
1683                                        PP.getSelectorTable(), &propertyName);
1684 
1685   ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1686   if (!Setter) {
1687     // If this reference is in an @implementation, also check for 'private'
1688     // methods.
1689     if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1690       if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1691         if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
1692           Setter = ImpDecl->getClassMethod(SetterSel);
1693   }
1694   // Look through local category implementations associated with the class.
1695   if (!Setter)
1696     Setter = IFace->getCategoryClassMethod(SetterSel);
1697 
1698   if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1699     return ExprError();
1700 
1701   if (Getter || Setter) {
1702     if (IsSuper)
1703     return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1704                                                    Context.PseudoObjectTy,
1705                                                    VK_LValue, OK_ObjCProperty,
1706                                                    propertyNameLoc,
1707                                                    receiverNameLoc,
1708                                           Context.getObjCInterfaceType(IFace)));
1709 
1710     return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1711                                                    Context.PseudoObjectTy,
1712                                                    VK_LValue, OK_ObjCProperty,
1713                                                    propertyNameLoc,
1714                                                    receiverNameLoc, IFace));
1715   }
1716   return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1717                      << &propertyName << Context.getObjCInterfaceType(IFace));
1718 }
1719 
1720 namespace {
1721 
1722 class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1723  public:
1724   ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1725     // Determine whether "super" is acceptable in the current context.
1726     if (Method && Method->getClassInterface())
1727       WantObjCSuper = Method->getClassInterface()->getSuperClass();
1728   }
1729 
1730   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1731     return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1732         candidate.isKeyword("super");
1733   }
1734 };
1735 
1736 }
1737 
1738 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
1739                                                IdentifierInfo *Name,
1740                                                SourceLocation NameLoc,
1741                                                bool IsSuper,
1742                                                bool HasTrailingDot,
1743                                                ParsedType &ReceiverType) {
1744   ReceiverType = ParsedType();
1745 
1746   // If the identifier is "super" and there is no trailing dot, we're
1747   // messaging super. If the identifier is "super" and there is a
1748   // trailing dot, it's an instance message.
1749   if (IsSuper && S->isInObjcMethodScope())
1750     return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
1751 
1752   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1753   LookupName(Result, S);
1754 
1755   switch (Result.getResultKind()) {
1756   case LookupResult::NotFound:
1757     // Normal name lookup didn't find anything. If we're in an
1758     // Objective-C method, look for ivars. If we find one, we're done!
1759     // FIXME: This is a hack. Ivar lookup should be part of normal
1760     // lookup.
1761     if (ObjCMethodDecl *Method = getCurMethodDecl()) {
1762       if (!Method->getClassInterface()) {
1763         // Fall back: let the parser try to parse it as an instance message.
1764         return ObjCInstanceMessage;
1765       }
1766 
1767       ObjCInterfaceDecl *ClassDeclared;
1768       if (Method->getClassInterface()->lookupInstanceVariable(Name,
1769                                                               ClassDeclared))
1770         return ObjCInstanceMessage;
1771     }
1772 
1773     // Break out; we'll perform typo correction below.
1774     break;
1775 
1776   case LookupResult::NotFoundInCurrentInstantiation:
1777   case LookupResult::FoundOverloaded:
1778   case LookupResult::FoundUnresolvedValue:
1779   case LookupResult::Ambiguous:
1780     Result.suppressDiagnostics();
1781     return ObjCInstanceMessage;
1782 
1783   case LookupResult::Found: {
1784     // If the identifier is a class or not, and there is a trailing dot,
1785     // it's an instance message.
1786     if (HasTrailingDot)
1787       return ObjCInstanceMessage;
1788     // We found something. If it's a type, then we have a class
1789     // message. Otherwise, it's an instance message.
1790     NamedDecl *ND = Result.getFoundDecl();
1791     QualType T;
1792     if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1793       T = Context.getObjCInterfaceType(Class);
1794     else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
1795       T = Context.getTypeDeclType(Type);
1796     else
1797       return ObjCInstanceMessage;
1798 
1799     //  We have a class message, and T is the type we're
1800     //  messaging. Build source-location information for it.
1801     TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1802     ReceiverType = CreateParsedType(T, TSInfo);
1803     return ObjCClassMessage;
1804   }
1805   }
1806 
1807   ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
1808   if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
1809                                              Result.getLookupKind(), S, NULL,
1810                                              Validator)) {
1811     if (Corrected.isKeyword()) {
1812       // If we've found the keyword "super" (the only keyword that would be
1813       // returned by CorrectTypo), this is a send to super.
1814       Diag(NameLoc, diag::err_unknown_receiver_suggest)
1815         << Name << Corrected.getCorrection()
1816         << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
1817       return ObjCSuperMessage;
1818     } else if (ObjCInterfaceDecl *Class =
1819                Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1820       // If we found a declaration, correct when it refers to an Objective-C
1821       // class.
1822       Diag(NameLoc, diag::err_unknown_receiver_suggest)
1823         << Name << Corrected.getCorrection()
1824         << FixItHint::CreateReplacement(SourceRange(NameLoc),
1825                                         Class->getNameAsString());
1826       Diag(Class->getLocation(), diag::note_previous_decl)
1827         << Corrected.getCorrection();
1828 
1829       QualType T = Context.getObjCInterfaceType(Class);
1830       TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1831       ReceiverType = CreateParsedType(T, TSInfo);
1832       return ObjCClassMessage;
1833     }
1834   }
1835 
1836   // Fall back: let the parser try to parse it as an instance message.
1837   return ObjCInstanceMessage;
1838 }
1839 
1840 ExprResult Sema::ActOnSuperMessage(Scope *S,
1841                                    SourceLocation SuperLoc,
1842                                    Selector Sel,
1843                                    SourceLocation LBracLoc,
1844                                    ArrayRef<SourceLocation> SelectorLocs,
1845                                    SourceLocation RBracLoc,
1846                                    MultiExprArg Args) {
1847   // Determine whether we are inside a method or not.
1848   ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
1849   if (!Method) {
1850     Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1851     return ExprError();
1852   }
1853 
1854   ObjCInterfaceDecl *Class = Method->getClassInterface();
1855   if (!Class) {
1856     Diag(SuperLoc, diag::error_no_super_class_message)
1857       << Method->getDeclName();
1858     return ExprError();
1859   }
1860 
1861   ObjCInterfaceDecl *Super = Class->getSuperClass();
1862   if (!Super) {
1863     // The current class does not have a superclass.
1864     Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1865       << Class->getIdentifier();
1866     return ExprError();
1867   }
1868 
1869   // We are in a method whose class has a superclass, so 'super'
1870   // is acting as a keyword.
1871   if (Method->getSelector() == Sel)
1872     getCurFunction()->ObjCShouldCallSuper = false;
1873 
1874   if (Method->isInstanceMethod()) {
1875     // Since we are in an instance method, this is an instance
1876     // message to the superclass instance.
1877     QualType SuperTy = Context.getObjCInterfaceType(Super);
1878     SuperTy = Context.getObjCObjectPointerType(SuperTy);
1879     return BuildInstanceMessage(0, SuperTy, SuperLoc,
1880                                 Sel, /*Method=*/0,
1881                                 LBracLoc, SelectorLocs, RBracLoc, Args);
1882   }
1883 
1884   // Since we are in a class method, this is a class message to
1885   // the superclass.
1886   return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1887                            Context.getObjCInterfaceType(Super),
1888                            SuperLoc, Sel, /*Method=*/0,
1889                            LBracLoc, SelectorLocs, RBracLoc, Args);
1890 }
1891 
1892 
1893 ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
1894                                            bool isSuperReceiver,
1895                                            SourceLocation Loc,
1896                                            Selector Sel,
1897                                            ObjCMethodDecl *Method,
1898                                            MultiExprArg Args) {
1899   TypeSourceInfo *receiverTypeInfo = 0;
1900   if (!ReceiverType.isNull())
1901     receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
1902 
1903   return BuildClassMessage(receiverTypeInfo, ReceiverType,
1904                           /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
1905                            Sel, Method, Loc, Loc, Loc, Args,
1906                            /*isImplicit=*/true);
1907 
1908 }
1909 
1910 static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
1911                                unsigned DiagID,
1912                                bool (*refactor)(const ObjCMessageExpr *,
1913                                               const NSAPI &, edit::Commit &)) {
1914   SourceLocation MsgLoc = Msg->getExprLoc();
1915   if (S.Diags.getDiagnosticLevel(DiagID, MsgLoc) == DiagnosticsEngine::Ignored)
1916     return;
1917 
1918   SourceManager &SM = S.SourceMgr;
1919   edit::Commit ECommit(SM, S.LangOpts);
1920   if (refactor(Msg,*S.NSAPIObj, ECommit)) {
1921     DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
1922                         << Msg->getSelector() << Msg->getSourceRange();
1923     // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
1924     if (!ECommit.isCommitable())
1925       return;
1926     for (edit::Commit::edit_iterator
1927            I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
1928       const edit::Commit::Edit &Edit = *I;
1929       switch (Edit.Kind) {
1930       case edit::Commit::Act_Insert:
1931         Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
1932                                                         Edit.Text,
1933                                                         Edit.BeforePrev));
1934         break;
1935       case edit::Commit::Act_InsertFromRange:
1936         Builder.AddFixItHint(
1937             FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
1938                                                 Edit.getInsertFromRange(SM),
1939                                                 Edit.BeforePrev));
1940         break;
1941       case edit::Commit::Act_Remove:
1942         Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
1943         break;
1944       }
1945     }
1946   }
1947 }
1948 
1949 static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
1950   applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
1951                      edit::rewriteObjCRedundantCallWithLiteral);
1952 }
1953 
1954 /// \brief Build an Objective-C class message expression.
1955 ///
1956 /// This routine takes care of both normal class messages and
1957 /// class messages to the superclass.
1958 ///
1959 /// \param ReceiverTypeInfo Type source information that describes the
1960 /// receiver of this message. This may be NULL, in which case we are
1961 /// sending to the superclass and \p SuperLoc must be a valid source
1962 /// location.
1963 
1964 /// \param ReceiverType The type of the object receiving the
1965 /// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1966 /// type as that refers to. For a superclass send, this is the type of
1967 /// the superclass.
1968 ///
1969 /// \param SuperLoc The location of the "super" keyword in a
1970 /// superclass message.
1971 ///
1972 /// \param Sel The selector to which the message is being sent.
1973 ///
1974 /// \param Method The method that this class message is invoking, if
1975 /// already known.
1976 ///
1977 /// \param LBracLoc The location of the opening square bracket ']'.
1978 ///
1979 /// \param RBracLoc The location of the closing square bracket ']'.
1980 ///
1981 /// \param ArgsIn The message arguments.
1982 ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
1983                                    QualType ReceiverType,
1984                                    SourceLocation SuperLoc,
1985                                    Selector Sel,
1986                                    ObjCMethodDecl *Method,
1987                                    SourceLocation LBracLoc,
1988                                    ArrayRef<SourceLocation> SelectorLocs,
1989                                    SourceLocation RBracLoc,
1990                                    MultiExprArg ArgsIn,
1991                                    bool isImplicit) {
1992   SourceLocation Loc = SuperLoc.isValid()? SuperLoc
1993     : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
1994   if (LBracLoc.isInvalid()) {
1995     Diag(Loc, diag::err_missing_open_square_message_send)
1996       << FixItHint::CreateInsertion(Loc, "[");
1997     LBracLoc = Loc;
1998   }
1999 
2000   if (ReceiverType->isDependentType()) {
2001     // If the receiver type is dependent, we can't type-check anything
2002     // at this point. Build a dependent expression.
2003     unsigned NumArgs = ArgsIn.size();
2004     Expr **Args = ArgsIn.data();
2005     assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2006     return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
2007                                          VK_RValue, LBracLoc, ReceiverTypeInfo,
2008                                          Sel, SelectorLocs, /*Method=*/0,
2009                                          makeArrayRef(Args, NumArgs),RBracLoc,
2010                                          isImplicit));
2011   }
2012 
2013   // Find the class to which we are sending this message.
2014   ObjCInterfaceDecl *Class = 0;
2015   const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2016   if (!ClassType || !(Class = ClassType->getInterface())) {
2017     Diag(Loc, diag::err_invalid_receiver_class_message)
2018       << ReceiverType;
2019     return ExprError();
2020   }
2021   assert(Class && "We don't know which class we're messaging?");
2022   // objc++ diagnoses during typename annotation.
2023   if (!getLangOpts().CPlusPlus)
2024     (void)DiagnoseUseOfDecl(Class, Loc);
2025   // Find the method we are messaging.
2026   if (!Method) {
2027     SourceRange TypeRange
2028       = SuperLoc.isValid()? SourceRange(SuperLoc)
2029                           : ReceiverTypeInfo->getTypeLoc().getSourceRange();
2030     if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
2031                             (getLangOpts().ObjCAutoRefCount
2032                                ? diag::err_arc_receiver_forward_class
2033                                : diag::warn_receiver_forward_class),
2034                             TypeRange)) {
2035       // A forward class used in messaging is treated as a 'Class'
2036       Method = LookupFactoryMethodInGlobalPool(Sel,
2037                                                SourceRange(LBracLoc, RBracLoc));
2038       if (Method && !getLangOpts().ObjCAutoRefCount)
2039         Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2040           << Method->getDeclName();
2041     }
2042     if (!Method)
2043       Method = Class->lookupClassMethod(Sel);
2044 
2045     // If we have an implementation in scope, check "private" methods.
2046     if (!Method)
2047       Method = Class->lookupPrivateClassMethod(Sel);
2048 
2049     if (Method && DiagnoseUseOfDecl(Method, Loc))
2050       return ExprError();
2051   }
2052 
2053   // Check the argument types and determine the result type.
2054   QualType ReturnType;
2055   ExprValueKind VK = VK_RValue;
2056 
2057   unsigned NumArgs = ArgsIn.size();
2058   Expr **Args = ArgsIn.data();
2059   if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, SelectorLocs,
2060                                 Method, true,
2061                                 SuperLoc.isValid(), LBracLoc, RBracLoc,
2062                                 ReturnType, VK))
2063     return ExprError();
2064 
2065   if (Method && !Method->getResultType()->isVoidType() &&
2066       RequireCompleteType(LBracLoc, Method->getResultType(),
2067                           diag::err_illegal_message_expr_incomplete_type))
2068     return ExprError();
2069 
2070   // Construct the appropriate ObjCMessageExpr.
2071   ObjCMessageExpr *Result;
2072   if (SuperLoc.isValid())
2073     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2074                                      SuperLoc, /*IsInstanceSuper=*/false,
2075                                      ReceiverType, Sel, SelectorLocs,
2076                                      Method, makeArrayRef(Args, NumArgs),
2077                                      RBracLoc, isImplicit);
2078   else {
2079     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2080                                      ReceiverTypeInfo, Sel, SelectorLocs,
2081                                      Method, makeArrayRef(Args, NumArgs),
2082                                      RBracLoc, isImplicit);
2083     if (!isImplicit)
2084       checkCocoaAPI(*this, Result);
2085   }
2086   return MaybeBindToTemporary(Result);
2087 }
2088 
2089 // ActOnClassMessage - used for both unary and keyword messages.
2090 // ArgExprs is optional - if it is present, the number of expressions
2091 // is obtained from Sel.getNumArgs().
2092 ExprResult Sema::ActOnClassMessage(Scope *S,
2093                                    ParsedType Receiver,
2094                                    Selector Sel,
2095                                    SourceLocation LBracLoc,
2096                                    ArrayRef<SourceLocation> SelectorLocs,
2097                                    SourceLocation RBracLoc,
2098                                    MultiExprArg Args) {
2099   TypeSourceInfo *ReceiverTypeInfo;
2100   QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2101   if (ReceiverType.isNull())
2102     return ExprError();
2103 
2104 
2105   if (!ReceiverTypeInfo)
2106     ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2107 
2108   return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
2109                            /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
2110                            LBracLoc, SelectorLocs, RBracLoc, Args);
2111 }
2112 
2113 ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2114                                               QualType ReceiverType,
2115                                               SourceLocation Loc,
2116                                               Selector Sel,
2117                                               ObjCMethodDecl *Method,
2118                                               MultiExprArg Args) {
2119   return BuildInstanceMessage(Receiver, ReceiverType,
2120                               /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2121                               Sel, Method, Loc, Loc, Loc, Args,
2122                               /*isImplicit=*/true);
2123 }
2124 
2125 /// \brief Build an Objective-C instance message expression.
2126 ///
2127 /// This routine takes care of both normal instance messages and
2128 /// instance messages to the superclass instance.
2129 ///
2130 /// \param Receiver The expression that computes the object that will
2131 /// receive this message. This may be empty, in which case we are
2132 /// sending to the superclass instance and \p SuperLoc must be a valid
2133 /// source location.
2134 ///
2135 /// \param ReceiverType The (static) type of the object receiving the
2136 /// message. When a \p Receiver expression is provided, this is the
2137 /// same type as that expression. For a superclass instance send, this
2138 /// is a pointer to the type of the superclass.
2139 ///
2140 /// \param SuperLoc The location of the "super" keyword in a
2141 /// superclass instance message.
2142 ///
2143 /// \param Sel The selector to which the message is being sent.
2144 ///
2145 /// \param Method The method that this instance message is invoking, if
2146 /// already known.
2147 ///
2148 /// \param LBracLoc The location of the opening square bracket ']'.
2149 ///
2150 /// \param RBracLoc The location of the closing square bracket ']'.
2151 ///
2152 /// \param ArgsIn The message arguments.
2153 ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
2154                                       QualType ReceiverType,
2155                                       SourceLocation SuperLoc,
2156                                       Selector Sel,
2157                                       ObjCMethodDecl *Method,
2158                                       SourceLocation LBracLoc,
2159                                       ArrayRef<SourceLocation> SelectorLocs,
2160                                       SourceLocation RBracLoc,
2161                                       MultiExprArg ArgsIn,
2162                                       bool isImplicit) {
2163   // The location of the receiver.
2164   SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
2165 
2166   if (LBracLoc.isInvalid()) {
2167     Diag(Loc, diag::err_missing_open_square_message_send)
2168       << FixItHint::CreateInsertion(Loc, "[");
2169     LBracLoc = Loc;
2170   }
2171 
2172   // If we have a receiver expression, perform appropriate promotions
2173   // and determine receiver type.
2174   if (Receiver) {
2175     if (Receiver->hasPlaceholderType()) {
2176       ExprResult Result;
2177       if (Receiver->getType() == Context.UnknownAnyTy)
2178         Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2179       else
2180         Result = CheckPlaceholderExpr(Receiver);
2181       if (Result.isInvalid()) return ExprError();
2182       Receiver = Result.take();
2183     }
2184 
2185     if (Receiver->isTypeDependent()) {
2186       // If the receiver is type-dependent, we can't type-check anything
2187       // at this point. Build a dependent expression.
2188       unsigned NumArgs = ArgsIn.size();
2189       Expr **Args = ArgsIn.data();
2190       assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2191       return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
2192                                            VK_RValue, LBracLoc, Receiver, Sel,
2193                                            SelectorLocs, /*Method=*/0,
2194                                            makeArrayRef(Args, NumArgs),
2195                                            RBracLoc, isImplicit));
2196     }
2197 
2198     // If necessary, apply function/array conversion to the receiver.
2199     // C99 6.7.5.3p[7,8].
2200     ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2201     if (Result.isInvalid())
2202       return ExprError();
2203     Receiver = Result.take();
2204     ReceiverType = Receiver->getType();
2205 
2206     // If the receiver is an ObjC pointer, a block pointer, or an
2207     // __attribute__((NSObject)) pointer, we don't need to do any
2208     // special conversion in order to look up a receiver.
2209     if (ReceiverType->isObjCRetainableType()) {
2210       // do nothing
2211     } else if (!getLangOpts().ObjCAutoRefCount &&
2212                !Context.getObjCIdType().isNull() &&
2213                (ReceiverType->isPointerType() ||
2214                 ReceiverType->isIntegerType())) {
2215       // Implicitly convert integers and pointers to 'id' but emit a warning.
2216       // But not in ARC.
2217       Diag(Loc, diag::warn_bad_receiver_type)
2218         << ReceiverType
2219         << Receiver->getSourceRange();
2220       if (ReceiverType->isPointerType()) {
2221         Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2222                                      CK_CPointerToObjCPointerCast).take();
2223       } else {
2224         // TODO: specialized warning on null receivers?
2225         bool IsNull = Receiver->isNullPointerConstant(Context,
2226                                               Expr::NPC_ValueDependentIsNull);
2227         CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2228         Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2229                                      Kind).take();
2230       }
2231       ReceiverType = Receiver->getType();
2232     } else if (getLangOpts().CPlusPlus) {
2233       ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2234       if (result.isUsable()) {
2235         Receiver = result.take();
2236         ReceiverType = Receiver->getType();
2237       }
2238     }
2239   }
2240 
2241   // There's a somewhat weird interaction here where we assume that we
2242   // won't actually have a method unless we also don't need to do some
2243   // of the more detailed type-checking on the receiver.
2244 
2245   if (!Method) {
2246     // Handle messages to id.
2247     bool receiverIsId = ReceiverType->isObjCIdType();
2248     if (receiverIsId || ReceiverType->isBlockPointerType() ||
2249         (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2250       Method = LookupInstanceMethodInGlobalPool(Sel,
2251                                                 SourceRange(LBracLoc, RBracLoc),
2252                                                 receiverIsId);
2253       if (!Method)
2254         Method = LookupFactoryMethodInGlobalPool(Sel,
2255                                                  SourceRange(LBracLoc,RBracLoc),
2256                                                  receiverIsId);
2257     } else if (ReceiverType->isObjCClassType() ||
2258                ReceiverType->isObjCQualifiedClassType()) {
2259       // Handle messages to Class.
2260       // We allow sending a message to a qualified Class ("Class<foo>"), which
2261       // is ok as long as one of the protocols implements the selector (if not, warn).
2262       if (const ObjCObjectPointerType *QClassTy
2263             = ReceiverType->getAsObjCQualifiedClassType()) {
2264         // Search protocols for class methods.
2265         Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2266         if (!Method) {
2267           Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2268           // warn if instance method found for a Class message.
2269           if (Method) {
2270             Diag(Loc, diag::warn_instance_method_on_class_found)
2271               << Method->getSelector() << Sel;
2272             Diag(Method->getLocation(), diag::note_method_declared_at)
2273               << Method->getDeclName();
2274           }
2275         }
2276       } else {
2277         if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2278           if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2279             // First check the public methods in the class interface.
2280             Method = ClassDecl->lookupClassMethod(Sel);
2281 
2282             if (!Method)
2283               Method = ClassDecl->lookupPrivateClassMethod(Sel);
2284           }
2285           if (Method && DiagnoseUseOfDecl(Method, Loc))
2286             return ExprError();
2287         }
2288         if (!Method) {
2289           // If not messaging 'self', look for any factory method named 'Sel'.
2290           if (!Receiver || !isSelfExpr(Receiver)) {
2291             Method = LookupFactoryMethodInGlobalPool(Sel,
2292                                                 SourceRange(LBracLoc, RBracLoc),
2293                                                      true);
2294             if (!Method) {
2295               // If no class (factory) method was found, check if an _instance_
2296               // method of the same name exists in the root class only.
2297               Method = LookupInstanceMethodInGlobalPool(Sel,
2298                                                SourceRange(LBracLoc, RBracLoc),
2299                                                         true);
2300               if (Method)
2301                   if (const ObjCInterfaceDecl *ID =
2302                       dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2303                     if (ID->getSuperClass())
2304                       Diag(Loc, diag::warn_root_inst_method_not_found)
2305                       << Sel << SourceRange(LBracLoc, RBracLoc);
2306                   }
2307             }
2308           }
2309         }
2310       }
2311     } else {
2312       ObjCInterfaceDecl* ClassDecl = 0;
2313 
2314       // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2315       // long as one of the protocols implements the selector (if not, warn).
2316       // And as long as message is not deprecated/unavailable (warn if it is).
2317       if (const ObjCObjectPointerType *QIdTy
2318                                    = ReceiverType->getAsObjCQualifiedIdType()) {
2319         // Search protocols for instance methods.
2320         Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2321         if (!Method)
2322           Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
2323         if (Method && DiagnoseUseOfDecl(Method, Loc))
2324           return ExprError();
2325       } else if (const ObjCObjectPointerType *OCIType
2326                    = ReceiverType->getAsObjCInterfacePointerType()) {
2327         // We allow sending a message to a pointer to an interface (an object).
2328         ClassDecl = OCIType->getInterfaceDecl();
2329 
2330         // Try to complete the type. Under ARC, this is a hard error from which
2331         // we don't try to recover.
2332         const ObjCInterfaceDecl *forwardClass = 0;
2333         if (RequireCompleteType(Loc, OCIType->getPointeeType(),
2334               getLangOpts().ObjCAutoRefCount
2335                 ? diag::err_arc_receiver_forward_instance
2336                 : diag::warn_receiver_forward_instance,
2337                                 Receiver? Receiver->getSourceRange()
2338                                         : SourceRange(SuperLoc))) {
2339           if (getLangOpts().ObjCAutoRefCount)
2340             return ExprError();
2341 
2342           forwardClass = OCIType->getInterfaceDecl();
2343           Diag(Receiver ? Receiver->getLocStart()
2344                         : SuperLoc, diag::note_receiver_is_id);
2345           Method = 0;
2346         } else {
2347           Method = ClassDecl->lookupInstanceMethod(Sel);
2348         }
2349 
2350         if (!Method)
2351           // Search protocol qualifiers.
2352           Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2353 
2354         if (!Method) {
2355           // If we have implementations in scope, check "private" methods.
2356           Method = ClassDecl->lookupPrivateMethod(Sel);
2357 
2358           if (!Method && getLangOpts().ObjCAutoRefCount) {
2359             Diag(Loc, diag::err_arc_may_not_respond)
2360               << OCIType->getPointeeType() << Sel
2361               << SourceRange(SelectorLocs.front(), SelectorLocs.back());
2362             return ExprError();
2363           }
2364 
2365           if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
2366             // If we still haven't found a method, look in the global pool. This
2367             // behavior isn't very desirable, however we need it for GCC
2368             // compatibility. FIXME: should we deviate??
2369             if (OCIType->qual_empty()) {
2370               Method = LookupInstanceMethodInGlobalPool(Sel,
2371                                               SourceRange(LBracLoc, RBracLoc));
2372               if (Method && !forwardClass)
2373                 Diag(Loc, diag::warn_maynot_respond)
2374                   << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
2375             }
2376           }
2377         }
2378         if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
2379           return ExprError();
2380       } else {
2381         // Reject other random receiver types (e.g. structs).
2382         Diag(Loc, diag::err_bad_receiver_type)
2383           << ReceiverType << Receiver->getSourceRange();
2384         return ExprError();
2385       }
2386     }
2387   }
2388 
2389   // Check the message arguments.
2390   unsigned NumArgs = ArgsIn.size();
2391   Expr **Args = ArgsIn.data();
2392   QualType ReturnType;
2393   ExprValueKind VK = VK_RValue;
2394   bool ClassMessage = (ReceiverType->isObjCClassType() ||
2395                        ReceiverType->isObjCQualifiedClassType());
2396   if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel,
2397                                 SelectorLocs, Method,
2398                                 ClassMessage, SuperLoc.isValid(),
2399                                 LBracLoc, RBracLoc, ReturnType, VK))
2400     return ExprError();
2401 
2402   if (Method && !Method->getResultType()->isVoidType() &&
2403       RequireCompleteType(LBracLoc, Method->getResultType(),
2404                           diag::err_illegal_message_expr_incomplete_type))
2405     return ExprError();
2406 
2407   SourceLocation SelLoc = SelectorLocs.front();
2408 
2409   // In ARC, forbid the user from sending messages to
2410   // retain/release/autorelease/dealloc/retainCount explicitly.
2411   if (getLangOpts().ObjCAutoRefCount) {
2412     ObjCMethodFamily family =
2413       (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2414     switch (family) {
2415     case OMF_init:
2416       if (Method)
2417         checkInitMethod(Method, ReceiverType);
2418 
2419     case OMF_None:
2420     case OMF_alloc:
2421     case OMF_copy:
2422     case OMF_finalize:
2423     case OMF_mutableCopy:
2424     case OMF_new:
2425     case OMF_self:
2426       break;
2427 
2428     case OMF_dealloc:
2429     case OMF_retain:
2430     case OMF_release:
2431     case OMF_autorelease:
2432     case OMF_retainCount:
2433       Diag(Loc, diag::err_arc_illegal_explicit_message)
2434         << Sel << SelLoc;
2435       break;
2436 
2437     case OMF_performSelector:
2438       if (Method && NumArgs >= 1) {
2439         if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2440           Selector ArgSel = SelExp->getSelector();
2441           ObjCMethodDecl *SelMethod =
2442             LookupInstanceMethodInGlobalPool(ArgSel,
2443                                              SelExp->getSourceRange());
2444           if (!SelMethod)
2445             SelMethod =
2446               LookupFactoryMethodInGlobalPool(ArgSel,
2447                                               SelExp->getSourceRange());
2448           if (SelMethod) {
2449             ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2450             switch (SelFamily) {
2451               case OMF_alloc:
2452               case OMF_copy:
2453               case OMF_mutableCopy:
2454               case OMF_new:
2455               case OMF_self:
2456               case OMF_init:
2457                 // Issue error, unless ns_returns_not_retained.
2458                 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2459                   // selector names a +1 method
2460                   Diag(SelLoc,
2461                        diag::err_arc_perform_selector_retains);
2462                   Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2463                     << SelMethod->getDeclName();
2464                 }
2465                 break;
2466               default:
2467                 // +0 call. OK. unless ns_returns_retained.
2468                 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2469                   // selector names a +1 method
2470                   Diag(SelLoc,
2471                        diag::err_arc_perform_selector_retains);
2472                   Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2473                     << SelMethod->getDeclName();
2474                 }
2475                 break;
2476             }
2477           }
2478         } else {
2479           // error (may leak).
2480           Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
2481           Diag(Args[0]->getExprLoc(), diag::note_used_here);
2482         }
2483       }
2484       break;
2485     }
2486   }
2487 
2488   // Construct the appropriate ObjCMessageExpr instance.
2489   ObjCMessageExpr *Result;
2490   if (SuperLoc.isValid())
2491     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2492                                      SuperLoc,  /*IsInstanceSuper=*/true,
2493                                      ReceiverType, Sel, SelectorLocs, Method,
2494                                      makeArrayRef(Args, NumArgs), RBracLoc,
2495                                      isImplicit);
2496   else {
2497     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2498                                      Receiver, Sel, SelectorLocs, Method,
2499                                      makeArrayRef(Args, NumArgs), RBracLoc,
2500                                      isImplicit);
2501     if (!isImplicit)
2502       checkCocoaAPI(*this, Result);
2503   }
2504 
2505   if (getLangOpts().ObjCAutoRefCount) {
2506     DiagnoseARCUseOfWeakReceiver(*this, Receiver);
2507 
2508     // In ARC, annotate delegate init calls.
2509     if (Result->getMethodFamily() == OMF_init &&
2510         (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2511       // Only consider init calls *directly* in init implementations,
2512       // not within blocks.
2513       ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2514       if (method && method->getMethodFamily() == OMF_init) {
2515         // The implicit assignment to self means we also don't want to
2516         // consume the result.
2517         Result->setDelegateInitCall(true);
2518         return Owned(Result);
2519       }
2520     }
2521 
2522     // In ARC, check for message sends which are likely to introduce
2523     // retain cycles.
2524     checkRetainCycles(Result);
2525 
2526     if (!isImplicit && Method) {
2527       if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
2528         bool IsWeak =
2529           Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
2530         if (!IsWeak && Sel.isUnarySelector())
2531           IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
2532 
2533         if (IsWeak) {
2534           DiagnosticsEngine::Level Level =
2535             Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
2536                                      LBracLoc);
2537           if (Level != DiagnosticsEngine::Ignored)
2538             getCurFunction()->recordUseOfWeak(Result, Prop);
2539 
2540         }
2541       }
2542     }
2543   }
2544 
2545   return MaybeBindToTemporary(Result);
2546 }
2547 
2548 static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
2549   if (ObjCSelectorExpr *OSE =
2550       dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
2551     Selector Sel = OSE->getSelector();
2552     SourceLocation Loc = OSE->getAtLoc();
2553     llvm::DenseMap<Selector, SourceLocation>::iterator Pos
2554     = S.ReferencedSelectors.find(Sel);
2555     if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
2556       S.ReferencedSelectors.erase(Pos);
2557   }
2558 }
2559 
2560 // ActOnInstanceMessage - used for both unary and keyword messages.
2561 // ArgExprs is optional - if it is present, the number of expressions
2562 // is obtained from Sel.getNumArgs().
2563 ExprResult Sema::ActOnInstanceMessage(Scope *S,
2564                                       Expr *Receiver,
2565                                       Selector Sel,
2566                                       SourceLocation LBracLoc,
2567                                       ArrayRef<SourceLocation> SelectorLocs,
2568                                       SourceLocation RBracLoc,
2569                                       MultiExprArg Args) {
2570   if (!Receiver)
2571     return ExprError();
2572 
2573   // A ParenListExpr can show up while doing error recovery with invalid code.
2574   if (isa<ParenListExpr>(Receiver)) {
2575     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
2576     if (Result.isInvalid()) return ExprError();
2577     Receiver = Result.take();
2578   }
2579 
2580   if (RespondsToSelectorSel.isNull()) {
2581     IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
2582     RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
2583   }
2584   if (Sel == RespondsToSelectorSel)
2585     RemoveSelectorFromWarningCache(*this, Args[0]);
2586 
2587   return BuildInstanceMessage(Receiver, Receiver->getType(),
2588                               /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
2589                               LBracLoc, SelectorLocs, RBracLoc, Args);
2590 }
2591 
2592 enum ARCConversionTypeClass {
2593   /// int, void, struct A
2594   ACTC_none,
2595 
2596   /// id, void (^)()
2597   ACTC_retainable,
2598 
2599   /// id*, id***, void (^*)(),
2600   ACTC_indirectRetainable,
2601 
2602   /// void* might be a normal C type, or it might a CF type.
2603   ACTC_voidPtr,
2604 
2605   /// struct A*
2606   ACTC_coreFoundation
2607 };
2608 static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2609   return (ACTC == ACTC_retainable ||
2610           ACTC == ACTC_coreFoundation ||
2611           ACTC == ACTC_voidPtr);
2612 }
2613 static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2614   return ACTC == ACTC_none ||
2615          ACTC == ACTC_voidPtr ||
2616          ACTC == ACTC_coreFoundation;
2617 }
2618 
2619 static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
2620   bool isIndirect = false;
2621 
2622   // Ignore an outermost reference type.
2623   if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
2624     type = ref->getPointeeType();
2625     isIndirect = true;
2626   }
2627 
2628   // Drill through pointers and arrays recursively.
2629   while (true) {
2630     if (const PointerType *ptr = type->getAs<PointerType>()) {
2631       type = ptr->getPointeeType();
2632 
2633       // The first level of pointer may be the innermost pointer on a CF type.
2634       if (!isIndirect) {
2635         if (type->isVoidType()) return ACTC_voidPtr;
2636         if (type->isRecordType()) return ACTC_coreFoundation;
2637       }
2638     } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2639       type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2640     } else {
2641       break;
2642     }
2643     isIndirect = true;
2644   }
2645 
2646   if (isIndirect) {
2647     if (type->isObjCARCBridgableType())
2648       return ACTC_indirectRetainable;
2649     return ACTC_none;
2650   }
2651 
2652   if (type->isObjCARCBridgableType())
2653     return ACTC_retainable;
2654 
2655   return ACTC_none;
2656 }
2657 
2658 namespace {
2659   /// A result from the cast checker.
2660   enum ACCResult {
2661     /// Cannot be casted.
2662     ACC_invalid,
2663 
2664     /// Can be safely retained or not retained.
2665     ACC_bottom,
2666 
2667     /// Can be casted at +0.
2668     ACC_plusZero,
2669 
2670     /// Can be casted at +1.
2671     ACC_plusOne
2672   };
2673   ACCResult merge(ACCResult left, ACCResult right) {
2674     if (left == right) return left;
2675     if (left == ACC_bottom) return right;
2676     if (right == ACC_bottom) return left;
2677     return ACC_invalid;
2678   }
2679 
2680   /// A checker which white-lists certain expressions whose conversion
2681   /// to or from retainable type would otherwise be forbidden in ARC.
2682   class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2683     typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2684 
2685     ASTContext &Context;
2686     ARCConversionTypeClass SourceClass;
2687     ARCConversionTypeClass TargetClass;
2688     bool Diagnose;
2689 
2690     static bool isCFType(QualType type) {
2691       // Someday this can use ns_bridged.  For now, it has to do this.
2692       return type->isCARCBridgableType();
2693     }
2694 
2695   public:
2696     ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
2697                    ARCConversionTypeClass target, bool diagnose)
2698       : Context(Context), SourceClass(source), TargetClass(target),
2699         Diagnose(diagnose) {}
2700 
2701     using super::Visit;
2702     ACCResult Visit(Expr *e) {
2703       return super::Visit(e->IgnoreParens());
2704     }
2705 
2706     ACCResult VisitStmt(Stmt *s) {
2707       return ACC_invalid;
2708     }
2709 
2710     /// Null pointer constants can be casted however you please.
2711     ACCResult VisitExpr(Expr *e) {
2712       if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2713         return ACC_bottom;
2714       return ACC_invalid;
2715     }
2716 
2717     /// Objective-C string literals can be safely casted.
2718     ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2719       // If we're casting to any retainable type, go ahead.  Global
2720       // strings are immune to retains, so this is bottom.
2721       if (isAnyRetainable(TargetClass)) return ACC_bottom;
2722 
2723       return ACC_invalid;
2724     }
2725 
2726     /// Look through certain implicit and explicit casts.
2727     ACCResult VisitCastExpr(CastExpr *e) {
2728       switch (e->getCastKind()) {
2729         case CK_NullToPointer:
2730           return ACC_bottom;
2731 
2732         case CK_NoOp:
2733         case CK_LValueToRValue:
2734         case CK_BitCast:
2735         case CK_CPointerToObjCPointerCast:
2736         case CK_BlockPointerToObjCPointerCast:
2737         case CK_AnyPointerToBlockPointerCast:
2738           return Visit(e->getSubExpr());
2739 
2740         default:
2741           return ACC_invalid;
2742       }
2743     }
2744 
2745     /// Look through unary extension.
2746     ACCResult VisitUnaryExtension(UnaryOperator *e) {
2747       return Visit(e->getSubExpr());
2748     }
2749 
2750     /// Ignore the LHS of a comma operator.
2751     ACCResult VisitBinComma(BinaryOperator *e) {
2752       return Visit(e->getRHS());
2753     }
2754 
2755     /// Conditional operators are okay if both sides are okay.
2756     ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2757       ACCResult left = Visit(e->getTrueExpr());
2758       if (left == ACC_invalid) return ACC_invalid;
2759       return merge(left, Visit(e->getFalseExpr()));
2760     }
2761 
2762     /// Look through pseudo-objects.
2763     ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2764       // If we're getting here, we should always have a result.
2765       return Visit(e->getResultExpr());
2766     }
2767 
2768     /// Statement expressions are okay if their result expression is okay.
2769     ACCResult VisitStmtExpr(StmtExpr *e) {
2770       return Visit(e->getSubStmt()->body_back());
2771     }
2772 
2773     /// Some declaration references are okay.
2774     ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
2775       // References to global constants from system headers are okay.
2776       // These are things like 'kCFStringTransformToLatin'.  They are
2777       // can also be assumed to be immune to retains.
2778       VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
2779       if (isAnyRetainable(TargetClass) &&
2780           isAnyRetainable(SourceClass) &&
2781           var &&
2782           var->getStorageClass() == SC_Extern &&
2783           var->getType().isConstQualified() &&
2784           Context.getSourceManager().isInSystemHeader(var->getLocation())) {
2785         return ACC_bottom;
2786       }
2787 
2788       // Nothing else.
2789       return ACC_invalid;
2790     }
2791 
2792     /// Some calls are okay.
2793     ACCResult VisitCallExpr(CallExpr *e) {
2794       if (FunctionDecl *fn = e->getDirectCallee())
2795         if (ACCResult result = checkCallToFunction(fn))
2796           return result;
2797 
2798       return super::VisitCallExpr(e);
2799     }
2800 
2801     ACCResult checkCallToFunction(FunctionDecl *fn) {
2802       // Require a CF*Ref return type.
2803       if (!isCFType(fn->getResultType()))
2804         return ACC_invalid;
2805 
2806       if (!isAnyRetainable(TargetClass))
2807         return ACC_invalid;
2808 
2809       // Honor an explicit 'not retained' attribute.
2810       if (fn->hasAttr<CFReturnsNotRetainedAttr>())
2811         return ACC_plusZero;
2812 
2813       // Honor an explicit 'retained' attribute, except that for
2814       // now we're not going to permit implicit handling of +1 results,
2815       // because it's a bit frightening.
2816       if (fn->hasAttr<CFReturnsRetainedAttr>())
2817         return Diagnose ? ACC_plusOne
2818                         : ACC_invalid; // ACC_plusOne if we start accepting this
2819 
2820       // Recognize this specific builtin function, which is used by CFSTR.
2821       unsigned builtinID = fn->getBuiltinID();
2822       if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
2823         return ACC_bottom;
2824 
2825       // Otherwise, don't do anything implicit with an unaudited function.
2826       if (!fn->hasAttr<CFAuditedTransferAttr>())
2827         return ACC_invalid;
2828 
2829       // Otherwise, it's +0 unless it follows the create convention.
2830       if (ento::coreFoundation::followsCreateRule(fn))
2831         return Diagnose ? ACC_plusOne
2832                         : ACC_invalid; // ACC_plusOne if we start accepting this
2833 
2834       return ACC_plusZero;
2835     }
2836 
2837     ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
2838       return checkCallToMethod(e->getMethodDecl());
2839     }
2840 
2841     ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
2842       ObjCMethodDecl *method;
2843       if (e->isExplicitProperty())
2844         method = e->getExplicitProperty()->getGetterMethodDecl();
2845       else
2846         method = e->getImplicitPropertyGetter();
2847       return checkCallToMethod(method);
2848     }
2849 
2850     ACCResult checkCallToMethod(ObjCMethodDecl *method) {
2851       if (!method) return ACC_invalid;
2852 
2853       // Check for message sends to functions returning CF types.  We
2854       // just obey the Cocoa conventions with these, even though the
2855       // return type is CF.
2856       if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType()))
2857         return ACC_invalid;
2858 
2859       // If the method is explicitly marked not-retained, it's +0.
2860       if (method->hasAttr<CFReturnsNotRetainedAttr>())
2861         return ACC_plusZero;
2862 
2863       // If the method is explicitly marked as returning retained, or its
2864       // selector follows a +1 Cocoa convention, treat it as +1.
2865       if (method->hasAttr<CFReturnsRetainedAttr>())
2866         return ACC_plusOne;
2867 
2868       switch (method->getSelector().getMethodFamily()) {
2869       case OMF_alloc:
2870       case OMF_copy:
2871       case OMF_mutableCopy:
2872       case OMF_new:
2873         return ACC_plusOne;
2874 
2875       default:
2876         // Otherwise, treat it as +0.
2877         return ACC_plusZero;
2878       }
2879     }
2880   };
2881 }
2882 
2883 bool Sema::isKnownName(StringRef name) {
2884   if (name.empty())
2885     return false;
2886   LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
2887                  Sema::LookupOrdinaryName);
2888   return LookupName(R, TUScope, false);
2889 }
2890 
2891 static void addFixitForObjCARCConversion(Sema &S,
2892                                          DiagnosticBuilder &DiagB,
2893                                          Sema::CheckedConversionKind CCK,
2894                                          SourceLocation afterLParen,
2895                                          QualType castType,
2896                                          Expr *castExpr,
2897                                          Expr *realCast,
2898                                          const char *bridgeKeyword,
2899                                          const char *CFBridgeName) {
2900   // We handle C-style and implicit casts here.
2901   switch (CCK) {
2902   case Sema::CCK_ImplicitConversion:
2903   case Sema::CCK_CStyleCast:
2904   case Sema::CCK_OtherCast:
2905     break;
2906   case Sema::CCK_FunctionalCast:
2907     return;
2908   }
2909 
2910   if (CFBridgeName) {
2911     if (CCK == Sema::CCK_OtherCast) {
2912       if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
2913         SourceRange range(NCE->getOperatorLoc(),
2914                           NCE->getAngleBrackets().getEnd());
2915         SmallString<32> BridgeCall;
2916 
2917         SourceManager &SM = S.getSourceManager();
2918         char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
2919         if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
2920           BridgeCall += ' ';
2921 
2922         BridgeCall += CFBridgeName;
2923         DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
2924       }
2925       return;
2926     }
2927     Expr *castedE = castExpr;
2928     if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
2929       castedE = CCE->getSubExpr();
2930     castedE = castedE->IgnoreImpCasts();
2931     SourceRange range = castedE->getSourceRange();
2932 
2933     SmallString<32> BridgeCall;
2934 
2935     SourceManager &SM = S.getSourceManager();
2936     char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
2937     if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
2938       BridgeCall += ' ';
2939 
2940     BridgeCall += CFBridgeName;
2941 
2942     if (isa<ParenExpr>(castedE)) {
2943       DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2944                          BridgeCall));
2945     } else {
2946       BridgeCall += '(';
2947       DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2948                                                     BridgeCall));
2949       DiagB.AddFixItHint(FixItHint::CreateInsertion(
2950                                        S.PP.getLocForEndOfToken(range.getEnd()),
2951                                        ")"));
2952     }
2953     return;
2954   }
2955 
2956   if (CCK == Sema::CCK_CStyleCast) {
2957     DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
2958   } else if (CCK == Sema::CCK_OtherCast) {
2959     if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
2960       std::string castCode = "(";
2961       castCode += bridgeKeyword;
2962       castCode += castType.getAsString();
2963       castCode += ")";
2964       SourceRange Range(NCE->getOperatorLoc(),
2965                         NCE->getAngleBrackets().getEnd());
2966       DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
2967     }
2968   } else {
2969     std::string castCode = "(";
2970     castCode += bridgeKeyword;
2971     castCode += castType.getAsString();
2972     castCode += ")";
2973     Expr *castedE = castExpr->IgnoreImpCasts();
2974     SourceRange range = castedE->getSourceRange();
2975     if (isa<ParenExpr>(castedE)) {
2976       DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2977                          castCode));
2978     } else {
2979       castCode += "(";
2980       DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2981                                                     castCode));
2982       DiagB.AddFixItHint(FixItHint::CreateInsertion(
2983                                        S.PP.getLocForEndOfToken(range.getEnd()),
2984                                        ")"));
2985     }
2986   }
2987 }
2988 
2989 static void
2990 diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
2991                           QualType castType, ARCConversionTypeClass castACTC,
2992                           Expr *castExpr, Expr *realCast,
2993                           ARCConversionTypeClass exprACTC,
2994                           Sema::CheckedConversionKind CCK) {
2995   SourceLocation loc =
2996     (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
2997 
2998   if (S.makeUnavailableInSystemHeader(loc,
2999                 "converts between Objective-C and C pointers in -fobjc-arc"))
3000     return;
3001 
3002   QualType castExprType = castExpr->getType();
3003 
3004   unsigned srcKind = 0;
3005   switch (exprACTC) {
3006   case ACTC_none:
3007   case ACTC_coreFoundation:
3008   case ACTC_voidPtr:
3009     srcKind = (castExprType->isPointerType() ? 1 : 0);
3010     break;
3011   case ACTC_retainable:
3012     srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3013     break;
3014   case ACTC_indirectRetainable:
3015     srcKind = 4;
3016     break;
3017   }
3018 
3019   // Check whether this could be fixed with a bridge cast.
3020   SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
3021   SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
3022 
3023   // Bridge from an ARC type to a CF type.
3024   if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
3025 
3026     S.Diag(loc, diag::err_arc_cast_requires_bridge)
3027       << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3028       << 2 // of C pointer type
3029       << castExprType
3030       << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3031       << castType
3032       << castRange
3033       << castExpr->getSourceRange();
3034     bool br = S.isKnownName("CFBridgingRelease");
3035     ACCResult CreateRule =
3036       ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3037     assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3038     if (CreateRule != ACC_plusOne)
3039     {
3040       DiagnosticBuilder DiagB =
3041         (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3042                               : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3043 
3044       addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3045                                    castType, castExpr, realCast, "__bridge ", 0);
3046     }
3047     if (CreateRule != ACC_plusZero)
3048     {
3049       DiagnosticBuilder DiagB =
3050         (CCK == Sema::CCK_OtherCast && !br) ?
3051           S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3052           S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3053                  diag::note_arc_bridge_transfer)
3054             << castExprType << br;
3055 
3056       addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3057                                    castType, castExpr, realCast, "__bridge_transfer ",
3058                                    br ? "CFBridgingRelease" : 0);
3059     }
3060 
3061     return;
3062   }
3063 
3064   // Bridge from a CF type to an ARC type.
3065   if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
3066     bool br = S.isKnownName("CFBridgingRetain");
3067     S.Diag(loc, diag::err_arc_cast_requires_bridge)
3068       << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3069       << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3070       << castExprType
3071       << 2 // to C pointer type
3072       << castType
3073       << castRange
3074       << castExpr->getSourceRange();
3075     ACCResult CreateRule =
3076       ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3077     assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3078     if (CreateRule != ACC_plusOne)
3079     {
3080       DiagnosticBuilder DiagB =
3081       (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3082                                : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3083       addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3084                                    castType, castExpr, realCast, "__bridge ", 0);
3085     }
3086     if (CreateRule != ACC_plusZero)
3087     {
3088       DiagnosticBuilder DiagB =
3089         (CCK == Sema::CCK_OtherCast && !br) ?
3090           S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3091           S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3092                  diag::note_arc_bridge_retained)
3093             << castType << br;
3094 
3095       addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3096                                    castType, castExpr, realCast, "__bridge_retained ",
3097                                    br ? "CFBridgingRetain" : 0);
3098     }
3099 
3100     return;
3101   }
3102 
3103   S.Diag(loc, diag::err_arc_mismatched_cast)
3104     << (CCK != Sema::CCK_ImplicitConversion)
3105     << srcKind << castExprType << castType
3106     << castRange << castExpr->getSourceRange();
3107 }
3108 
3109 Sema::ARCConversionResult
3110 Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
3111                              Expr *&castExpr, CheckedConversionKind CCK) {
3112   QualType castExprType = castExpr->getType();
3113 
3114   // For the purposes of the classification, we assume reference types
3115   // will bind to temporaries.
3116   QualType effCastType = castType;
3117   if (const ReferenceType *ref = castType->getAs<ReferenceType>())
3118     effCastType = ref->getPointeeType();
3119 
3120   ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
3121   ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
3122   if (exprACTC == castACTC) {
3123     // check for viablity and report error if casting an rvalue to a
3124     // life-time qualifier.
3125     if ((castACTC == ACTC_retainable) &&
3126         (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
3127         (castType != castExprType)) {
3128       const Type *DT = castType.getTypePtr();
3129       QualType QDT = castType;
3130       // We desugar some types but not others. We ignore those
3131       // that cannot happen in a cast; i.e. auto, and those which
3132       // should not be de-sugared; i.e typedef.
3133       if (const ParenType *PT = dyn_cast<ParenType>(DT))
3134         QDT = PT->desugar();
3135       else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
3136         QDT = TP->desugar();
3137       else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
3138         QDT = AT->desugar();
3139       if (QDT != castType &&
3140           QDT.getObjCLifetime() !=  Qualifiers::OCL_None) {
3141         SourceLocation loc =
3142           (castRange.isValid() ? castRange.getBegin()
3143                               : castExpr->getExprLoc());
3144         Diag(loc, diag::err_arc_nolifetime_behavior);
3145       }
3146     }
3147     return ACR_okay;
3148   }
3149 
3150   if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
3151 
3152   // Allow all of these types to be cast to integer types (but not
3153   // vice-versa).
3154   if (castACTC == ACTC_none && castType->isIntegralType(Context))
3155     return ACR_okay;
3156 
3157   // Allow casts between pointers to lifetime types (e.g., __strong id*)
3158   // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
3159   // must be explicit.
3160   if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
3161     return ACR_okay;
3162   if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
3163       CCK != CCK_ImplicitConversion)
3164     return ACR_okay;
3165 
3166   switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
3167   // For invalid casts, fall through.
3168   case ACC_invalid:
3169     break;
3170 
3171   // Do nothing for both bottom and +0.
3172   case ACC_bottom:
3173   case ACC_plusZero:
3174     return ACR_okay;
3175 
3176   // If the result is +1, consume it here.
3177   case ACC_plusOne:
3178     castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
3179                                         CK_ARCConsumeObject, castExpr,
3180                                         0, VK_RValue);
3181     ExprNeedsCleanups = true;
3182     return ACR_okay;
3183   }
3184 
3185   // If this is a non-implicit cast from id or block type to a
3186   // CoreFoundation type, delay complaining in case the cast is used
3187   // in an acceptable context.
3188   if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
3189       CCK != CCK_ImplicitConversion)
3190     return ACR_unbridged;
3191 
3192   diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3193                             castExpr, castExpr, exprACTC, CCK);
3194   return ACR_okay;
3195 }
3196 
3197 /// Given that we saw an expression with the ARCUnbridgedCastTy
3198 /// placeholder type, complain bitterly.
3199 void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3200   // We expect the spurious ImplicitCastExpr to already have been stripped.
3201   assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3202   CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3203 
3204   SourceRange castRange;
3205   QualType castType;
3206   CheckedConversionKind CCK;
3207 
3208   if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3209     castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3210     castType = cast->getTypeAsWritten();
3211     CCK = CCK_CStyleCast;
3212   } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3213     castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3214     castType = cast->getTypeAsWritten();
3215     CCK = CCK_OtherCast;
3216   } else {
3217     castType = cast->getType();
3218     CCK = CCK_ImplicitConversion;
3219   }
3220 
3221   ARCConversionTypeClass castACTC =
3222     classifyTypeForARCConversion(castType.getNonReferenceType());
3223 
3224   Expr *castExpr = realCast->getSubExpr();
3225   assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3226 
3227   diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3228                             castExpr, realCast, ACTC_retainable, CCK);
3229 }
3230 
3231 /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3232 /// type, remove the placeholder cast.
3233 Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3234   assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3235 
3236   if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3237     Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3238     return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3239   } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3240     assert(uo->getOpcode() == UO_Extension);
3241     Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3242     return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3243                                    sub->getValueKind(), sub->getObjectKind(),
3244                                        uo->getOperatorLoc());
3245   } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3246     assert(!gse->isResultDependent());
3247 
3248     unsigned n = gse->getNumAssocs();
3249     SmallVector<Expr*, 4> subExprs(n);
3250     SmallVector<TypeSourceInfo*, 4> subTypes(n);
3251     for (unsigned i = 0; i != n; ++i) {
3252       subTypes[i] = gse->getAssocTypeSourceInfo(i);
3253       Expr *sub = gse->getAssocExpr(i);
3254       if (i == gse->getResultIndex())
3255         sub = stripARCUnbridgedCast(sub);
3256       subExprs[i] = sub;
3257     }
3258 
3259     return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3260                                               gse->getControllingExpr(),
3261                                               subTypes, subExprs,
3262                                               gse->getDefaultLoc(),
3263                                               gse->getRParenLoc(),
3264                                        gse->containsUnexpandedParameterPack(),
3265                                               gse->getResultIndex());
3266   } else {
3267     assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3268     return cast<ImplicitCastExpr>(e)->getSubExpr();
3269   }
3270 }
3271 
3272 bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3273                                                  QualType exprType) {
3274   QualType canCastType =
3275     Context.getCanonicalType(castType).getUnqualifiedType();
3276   QualType canExprType =
3277     Context.getCanonicalType(exprType).getUnqualifiedType();
3278   if (isa<ObjCObjectPointerType>(canCastType) &&
3279       castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3280       canExprType->isObjCObjectPointerType()) {
3281     if (const ObjCObjectPointerType *ObjT =
3282         canExprType->getAs<ObjCObjectPointerType>())
3283       if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
3284         return !ObjI->isArcWeakrefUnavailable();
3285   }
3286   return true;
3287 }
3288 
3289 /// Look for an ObjCReclaimReturnedObject cast and destroy it.
3290 static Expr *maybeUndoReclaimObject(Expr *e) {
3291   // For now, we just undo operands that are *immediately* reclaim
3292   // expressions, which prevents the vast majority of potential
3293   // problems here.  To catch them all, we'd need to rebuild arbitrary
3294   // value-propagating subexpressions --- we can't reliably rebuild
3295   // in-place because of expression sharing.
3296   if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
3297     if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
3298       return ice->getSubExpr();
3299 
3300   return e;
3301 }
3302 
3303 ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
3304                                       ObjCBridgeCastKind Kind,
3305                                       SourceLocation BridgeKeywordLoc,
3306                                       TypeSourceInfo *TSInfo,
3307                                       Expr *SubExpr) {
3308   ExprResult SubResult = UsualUnaryConversions(SubExpr);
3309   if (SubResult.isInvalid()) return ExprError();
3310   SubExpr = SubResult.take();
3311 
3312   QualType T = TSInfo->getType();
3313   QualType FromType = SubExpr->getType();
3314 
3315   CastKind CK;
3316 
3317   bool MustConsume = false;
3318   if (T->isDependentType() || SubExpr->isTypeDependent()) {
3319     // Okay: we'll build a dependent expression type.
3320     CK = CK_Dependent;
3321   } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
3322     // Casting CF -> id
3323     CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
3324                                   : CK_CPointerToObjCPointerCast);
3325     switch (Kind) {
3326     case OBC_Bridge:
3327       break;
3328 
3329     case OBC_BridgeRetained: {
3330       bool br = isKnownName("CFBridgingRelease");
3331       Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3332         << 2
3333         << FromType
3334         << (T->isBlockPointerType()? 1 : 0)
3335         << T
3336         << SubExpr->getSourceRange()
3337         << Kind;
3338       Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3339         << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
3340       Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
3341         << FromType << br
3342         << FixItHint::CreateReplacement(BridgeKeywordLoc,
3343                                         br ? "CFBridgingRelease "
3344                                            : "__bridge_transfer ");
3345 
3346       Kind = OBC_Bridge;
3347       break;
3348     }
3349 
3350     case OBC_BridgeTransfer:
3351       // We must consume the Objective-C object produced by the cast.
3352       MustConsume = true;
3353       break;
3354     }
3355   } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
3356     // Okay: id -> CF
3357     CK = CK_BitCast;
3358     switch (Kind) {
3359     case OBC_Bridge:
3360       // Reclaiming a value that's going to be __bridge-casted to CF
3361       // is very dangerous, so we don't do it.
3362       SubExpr = maybeUndoReclaimObject(SubExpr);
3363       break;
3364 
3365     case OBC_BridgeRetained:
3366       // Produce the object before casting it.
3367       SubExpr = ImplicitCastExpr::Create(Context, FromType,
3368                                          CK_ARCProduceObject,
3369                                          SubExpr, 0, VK_RValue);
3370       break;
3371 
3372     case OBC_BridgeTransfer: {
3373       bool br = isKnownName("CFBridgingRetain");
3374       Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3375         << (FromType->isBlockPointerType()? 1 : 0)
3376         << FromType
3377         << 2
3378         << T
3379         << SubExpr->getSourceRange()
3380         << Kind;
3381 
3382       Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3383         << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
3384       Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
3385         << T << br
3386         << FixItHint::CreateReplacement(BridgeKeywordLoc,
3387                           br ? "CFBridgingRetain " : "__bridge_retained");
3388 
3389       Kind = OBC_Bridge;
3390       break;
3391     }
3392     }
3393   } else {
3394     Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
3395       << FromType << T << Kind
3396       << SubExpr->getSourceRange()
3397       << TSInfo->getTypeLoc().getSourceRange();
3398     return ExprError();
3399   }
3400 
3401   Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
3402                                                    BridgeKeywordLoc,
3403                                                    TSInfo, SubExpr);
3404 
3405   if (MustConsume) {
3406     ExprNeedsCleanups = true;
3407     Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
3408                                       0, VK_RValue);
3409   }
3410 
3411   return Result;
3412 }
3413 
3414 ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
3415                                       SourceLocation LParenLoc,
3416                                       ObjCBridgeCastKind Kind,
3417                                       SourceLocation BridgeKeywordLoc,
3418                                       ParsedType Type,
3419                                       SourceLocation RParenLoc,
3420                                       Expr *SubExpr) {
3421   TypeSourceInfo *TSInfo = 0;
3422   QualType T = GetTypeFromParser(Type, &TSInfo);
3423   if (!TSInfo)
3424     TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
3425   return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
3426                               SubExpr);
3427 }
3428