SemaExprObjC.cpp 91 KB

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